Previous 199869 Revisions Next

r40584 Thursday 3rd September, 2015 at 01:25:45 UTC by R. Belmont
Merge pull request #302 from JoakimLarsson/mz8105_1

New VME board: Mizar 8105
[/trunk].gitignore
[3rdparty/googletest].travis.yml* README.md* travis.sh*
[3rdparty/googletest/googlemock]CHANGES* CMakeLists.txt* CONTRIBUTORS* LICENSE* Makefile.am* README.md* configure.ac*
[3rdparty/googletest/googlemock/build-aux].keep*
[3rdparty/googletest/googlemock/docs]CheatSheet.md* CookBook.md* DesignDoc.md* DevGuide.md* Documentation.md* ForDummies.md* FrequentlyAskedQuestions.md* KnownIssues.md*
[3rdparty/googletest/googlemock/docs/v1_5]CheatSheet.md* CookBook.md* Documentation.md* ForDummies.md* FrequentlyAskedQuestions.md*
[3rdparty/googletest/googlemock/docs/v1_6]CheatSheet.md* CookBook.md* Documentation.md* ForDummies.md* FrequentlyAskedQuestions.md*
[3rdparty/googletest/googlemock/docs/v1_7]CheatSheet.md* CookBook.md* Documentation.md* ForDummies.md* FrequentlyAskedQuestions.md*
[3rdparty/googletest/googlemock/include/gmock]gmock-actions.h* gmock-cardinalities.h* gmock-generated-actions.h* gmock-generated-actions.h.pump* gmock-generated-function-mockers.h* gmock-generated-function-mockers.h.pump* gmock-generated-matchers.h* gmock-generated-matchers.h.pump* gmock-generated-nice-strict.h* gmock-generated-nice-strict.h.pump* gmock-matchers.h* gmock-more-actions.h* gmock-more-matchers.h* gmock-spec-builders.h* gmock.h*
[3rdparty/googletest/googlemock/include/gmock/internal]gmock-generated-internal-utils.h* gmock-generated-internal-utils.h.pump* gmock-internal-utils.h* gmock-port.h*
[3rdparty/googletest/googlemock/include/gmock/internal/custom]gmock-generated-actions.h* gmock-generated-actions.h.pump* gmock-matchers.h* gmock-port.h*
[3rdparty/googletest/googlemock/make]Makefile*
[3rdparty/googletest/googlemock/msvc/2005]gmock.sln* gmock.vcproj* gmock_config.vsprops* gmock_main.vcproj* gmock_test.vcproj*
[3rdparty/googletest/googlemock/msvc/2010]gmock.sln* gmock.vcxproj* gmock_config.props* gmock_main.vcxproj* gmock_test.vcxproj*
[3rdparty/googletest/googlemock/scripts]fuse_gmock_files.py* gmock-config.in* gmock_doctor.py* upload.py* upload_gmock.py*
[3rdparty/googletest/googlemock/scripts/generator]LICENSE* README* README.cppclean* gmock_gen.py*
[3rdparty/googletest/googlemock/scripts/generator/cpp]__init__.py* ast.py* gmock_class.py* gmock_class_test.py* keywords.py* tokenize.py* utils.py*
[3rdparty/googletest/googlemock/src]gmock-all.cc* gmock-cardinalities.cc* gmock-internal-utils.cc* gmock-matchers.cc* gmock-spec-builders.cc* gmock.cc* gmock_main.cc*
[3rdparty/googletest/googlemock/test]gmock-actions_test.cc* gmock-cardinalities_test.cc* gmock-generated-actions_test.cc* gmock-generated-function-mockers_test.cc* gmock-generated-internal-utils_test.cc* gmock-generated-matchers_test.cc* gmock-internal-utils_test.cc* gmock-matchers_test.cc* gmock-more-actions_test.cc* gmock-nice-strict_test.cc* gmock-port_test.cc* gmock-spec-builders_test.cc* gmock_all_test.cc* gmock_ex_test.cc* gmock_leak_test.py* gmock_leak_test_.cc* gmock_link2_test.cc* gmock_link_test.cc* gmock_link_test.h* gmock_output_test.py* gmock_output_test_.cc* gmock_output_test_golden.txt* gmock_stress_test.cc* gmock_test.cc* gmock_test_utils.py*
[3rdparty/googletest/googletest]CHANGES* CMakeLists.txt* CONTRIBUTORS* LICENSE* Makefile.am* README.md* configure.ac*
[3rdparty/googletest/googletest/build-aux].keep*
[3rdparty/googletest/googletest/cmake]internal_utils.cmake*
[3rdparty/googletest/googletest/codegear]gtest.cbproj* gtest.groupproj* gtest_all.cc* gtest_link.cc* gtest_main.cbproj* gtest_unittest.cbproj*
[3rdparty/googletest/googletest/docs]AdvancedGuide.md* DevGuide.md* Documentation.md* FAQ.md* Primer.md* PumpManual.md* Samples.md* V1_5_AdvancedGuide.md* V1_5_Documentation.md* V1_5_FAQ.md* V1_5_Primer.md* V1_5_PumpManual.md* V1_5_XcodeGuide.md* V1_6_AdvancedGuide.md* V1_6_Documentation.md* V1_6_FAQ.md* V1_6_Primer.md* V1_6_PumpManual.md* V1_6_Samples.md* V1_6_XcodeGuide.md* V1_7_AdvancedGuide.md* V1_7_Documentation.md* V1_7_FAQ.md* V1_7_Primer.md* V1_7_PumpManual.md* V1_7_Samples.md* V1_7_XcodeGuide.md* XcodeGuide.md*
[3rdparty/googletest/googletest/include/gtest]gtest-death-test.h* gtest-message.h* gtest-param-test.h* gtest-param-test.h.pump* gtest-printers.h* gtest-spi.h* gtest-test-part.h* gtest-typed-test.h* gtest.h* gtest_pred_impl.h* gtest_prod.h*
[3rdparty/googletest/googletest/include/gtest/internal]gtest-death-test-internal.h* gtest-filepath.h* gtest-internal.h* gtest-linked_ptr.h* gtest-param-util-generated.h* gtest-param-util-generated.h.pump* gtest-param-util.h* gtest-port-arch.h* gtest-port.h* gtest-string.h* gtest-tuple.h* gtest-tuple.h.pump* gtest-type-util.h* gtest-type-util.h.pump*
[3rdparty/googletest/googletest/include/gtest/internal/custom]gtest-port.h* gtest-printers.h* gtest.h*
[3rdparty/googletest/googletest/m4]acx_pthread.m4* gtest.m4*
[3rdparty/googletest/googletest/make]Makefile*
[3rdparty/googletest/googletest/msvc]gtest-md.sln* gtest-md.vcproj* gtest.sln* gtest.vcproj* gtest_main-md.vcproj* gtest_main.vcproj* gtest_prod_test-md.vcproj* gtest_prod_test.vcproj* gtest_unittest-md.vcproj* gtest_unittest.vcproj*
[3rdparty/googletest/googletest/samples]prime_tables.h* sample1.cc* sample1.h* sample10_unittest.cc* sample1_unittest.cc* sample2.cc* sample2.h* sample2_unittest.cc* sample3-inl.h* sample3_unittest.cc* sample4.cc* sample4.h* sample4_unittest.cc* sample5_unittest.cc* sample6_unittest.cc* sample7_unittest.cc* sample8_unittest.cc* sample9_unittest.cc*
[3rdparty/googletest/googletest/scripts]common.py* fuse_gtest_files.py* gen_gtest_pred_impl.py* gtest-config.in* pump.py* release_docs.py* upload.py* upload_gtest.py*
[3rdparty/googletest/googletest/scripts/test]Makefile*
[3rdparty/googletest/googletest/src]gtest-all.cc* gtest-death-test.cc* gtest-filepath.cc* gtest-internal-inl.h* gtest-port.cc* gtest-printers.cc* gtest-test-part.cc* gtest-typed-test.cc* gtest.cc* gtest_main.cc*
[3rdparty/googletest/googletest/test]gtest-death-test_ex_test.cc* gtest-death-test_test.cc* gtest-filepath_test.cc* gtest-linked_ptr_test.cc* gtest-listener_test.cc* gtest-message_test.cc* gtest-options_test.cc* gtest-param-test2_test.cc* gtest-param-test_test.cc* gtest-param-test_test.h* gtest-port_test.cc* gtest-printers_test.cc* gtest-test-part_test.cc* gtest-tuple_test.cc* gtest-typed-test2_test.cc* gtest-typed-test_test.cc* gtest-typed-test_test.h* gtest-unittest-api_test.cc* gtest_all_test.cc* gtest_break_on_failure_unittest.py* gtest_break_on_failure_unittest_.cc* gtest_catch_exceptions_test.py* gtest_catch_exceptions_test_.cc* gtest_color_test.py* gtest_color_test_.cc* gtest_env_var_test.py* gtest_env_var_test_.cc* gtest_environment_test.cc* gtest_filter_unittest.py* gtest_filter_unittest_.cc* gtest_help_test.py* gtest_help_test_.cc* gtest_list_tests_unittest.py* gtest_list_tests_unittest_.cc* gtest_main_unittest.cc* gtest_no_test_unittest.cc* gtest_output_test.py* gtest_output_test_.cc* gtest_output_test_golden_lin.txt* gtest_pred_impl_unittest.cc* gtest_premature_exit_test.cc* gtest_prod_test.cc* gtest_repeat_test.cc* gtest_shuffle_test.py* gtest_shuffle_test_.cc* gtest_sole_header_test.cc* gtest_stress_test.cc* gtest_test_utils.py* gtest_throw_on_failure_ex_test.cc* gtest_throw_on_failure_test.py* gtest_throw_on_failure_test_.cc* gtest_uninitialized_test.py* gtest_uninitialized_test_.cc* gtest_unittest.cc* gtest_xml_outfile1_test_.cc* gtest_xml_outfile2_test_.cc* gtest_xml_outfiles_test.py* gtest_xml_output_unittest.py* gtest_xml_output_unittest_.cc* gtest_xml_test_utils.py* production.cc* production.h*
[3rdparty/googletest/googletest/xcode/Config]DebugProject.xcconfig* FrameworkTarget.xcconfig* General.xcconfig* ReleaseProject.xcconfig* StaticLibraryTarget.xcconfig* TestTarget.xcconfig*
[3rdparty/googletest/googletest/xcode/Resources]Info.plist*
[3rdparty/googletest/googletest/xcode/Samples/FrameworkSample]Info.plist* runtests.sh* widget.cc* widget.h* widget_test.cc*
[3rdparty/googletest/googletest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj]project.pbxproj*
[3rdparty/googletest/googletest/xcode/Scripts]runtests.sh* versiongenerate.py*
[3rdparty/googletest/googletest/xcode/gtest.xcodeproj]project.pbxproj*
[3rdparty/unittest-cpp].gitattributes .gitignore .gitmodules AUTHORS CMakeLists.txt ChangeLog INSTALL LICENSE Makefile.am README.md UnitTest++ configure.ac
[3rdparty/unittest-cpp/UnitTest++]AssertException.cpp AssertException.h CheckMacros.h Checks.cpp Checks.h CompositeTestReporter.cpp CompositeTestReporter.h Config.h CurrentTest.cpp CurrentTest.h DeferredTestReporter.cpp DeferredTestReporter.h DeferredTestResult.cpp DeferredTestResult.h ExceptionMacros.h ExecuteTest.h HelperMacros.h Makefile.am MemoryOutStream.cpp MemoryOutStream.h Posix ReportAssert.cpp ReportAssert.h ReportAssertImpl.h Test.cpp Test.h TestDetails.cpp TestDetails.h TestList.cpp TestList.h TestMacros.h TestReporter.cpp TestReporter.h TestReporterStdout.cpp TestReporterStdout.h TestResults.cpp TestResults.h TestRunner.cpp TestRunner.h TestSuite.h TimeConstraint.cpp TimeConstraint.h TimeHelpers.h UnitTest++.h UnitTestPP.h Win32 XmlTestReporter.cpp XmlTestReporter.h unittestpp_vs2005.vcproj unittestpp_vs2008.vcproj
[3rdparty/unittest-cpp/UnitTest++/Posix]SignalTranslator.cpp SignalTranslator.h TimeHelpers.cpp TimeHelpers.h
[3rdparty/unittest-cpp/UnitTest++/Win32]TimeHelpers.cpp TimeHelpers.h
[3rdparty/unittest-cpp/builds].gitignore
[3rdparty/unittest-cpp/docs]Building-Using-CMake.md Home.md Macro-Reference.md Writing-More-Tests-With-the-Bowling-Game-Kata.md Writing-and-Running-Your-First-Test.md
[3rdparty/unittest-cpp/tests]Main.cpp RecordingReporter.h ScopedCurrentTest.h TestAssertHandler.cpp TestCheckMacros.cpp TestChecks.cpp TestCompositeTestReporter.cpp TestCurrentTest.cpp TestDeferredTestReporter.cpp TestExceptions.cpp TestMemoryOutStream.cpp TestTest.cpp TestTestList.cpp TestTestMacros.cpp TestTestResults.cpp TestTestRunner.cpp TestTestSuite.cpp TestTimeConstraint.cpp TestTimeConstraintMacro.cpp TestUnitTestPP.cpp TestXmlTestReporter.cpp
[hash]a800_flop.xml c64_flop.xml megadriv.xml x1_cass.xml
[scripts]genie.lua
[scripts/src]3rdparty.lua tests.lua
[scripts/target/mame]mess.lua
[src/emu/bus/centronics]printer.c
[src/emu/bus/pc_kbd]iskr1030.c iskr1030.h
[src/emu/cpu/t11]t11.c t11.h
[src/emu/drivers]emudummy.c
[src/emu/machine]68230pit.c 68230pit.h at_keybc.c at_keybc.h
[src/emu/netlist]nl_base.h nl_setup.h
[src/emu/netlist/plib]pstring.c pstring.h
[src/emu/netlist/solver]nld_solver.h
[src/emu/sound]c352.c c352.h l7a1045_l6028_dsp_a.c l7a1045_l6028_dsp_a.h tms5110.c tms5110.h tms5220.c tms5220.h
[src/emu/video]poly.h polylgcy.h
[src/mame]arcade.lst mess.lst
[src/mame/audio]hng64.c
[src/mame/drivers]cps1.c deco32.c fcrash.c galastrm.c groundfx.c hng64.c lethalj.c midxunit.c model2.c model3.c namcofl.c namconb1.c namcond1.c namcos11.c namcos12.c namcos22.c namcos23.c quantum.c yunsun16.c zaccaria.c
[src/mame/includes]chihiro.h galastrm.h hng64.h model2.h model3.h
[src/mame/machine]hng64_net.c model3.c namco62.c namco62.h xbox.c
[src/mame/video]chihiro.c deco16ic.c galastrm.c hng64.c hng64_sprite.c midzeus2.c model2.c model2rd.inc model3.c namcos22.c
[src/mess/drivers]asst128.c at.c besta.c canon_s80.c* dvk_kcgd.c* force68k.c mc1000.c mk85.c mk90.c tispeak.c uknc.c
[src/mess/layout]fccpu1.lay*
[src/osd/modules/debugger/win]debugviewinfo.c debugwininfo.c editwininfo.c
[src/osd/windows]input.c output.c window.c winmain.c winutil.c winutil.h
[tests]main.c
[tests/lib/util]corestr.c

trunk/.gitignore
r249095r249096
11*~
22/*
3!/*/
3/*/
4!/3rdparty/
5!/artwork/
6!/docs/
7!/hash/
8!/hlsl/
9!/keymaps/
10!/nl_examples/
11!/samples/
12!/scripts/
13!/src/
14!/tests/
15!/web/
416!/.gitattributes
517!/.gitignore
618!/.travis.yml
719!/makefile
8!/mame.doxygen
20!/mame.doxygen
921!/*.md
10/cfg
11/diff
12/ini
13/inp
14/nvram
15/obj
16/roms
17/snap
1822src/regtests/chdman/temp
1923src/regtests/jedutil/output
20/sta
21*.pyc
22/build
23/documentation
No newline at end of file
24*.pyc
No newline at end of file
trunk/3rdparty/googletest/.travis.yml
r0r249096
1# Build matrix / environment variable are explained on:
2# http://about.travis-ci.org/docs/user/build-configuration/
3# This file can be validated on:
4# http://lint.travis-ci.org/
5# See also
6# http://stackoverflow.com/questions/22111549/travis-ci-with-clang-3-4-and-c11/30925448#30925448
7# to allow C++11, though we are not yet building with -std=c++11
8
9install:
10# /usr/bin/gcc is 4.6 always, but gcc-X.Y is available.
11- if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi
12# /usr/bin/clang is our version already, and clang-X.Y does not exist.
13#- if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.7" CC="clang-3.7"; fi
14- echo ${PATH}
15- ls /usr/local
16- ls /usr/local/bin
17- export PATH=/usr/local/bin:/usr/bin:${PATH}
18- echo ${CXX}
19- ${CXX} --version
20addons:
21  apt:
22    sources:
23    - ubuntu-toolchain-r-test
24    packages:
25    - gcc-4.9
26    - g++-4.9
27    - clang
28    - valgrind
29os:
30  - linux
31  - osx
32language: cpp
33compiler:
34  - gcc
35  - clang
36script: ./travis.sh
37env:
38  matrix:
39    - GTEST_TARGET=googletest SHARED_LIB=OFF STATIC_LIB=ON CMAKE_PKG=OFF BUILD_TYPE=debug   VERBOSE_MAKE=true VERBOSE
40    - GTEST_TARGET=googlemock SHARED_LIB=OFF STATIC_LIB=ON CMAKE_PKG=OFF BUILD_TYPE=debug   VERBOSE_MAKE=true VERBOSE
41#    - GTEST_TARGET=googletest SHARED_LIB=ON  STATIC_LIB=ON CMAKE_PKG=ON  BUILD_TYPE=release VERBOSE_MAKE=false
42#    - GTEST_TARGET=googlemock SHARED_LIB=ON  STATIC_LIB=ON CMAKE_PKG=ON  BUILD_TYPE=release VERBOSE_MAKE=false
43notifications:
44  email: false
45sudo: false
trunk/3rdparty/googletest/README.md
r0r249096
1
2# Google Test #
3
4[![Build Status](https://travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest)
5
6Welcome to **Google Test**, Google's C++ test framework!
7
8This repository is a merger of the formerly separate GoogleTest and
9GoogleMock projects. These were so closely related that it makes sense to
10maintain and release them together.
11
12Please see the project page above for more information as well as the
13mailing list for questions, discussions, and development.  There is
14also an IRC channel on OFTC (irc.oftc.net) #gtest available.  Please
15join us!
16
17**Google Mock** is an extension to Google Test for writing and using C++ mock
18classes.  See the separate [Google Mock documentation](googlemock/README.md).
19
20More detailed documentation for googletest (including build instructions) are
21in its interior [googletest/README.md](googletest/README.md) file.
22
23## Features ##
24
25  * An [XUnit](https://en.wikipedia.org/wiki/XUnit) test framework.
26  * Test discovery.
27  * A rich set of assertions.
28  * User-defined assertions.
29  * Death tests.
30  * Fatal and non-fatal failures.
31  * Value-parameterized tests.
32  * Type-parameterized tests.
33  * Various options for running the tests.
34  * XML test report generation.
35
36## Platforms ##
37
38Google test has been used on a variety of platforms:
39
40  * Linux
41  * Mac OS X
42  * Windows
43  * Cygwin
44  * MinGW
45  * Windows Mobile
46  * Symbian
47
48## Who Is Using Google Test? ##
49
50In addition to many internal projects at Google, Google Test is also used by
51the following notable projects:
52
53  * The [Chromium projects](http://www.chromium.org/) (behind the Chrome
54    browser and Chrome OS).
55  * The [LLVM](http://llvm.org/) compiler.
56  * [Protocol Buffers](http://code.google.com/p/protobuf/), Google's data
57    interchange format.
58  * The [OpenCV](http://opencv.org/) computer vision library.
59
60## Related Open Source Projects ##
61
62[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that runs
63your test binary, allows you to track its progress via a progress bar, and
64displays a list of test failures. Clicking on one shows failure text. Google
65Test UI is written in C#.
66
67[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event
68listener for Google Test that implements the
69[TAP protocol](http://en.wikipedia.org/wiki/Test_Anything_Protocol) for test
70result output. If your test runner understands TAP, you may find it useful.
71
72## Requirements ##
73
74Google Test is designed to have fairly minimal requirements to build
75and use with your projects, but there are some.  Currently, we support
76Linux, Windows, Mac OS X, and Cygwin.  We will also make our best
77effort to support other platforms (e.g. Solaris, AIX, and z/OS).
78However, since core members of the Google Test project have no access
79to these platforms, Google Test may have outstanding issues there.  If
80you notice any problems on your platform, please notify
81<googletestframework@googlegroups.com>. Patches for fixing them are
82even more welcome!
83
84### Linux Requirements ###
85
86These are the base requirements to build and use Google Test from a source
87package (as described below):
88
89  * GNU-compatible Make or gmake
90  * POSIX-standard shell
91  * POSIX(-2) Regular Expressions (regex.h)
92  * A C++98-standard-compliant compiler
93
94### Windows Requirements ###
95
96  * Microsoft Visual C++ v7.1 or newer
97
98### Cygwin Requirements ###
99
100  * Cygwin v1.5.25-14 or newer
101
102### Mac OS X Requirements ###
103
104  * Mac OS X v10.4 Tiger or newer
105  * XCode Developer Tools
106
107### Requirements for Contributors ###
108
109We welcome patches.  If you plan to contribute a patch, you need to
110build Google Test and its own tests from a git checkout (described
111below), which has further requirements:
112
113  * [Python](http://python.org/) v2.3 or newer (for running some of
114    the tests and re-generating certain source files from templates)
115  * [CMake](http://www.cmake.org/) v2.6.4 or newer
116
117## Regenerating Source Files ##
118
119Some of Google Test's source files are generated from templates (not
120in the C++ sense) using a script.
121For example, the
122file include/gtest/internal/gtest-type-util.h.pump is used to generate
123gtest-type-util.h in the same directory.
124
125You don't need to worry about regenerating the source files
126unless you need to modify them.  You would then modify the
127corresponding `.pump` files and run the '[pump.py](googletest/scripts/pump.py)'
128generator script.  See the [Pump Manual](googletest/docs/PumpManual.md).
129
130### Contributing Code ###
131
132We welcome patches.  Please read the
133[Developer's Guide](googletest/docs/DevGuide.md)
134for how you can contribute. In particular, make sure you have signed
135the Contributor License Agreement, or we won't be able to accept the
136patch.
137
138Happy testing!
trunk/3rdparty/googletest/googlemock/CHANGES
r0r249096
1Changes for 1.7.0:
2
3* All new improvements in Google Test 1.7.0.
4* New feature: matchers DoubleNear(), FloatNear(),
5  NanSensitiveDoubleNear(), NanSensitiveFloatNear(),
6  UnorderedElementsAre(), UnorderedElementsAreArray(), WhenSorted(),
7  WhenSortedBy(), IsEmpty(), and SizeIs().
8* Improvement: Google Mock can now be built as a DLL.
9* Improvement: when compiled by a C++11 compiler, matchers AllOf()
10  and AnyOf() can accept an arbitrary number of matchers.
11* Improvement: when compiled by a C++11 compiler, matchers
12  ElementsAreArray() can accept an initializer list.
13* Improvement: when exceptions are enabled, a mock method with no
14  default action now throws instead crashing the test.
15* Improvement: added class testing::StringMatchResultListener to aid
16  definition of composite matchers.
17* Improvement: function return types used in MOCK_METHOD*() macros can
18  now contain unprotected commas.
19* Improvement (potentially breaking): EXPECT_THAT() and ASSERT_THAT()
20  are now more strict in ensuring that the value type and the matcher
21  type are compatible, catching potential bugs in tests.
22* Improvement: Pointee() now works on an optional<T>.
23* Improvement: the ElementsAreArray() matcher can now take a vector or
24  iterator range as input, and makes a copy of its input elements
25  before the conversion to a Matcher.
26* Improvement: the Google Mock Generator can now generate mocks for
27  some class templates.
28* Bug fix: mock object destruction triggerred by another mock object's
29  destruction no longer hangs.
30* Improvement: Google Mock Doctor works better with newer Clang and
31  GCC now.
32* Compatibility fixes.
33* Bug/warning fixes.
34
35Changes for 1.6.0:
36
37* Compilation is much faster and uses much less memory, especially
38  when the constructor and destructor of a mock class are moved out of
39  the class body.
40* New matchers: Pointwise(), Each().
41* New actions: ReturnPointee() and ReturnRefOfCopy().
42* CMake support.
43* Project files for Visual Studio 2010.
44* AllOf() and AnyOf() can handle up-to 10 arguments now.
45* Google Mock doctor understands Clang error messages now.
46* SetArgPointee<> now accepts string literals.
47* gmock_gen.py handles storage specifier macros and template return
48  types now.
49* Compatibility fixes.
50* Bug fixes and implementation clean-ups.
51* Potentially incompatible changes: disables the harmful 'make install'
52  command in autotools.
53
54Potentially breaking changes:
55
56* The description string for MATCHER*() changes from Python-style
57  interpolation to an ordinary C++ string expression.
58* SetArgumentPointee is deprecated in favor of SetArgPointee.
59* Some non-essential project files for Visual Studio 2005 are removed.
60
61Changes for 1.5.0:
62
63 * New feature: Google Mock can be safely used in multi-threaded tests
64   on platforms having pthreads.
65 * New feature: function for printing a value of arbitrary type.
66 * New feature: function ExplainMatchResult() for easy definition of
67   composite matchers.
68 * The new matcher API lets user-defined matchers generate custom
69   explanations more directly and efficiently.
70 * Better failure messages all around.
71 * NotNull() and IsNull() now work with smart pointers.
72 * Field() and Property() now work when the matcher argument is a pointer
73   passed by reference.
74 * Regular expression matchers on all platforms.
75 * Added GCC 4.0 support for Google Mock Doctor.
76 * Added gmock_all_test.cc for compiling most Google Mock tests
77   in a single file.
78 * Significantly cleaned up compiler warnings.
79 * Bug fixes, better test coverage, and implementation clean-ups.
80
81 Potentially breaking changes:
82
83 * Custom matchers defined using MatcherInterface or MakePolymorphicMatcher()
84   need to be updated after upgrading to Google Mock 1.5.0; matchers defined
85   using MATCHER or MATCHER_P* aren't affected.
86 * Dropped support for 'make install'.
87
88Changes for 1.4.0 (we skipped 1.2.* and 1.3.* to match the version of
89Google Test):
90
91 * Works in more environments: Symbian and minGW, Visual C++ 7.1.
92 * Lighter weight: comes with our own implementation of TR1 tuple (no
93   more dependency on Boost!).
94 * New feature: --gmock_catch_leaked_mocks for detecting leaked mocks.
95 * New feature: ACTION_TEMPLATE for defining templatized actions.
96 * New feature: the .After() clause for specifying expectation order.
97 * New feature: the .With() clause for for specifying inter-argument
98   constraints.
99 * New feature: actions ReturnArg<k>(), ReturnNew<T>(...), and
100   DeleteArg<k>().
101 * New feature: matchers Key(), Pair(), Args<...>(), AllArgs(), IsNull(),
102   and Contains().
103 * New feature: utility class MockFunction<F>, useful for checkpoints, etc.
104 * New feature: functions Value(x, m) and SafeMatcherCast<T>(m).
105 * New feature: copying a mock object is rejected at compile time.
106 * New feature: a script for fusing all Google Mock and Google Test
107   source files for easy deployment.
108 * Improved the Google Mock doctor to diagnose more diseases.
109 * Improved the Google Mock generator script.
110 * Compatibility fixes for Mac OS X and gcc.
111 * Bug fixes and implementation clean-ups.
112
113Changes for 1.1.0:
114
115 * New feature: ability to use Google Mock with any testing framework.
116 * New feature: macros for easily defining new matchers
117 * New feature: macros for easily defining new actions.
118 * New feature: more container matchers.
119 * New feature: actions for accessing function arguments and throwing
120   exceptions.
121 * Improved the Google Mock doctor script for diagnosing compiler errors.
122 * Bug fixes and implementation clean-ups.
123
124Changes for 1.0.0:
125
126 * Initial Open Source release of Google Mock
trunk/3rdparty/googletest/googlemock/CMakeLists.txt
r0r249096
1########################################################################
2# CMake build script for Google Mock.
3#
4# To run the tests for Google Mock itself on Linux, use 'make test' or
5# ctest.  You can select which tests to run using 'ctest -R regex'.
6# For more options, run 'ctest --help'.
7
8# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
9# make it prominent in the GUI.
10option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
11
12option(gmock_build_tests "Build all of Google Mock's own tests." OFF)
13
14# A directory to find Google Test sources.
15if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt")
16  set(gtest_dir gtest)
17else()
18  set(gtest_dir ../googletest)
19endif()
20
21# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().
22include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL)
23
24if (COMMAND pre_project_set_up_hermetic_build)
25  # Google Test also calls hermetic setup functions from add_subdirectory,
26  # although its changes will not affect things at the current scope.
27  pre_project_set_up_hermetic_build()
28endif()
29
30########################################################################
31#
32# Project-wide settings
33
34# Name of the project.
35#
36# CMake files in this project can refer to the root source directory
37# as ${gmock_SOURCE_DIR} and to the root binary directory as
38# ${gmock_BINARY_DIR}.
39# Language "C" is required for find_package(Threads).
40project(gmock CXX C)
41cmake_minimum_required(VERSION 2.6.2)
42
43if (COMMAND set_up_hermetic_build)
44  set_up_hermetic_build()
45endif()
46
47# Instructs CMake to process Google Test's CMakeLists.txt and add its
48# targets to the current scope.  We are placing Google Test's binary
49# directory in a subdirectory of our own as VC compilation may break
50# if they are the same (the default).
51add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/gtest")
52
53# Although Google Test's CMakeLists.txt calls this function, the
54# changes there don't affect the current scope.  Therefore we have to
55# call it again here.
56config_compiler_and_linker()  # from ${gtest_dir}/cmake/internal_utils.cmake
57
58# Adds Google Mock's and Google Test's header directories to the search path.
59include_directories("${gmock_SOURCE_DIR}/include"
60                    "${gmock_SOURCE_DIR}"
61                    "${gtest_SOURCE_DIR}/include"
62                    # This directory is needed to build directly from Google
63                    # Test sources.
64                    "${gtest_SOURCE_DIR}")
65
66# Summary of tuple support for Microsoft Visual Studio:
67# Compiler    version(MS)  version(cmake)  Support
68# ----------  -----------  --------------  -----------------------------
69# <= VS 2010  <= 10        <= 1600         Use Google Tests's own tuple.
70# VS 2012     11           1700            std::tr1::tuple + _VARIADIC_MAX=10
71# VS 2013     12           1800            std::tr1::tuple
72if (MSVC AND MSVC_VERSION EQUAL 1700)
73  add_definitions(/D _VARIADIC_MAX=10)
74endif()
75
76########################################################################
77#
78# Defines the gmock & gmock_main libraries.  User tests should link
79# with one of them.
80
81# Google Mock libraries.  We build them using more strict warnings than what
82# are used for other targets, to ensure that Google Mock can be compiled by
83# a user aggressive about warnings.
84cxx_library(gmock
85            "${cxx_strict}"
86            "${gtest_dir}/src/gtest-all.cc"
87            src/gmock-all.cc)
88
89cxx_library(gmock_main
90            "${cxx_strict}"
91            "${gtest_dir}/src/gtest-all.cc"
92            src/gmock-all.cc
93            src/gmock_main.cc)
94
95########################################################################
96#
97# Google Mock's own tests.
98#
99# You can skip this section if you aren't interested in testing
100# Google Mock itself.
101#
102# The tests are not built by default.  To build them, set the
103# gmock_build_tests option to ON.  You can do it by running ccmake
104# or specifying the -Dgmock_build_tests=ON flag when running cmake.
105
106if (gmock_build_tests)
107  # This must be set in the root directory for the tests to be run by
108  # 'make test' or ctest.
109  enable_testing()
110
111  ############################################################
112  # C++ tests built with standard compiler flags.
113
114  cxx_test(gmock-actions_test gmock_main)
115  cxx_test(gmock-cardinalities_test gmock_main)
116  cxx_test(gmock_ex_test gmock_main)
117  cxx_test(gmock-generated-actions_test gmock_main)
118  cxx_test(gmock-generated-function-mockers_test gmock_main)
119  cxx_test(gmock-generated-internal-utils_test gmock_main)
120  cxx_test(gmock-generated-matchers_test gmock_main)
121  cxx_test(gmock-internal-utils_test gmock_main)
122  cxx_test(gmock-matchers_test gmock_main)
123  cxx_test(gmock-more-actions_test gmock_main)
124  cxx_test(gmock-nice-strict_test gmock_main)
125  cxx_test(gmock-port_test gmock_main)
126  cxx_test(gmock-spec-builders_test gmock_main)
127  cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc)
128  cxx_test(gmock_test gmock_main)
129
130  if (CMAKE_USE_PTHREADS_INIT)
131    cxx_test(gmock_stress_test gmock)
132  endif()
133
134  # gmock_all_test is commented to save time building and running tests.
135  # Uncomment if necessary.
136  # cxx_test(gmock_all_test gmock_main)
137
138  ############################################################
139  # C++ tests built with non-standard compiler flags.
140
141  cxx_library(gmock_main_no_exception "${cxx_no_exception}"
142    "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
143
144  cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
145    "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
146
147  if (NOT MSVC OR MSVC_VERSION LESS 1600)  # 1600 is Visual Studio 2010.
148    # Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that
149    # conflict with our own definitions. Therefore using our own tuple does not
150    # work on those compilers.
151    cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}"
152      "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
153
154    cxx_test_with_flags(gmock_use_own_tuple_test "${cxx_use_own_tuple}"
155      gmock_main_use_own_tuple test/gmock-spec-builders_test.cc)
156  endif()
157
158  cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}"
159    gmock_main_no_exception test/gmock-more-actions_test.cc)
160
161  cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}"
162    gmock_main_no_rtti test/gmock-spec-builders_test.cc)
163
164  cxx_shared_library(shared_gmock_main "${cxx_default}"
165    "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
166
167  # Tests that a binary can be built with Google Mock as a shared library.  On
168  # some system configurations, it may not possible to run the binary without
169  # knowing more details about the system configurations. We do not try to run
170  # this binary. To get a more robust shared library coverage, configure with
171  # -DBUILD_SHARED_LIBS=ON.
172  cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}"
173    shared_gmock_main test/gmock-spec-builders_test.cc)
174  set_target_properties(shared_gmock_test_
175    PROPERTIES
176    COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
177
178  ############################################################
179  # Python tests.
180
181  cxx_executable(gmock_leak_test_ test gmock_main)
182  py_test(gmock_leak_test)
183
184  cxx_executable(gmock_output_test_ test gmock)
185  py_test(gmock_output_test)
186endif()
trunk/3rdparty/googletest/googlemock/CONTRIBUTORS
r0r249096
1# This file contains a list of people who've made non-trivial
2# contribution to the Google C++ Mocking Framework project.  People
3# who commit code to the project are encouraged to add their names
4# here.  Please keep the list sorted by first names.
5
6Benoit Sigoure <tsuna@google.com>
7Bogdan Piloca <boo@google.com>
8Chandler Carruth <chandlerc@google.com>
9Dave MacLachlan <dmaclach@gmail.com>
10David Anderson <danderson@google.com>
11Dean Sturtevant
12Gene Volovich <gv@cite.com>
13Hal Burch <gmock@hburch.com>
14Jeffrey Yasskin <jyasskin@google.com>
15Jim Keller <jimkeller@google.com>
16Joe Walnes <joe@truemesh.com>
17Jon Wray <jwray@google.com>
18Keir Mierle <mierle@gmail.com>
19Keith Ray <keith.ray@gmail.com>
20Kostya Serebryany <kcc@google.com>
21Lev Makhlis
22Manuel Klimek <klimek@google.com>
23Mario Tanev <radix@google.com>
24Mark Paskin
25Markus Heule <markus.heule@gmail.com>
26Matthew Simmons <simmonmt@acm.org>
27Mike Bland <mbland@google.com>
28Neal Norwitz <nnorwitz@gmail.com>
29Nermin Ozkiranartli <nermin@google.com>
30Owen Carlsen <ocarlsen@google.com>
31Paneendra Ba <paneendra@google.com>
32Paul Menage <menage@google.com>
33Piotr Kaminski <piotrk@google.com>
34Russ Rufer <russ@pentad.com>
35Sverre Sundsdal <sundsdal@gmail.com>
36Takeshi Yoshino <tyoshino@google.com>
37Vadim Berman <vadimb@google.com>
38Vlad Losev <vladl@google.com>
39Wolfgang Klier <wklier@google.com>
40Zhanyong Wan <wan@google.com>
trunk/3rdparty/googletest/googlemock/LICENSE
r0r249096
1Copyright 2008, Google Inc.
2All rights reserved.
3
4Redistribution and use in source and binary forms, with or without
5modification, are permitted provided that the following conditions are
6met:
7
8    * Redistributions of source code must retain the above copyright
9notice, this list of conditions and the following disclaimer.
10    * Redistributions in binary form must reproduce the above
11copyright notice, this list of conditions and the following disclaimer
12in the documentation and/or other materials provided with the
13distribution.
14    * Neither the name of Google Inc. nor the names of its
15contributors may be used to endorse or promote products derived from
16this software without specific prior written permission.
17
18THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
trunk/3rdparty/googletest/googlemock/Makefile.am
r0r249096
1# Automake file
2
3# Nonstandard package files for distribution.
4EXTRA_DIST = LICENSE
5
6# We may need to build our internally packaged gtest. If so, it will be
7# included in the 'subdirs' variable.
8SUBDIRS = $(subdirs)
9
10# This is generated by the configure script, so clean it for distribution.
11DISTCLEANFILES = scripts/gmock-config
12
13# We define the global AM_CPPFLAGS as everything we compile includes from these
14# directories.
15AM_CPPFLAGS = $(GTEST_CPPFLAGS) -I$(srcdir)/include
16
17# Modifies compiler and linker flags for pthreads compatibility.
18if HAVE_PTHREADS
19  AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1
20  AM_LIBS = @PTHREAD_LIBS@
21endif
22
23# Build rules for libraries.
24lib_LTLIBRARIES = lib/libgmock.la lib/libgmock_main.la
25
26lib_libgmock_la_SOURCES = src/gmock-all.cc
27
28pkginclude_HEADERS = \
29  include/gmock/gmock-actions.h \
30  include/gmock/gmock-cardinalities.h \
31  include/gmock/gmock-generated-actions.h \
32  include/gmock/gmock-generated-function-mockers.h \
33  include/gmock/gmock-generated-matchers.h \
34  include/gmock/gmock-generated-nice-strict.h \
35  include/gmock/gmock-matchers.h \
36  include/gmock/gmock-more-actions.h \
37  include/gmock/gmock-more-matchers.h \
38  include/gmock/gmock-spec-builders.h \
39  include/gmock/gmock.h
40
41pkginclude_internaldir = $(pkgincludedir)/internal
42pkginclude_internal_HEADERS = \
43  include/gmock/internal/gmock-generated-internal-utils.h \
44  include/gmock/internal/gmock-internal-utils.h \
45  include/gmock/internal/gmock-port.h
46
47lib_libgmock_main_la_SOURCES = src/gmock_main.cc
48lib_libgmock_main_la_LIBADD = lib/libgmock.la
49
50# Build rules for tests. Automake's naming for some of these variables isn't
51# terribly obvious, so this is a brief reference:
52#
53# TESTS -- Programs run automatically by "make check"
54# check_PROGRAMS -- Programs built by "make check" but not necessarily run
55
56TESTS=
57check_PROGRAMS=
58AM_LDFLAGS = $(GTEST_LDFLAGS)
59
60# This exercises all major components of Google Mock.  It also
61# verifies that libgmock works.
62TESTS += test/gmock-spec-builders_test
63check_PROGRAMS += test/gmock-spec-builders_test
64test_gmock_spec_builders_test_SOURCES = test/gmock-spec-builders_test.cc
65test_gmock_spec_builders_test_LDADD = $(GTEST_LIBS) lib/libgmock.la
66
67# This tests using Google Mock in multiple translation units.  It also
68# verifies that libgmock_main and libgmock work.
69TESTS += test/gmock_link_test
70check_PROGRAMS += test/gmock_link_test
71test_gmock_link_test_SOURCES = \
72  test/gmock_link2_test.cc \
73  test/gmock_link_test.cc \
74  test/gmock_link_test.h
75test_gmock_link_test_LDADD = $(GTEST_LIBS) lib/libgmock_main.la  lib/libgmock.la
76
77if HAVE_PYTHON
78  # Tests that fused gmock files compile and work.
79  TESTS += test/gmock_fused_test
80  check_PROGRAMS += test/gmock_fused_test
81  test_gmock_fused_test_SOURCES = \
82    fused-src/gmock-gtest-all.cc \
83    fused-src/gmock/gmock.h \
84    fused-src/gmock_main.cc \
85    fused-src/gtest/gtest.h \
86    test/gmock_test.cc
87  test_gmock_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src"
88endif
89
90# Google Mock source files that we don't compile directly.
91GMOCK_SOURCE_INGLUDES = \
92  src/gmock-cardinalities.cc \
93  src/gmock-internal-utils.cc \
94  src/gmock-matchers.cc \
95  src/gmock-spec-builders.cc \
96  src/gmock.cc
97
98EXTRA_DIST += $(GMOCK_SOURCE_INGLUDES)
99
100# C++ tests that we don't compile using autotools.
101EXTRA_DIST += \
102  test/gmock-actions_test.cc \
103  test/gmock_all_test.cc \
104  test/gmock-cardinalities_test.cc \
105  test/gmock_ex_test.cc \
106  test/gmock-generated-actions_test.cc \
107  test/gmock-generated-function-mockers_test.cc \
108  test/gmock-generated-internal-utils_test.cc \
109  test/gmock-generated-matchers_test.cc \
110  test/gmock-internal-utils_test.cc \
111  test/gmock-matchers_test.cc \
112  test/gmock-more-actions_test.cc \
113  test/gmock-nice-strict_test.cc \
114  test/gmock-port_test.cc \
115  test/gmock_stress_test.cc
116
117# Python tests, which we don't run using autotools.
118EXTRA_DIST += \
119  test/gmock_leak_test.py \
120  test/gmock_leak_test_.cc \
121  test/gmock_output_test.py \
122  test/gmock_output_test_.cc \
123  test/gmock_output_test_golden.txt \
124  test/gmock_test_utils.py
125
126# Nonstandard package files for distribution.
127EXTRA_DIST += \
128  CHANGES \
129  CONTRIBUTORS \
130  make/Makefile
131
132# Pump scripts for generating Google Mock headers.
133# TODO(chandlerc@google.com): automate the generation of *.h from *.h.pump.
134EXTRA_DIST += \
135  include/gmock/gmock-generated-actions.h.pump \
136  include/gmock/gmock-generated-function-mockers.h.pump \
137  include/gmock/gmock-generated-matchers.h.pump \
138  include/gmock/gmock-generated-nice-strict.h.pump \
139  include/gmock/internal/gmock-generated-internal-utils.h.pump
140
141# Script for fusing Google Mock and Google Test source files.
142EXTRA_DIST += scripts/fuse_gmock_files.py
143
144# The Google Mock Generator tool from the cppclean project.
145EXTRA_DIST += \
146  scripts/generator/LICENSE \
147  scripts/generator/README \
148  scripts/generator/README.cppclean \
149  scripts/generator/cpp/__init__.py \
150  scripts/generator/cpp/ast.py \
151  scripts/generator/cpp/gmock_class.py \
152  scripts/generator/cpp/keywords.py \
153  scripts/generator/cpp/tokenize.py \
154  scripts/generator/cpp/utils.py \
155  scripts/generator/gmock_gen.py
156
157# Script for diagnosing compiler errors in programs that use Google
158# Mock.
159EXTRA_DIST += scripts/gmock_doctor.py
160
161# CMake scripts.
162EXTRA_DIST += \
163  CMakeLists.txt
164
165# Microsoft Visual Studio 2005 projects.
166EXTRA_DIST += \
167  msvc/2005/gmock.sln \
168  msvc/2005/gmock.vcproj \
169  msvc/2005/gmock_config.vsprops \
170  msvc/2005/gmock_main.vcproj \
171  msvc/2005/gmock_test.vcproj
172
173# Microsoft Visual Studio 2010 projects.
174EXTRA_DIST += \
175  msvc/2010/gmock.sln \
176  msvc/2010/gmock.vcxproj \
177  msvc/2010/gmock_config.props \
178  msvc/2010/gmock_main.vcxproj \
179  msvc/2010/gmock_test.vcxproj
180
181if HAVE_PYTHON
182# gmock_test.cc does not really depend on files generated by the
183# fused-gmock-internal rule.  However, gmock_test.o does, and it is
184# important to include test/gmock_test.cc as part of this rule in order to
185# prevent compiling gmock_test.o until all dependent files have been
186# generated.
187$(test_gmock_fused_test_SOURCES): fused-gmock-internal
188
189# TODO(vladl@google.com): Find a way to add Google Tests's sources here.
190fused-gmock-internal: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \
191                      $(lib_libgmock_la_SOURCES) $(GMOCK_SOURCE_INGLUDES) \
192                      $(lib_libgmock_main_la_SOURCES) \
193                      scripts/fuse_gmock_files.py
194   mkdir -p "$(srcdir)/fused-src"
195   chmod -R u+w "$(srcdir)/fused-src"
196   rm -f "$(srcdir)/fused-src/gtest/gtest.h"
197   rm -f "$(srcdir)/fused-src/gmock/gmock.h"
198   rm -f "$(srcdir)/fused-src/gmock-gtest-all.cc"
199   "$(srcdir)/scripts/fuse_gmock_files.py" "$(srcdir)/fused-src"
200   cp -f "$(srcdir)/src/gmock_main.cc" "$(srcdir)/fused-src"
201
202maintainer-clean-local:
203   rm -rf "$(srcdir)/fused-src"
204endif
205
206# Death tests may produce core dumps in the build directory. In case
207# this happens, clean them to keep distcleancheck happy.
208CLEANFILES = core
209
210# Disables 'make install' as installing a compiled version of Google
211# Mock can lead to undefined behavior due to violation of the
212# One-Definition Rule.
213
214install-exec-local:
215   echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system."
216   false
217
218install-data-local:
219   echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system."
220   false
trunk/3rdparty/googletest/googlemock/README.md
r0r249096
1## Google Mock ##
2
3The Google C++ mocking framework.
4
5### Overview ###
6
7Google's framework for writing and using C++ mock classes.
8It can help you derive better designs of your system and write better tests.
9
10It is inspired by:
11
12  * [jMock](http://www.jmock.org/),
13  * [EasyMock](http://www.easymock.org/), and
14  * [Hamcrest](http://code.google.com/p/hamcrest/),
15
16and designed with C++'s specifics in mind.
17
18Google mock:
19
20  * lets you create mock classes trivially using simple macros.
21  * supports a rich set of matchers and actions.
22  * handles unordered, partially ordered, or completely ordered expectations.
23  * is extensible by users.
24
25We hope you find it useful!
26
27### Features ###
28
29  * Provides a declarative syntax for defining mocks.
30  * Can easily define partial (hybrid) mocks, which are a cross of real
31    and mock objects.
32  * Handles functions of arbitrary types and overloaded functions.
33  * Comes with a rich set of matchers for validating function arguments.
34  * Uses an intuitive syntax for controlling the behavior of a mock.
35  * Does automatic verification of expectations (no record-and-replay needed).
36  * Allows arbitrary (partial) ordering constraints on
37    function calls to be expressed,.
38  * Lets a user extend it by defining new matchers and actions.
39  * Does not use exceptions.
40  * Is easy to learn and use.
41
42Please see the project page above for more information as well as the
43mailing list for questions, discussions, and development.  There is
44also an IRC channel on OFTC (irc.oftc.net) #gtest available.  Please
45join us!
46
47Please note that code under [scripts/generator](scripts/generator/) is
48from [cppclean](http://code.google.com/p/cppclean/) and released under
49the Apache License, which is different from Google Mock's license.
50
51## Getting Started ##
52
53If you are new to the project, we suggest that you read the user
54documentation in the following order:
55
56  * Learn the [basics](../googletest/docs/Primer.md) of
57    Google Test, if you choose to use Google Mock with it (recommended).
58  * Read [Google Mock for Dummies](docs/ForDummies.md).
59  * Read the instructions below on how to build Google Mock.
60
61You can also watch Zhanyong's [talk](http://www.youtube.com/watch?v=sYpCyLI47rM) on Google Mock's usage and implementation.
62
63Once you understand the basics, check out the rest of the docs:
64
65  * [CheatSheet](googlemock/docs/CheatSheet.md) - all the commonly used stuff
66    at a glance.
67  * [CookBook](googlemock/docs/CookBook.md) - recipes for getting things done,
68    including advanced techniques.
69
70If you need help, please check the
71[KnownIssues](googlemock/docs/KnownIssues.md) and
72[FrequentlyAskedQuestions](googlemock/docs/frequentlyaskedquestions.md) before
73posting a question on the
74[discussion group](http://groups.google.com/group/googlemock).
75
76
77### Using Google Mock Without Google Test ###
78
79Google Mock is not a testing framework itself.  Instead, it needs a
80testing framework for writing tests.  Google Mock works seamlessly
81with [Google Test](http://code.google.com/p/googletest/), butj
82you can also use it with [any C++ testing framework](googlemock/ForDummies.md#Using_Google_Mock_with_Any_Testing_Framework).
83
84### Requirements for End Users ###
85
86Google Mock is implemented on top of [Google Test](
87http://github.com/google/googletest/), and depends on it.
88You must use the bundled version of Google Test when using Google Mock.
89
90You can also easily configure Google Mock to work with another testing
91framework, although it will still need Google Test.  Please read
92["Using_Google_Mock_with_Any_Testing_Framework"](
93    docs/ForDummies.md#Using_Google_Mock_with_Any_Testing_Framework)
94for instructions.
95
96Google Mock depends on advanced C++ features and thus requires a more
97modern compiler. The following are needed to use Google Mock:
98
99#### Linux Requirements ####
100
101  * GNU-compatible Make or "gmake"
102  * POSIX-standard shell
103  * POSIX(-2) Regular Expressions (regex.h)
104  * C++98-standard-compliant compiler (e.g. GCC 3.4 or newer)
105
106#### Windows Requirements ####
107
108  * Microsoft Visual C++ 8.0 SP1 or newer
109
110#### Mac OS X Requirements ####
111
112  * Mac OS X 10.4 Tiger or newer
113  * Developer Tools Installed
114
115### Requirements for Contributors ###
116
117We welcome patches. If you plan to contribute a patch, you need to
118build Google Mock and its tests, which has further requirements:
119
120  * Automake version 1.9 or newer
121  * Autoconf version 2.59 or newer
122  * Libtool / Libtoolize
123  * Python version 2.3 or newer (for running some of the tests and
124    re-generating certain source files from templates)
125
126### Building Google Mock ###
127
128#### Preparing to Build (Unix only) ####
129
130If you are using a Unix system and plan to use the GNU Autotools build
131system to build Google Mock (described below), you'll need to
132configure it now.
133
134To prepare the Autotools build system:
135
136    cd googlemock
137    autoreconf -fvi
138
139To build Google Mock and your tests that use it, you need to tell your
140build system where to find its headers and source files.  The exact
141way to do it depends on which build system you use, and is usually
142straightforward.
143
144This section shows how you can integrate Google Mock into your
145existing build system.
146
147Suppose you put Google Mock in directory `${GMOCK_DIR}` and Google Test
148in `${GTEST_DIR}` (the latter is `${GMOCK_DIR}/gtest` by default).  To
149build Google Mock, create a library build target (or a project as
150called by Visual Studio and Xcode) to compile
151
152    ${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc
153
154with
155
156    ${GTEST_DIR}/include and ${GMOCK_DIR}/include
157
158in the system header search path, and
159
160    ${GTEST_DIR} and ${GMOCK_DIR}
161
162in the normal header search path.  Assuming a Linux-like system and gcc,
163something like the following will do:
164
165    g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
166        -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
167        -pthread -c ${GTEST_DIR}/src/gtest-all.cc
168    g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
169        -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
170        -pthread -c ${GMOCK_DIR}/src/gmock-all.cc
171    ar -rv libgmock.a gtest-all.o gmock-all.o
172
173(We need -pthread as Google Test and Google Mock use threads.)
174
175Next, you should compile your test source file with
176${GTEST\_DIR}/include and ${GMOCK\_DIR}/include in the header search
177path, and link it with gmock and any other necessary libraries:
178
179    g++ -isystem ${GTEST_DIR}/include -isystem ${GMOCK_DIR}/include \
180        -pthread path/to/your_test.cc libgmock.a -o your_test
181
182As an example, the make/ directory contains a Makefile that you can
183use to build Google Mock on systems where GNU make is available
184(e.g. Linux, Mac OS X, and Cygwin).  It doesn't try to build Google
185Mock's own tests.  Instead, it just builds the Google Mock library and
186a sample test.  You can use it as a starting point for your own build
187script.
188
189If the default settings are correct for your environment, the
190following commands should succeed:
191
192    cd ${GMOCK_DIR}/make
193    make
194    ./gmock_test
195
196If you see errors, try to tweak the contents of
197[make/Makefile](make/Makefile) to make them go away.
198
199### Windows ###
200
201The msvc/2005 directory contains VC++ 2005 projects and the msvc/2010
202directory contains VC++ 2010 projects for building Google Mock and
203selected tests.
204
205Change to the appropriate directory and run "msbuild gmock.sln" to
206build the library and tests (or open the gmock.sln in the MSVC IDE).
207If you want to create your own project to use with Google Mock, you'll
208have to configure it to use the `gmock_config` propety sheet.  For that:
209
210 * Open the Property Manager window (View | Other Windows | Property Manager)
211 * Right-click on your project and select "Add Existing Property Sheet..."
212 * Navigate to `gmock_config.vsprops` or `gmock_config.props` and select it.
213 * In Project Properties | Configuration Properties | General | Additional
214   Include Directories, type <path to Google Mock>/include.
215
216### Tweaking Google Mock ###
217
218Google Mock can be used in diverse environments.  The default
219configuration may not work (or may not work well) out of the box in
220some environments.  However, you can easily tweak Google Mock by
221defining control macros on the compiler command line.  Generally,
222these macros are named like `GTEST_XYZ` and you define them to either 1
223or 0 to enable or disable a certain feature.
224
225We list the most frequently used macros below.  For a complete list,
226see file [${GTEST\_DIR}/include/gtest/internal/gtest-port.h](
227../googletest/include/gtest/internal/gtest-port.h).
228
229### Choosing a TR1 Tuple Library ###
230
231Google Mock uses the C++ Technical Report 1 (TR1) tuple library
232heavily.  Unfortunately TR1 tuple is not yet widely available with all
233compilers.  The good news is that Google Test 1.4.0+ implements a
234subset of TR1 tuple that's enough for Google Mock's need.  Google Mock
235will automatically use that implementation when the compiler doesn't
236provide TR1 tuple.
237
238Usually you don't need to care about which tuple library Google Test
239and Google Mock use.  However, if your project already uses TR1 tuple,
240you need to tell Google Test and Google Mock to use the same TR1 tuple
241library the rest of your project uses, or the two tuple
242implementations will clash.  To do that, add
243
244    -DGTEST_USE_OWN_TR1_TUPLE=0
245
246to the compiler flags while compiling Google Test, Google Mock, and
247your tests.  If you want to force Google Test and Google Mock to use
248their own tuple library, just add
249
250    -DGTEST_USE_OWN_TR1_TUPLE=1
251
252to the compiler flags instead.
253
254If you want to use Boost's TR1 tuple library with Google Mock, please
255refer to the Boost website (http://www.boost.org/) for how to obtain
256it and set it up.
257
258### As a Shared Library (DLL) ###
259
260Google Mock is compact, so most users can build and link it as a static
261library for the simplicity.  Google Mock can be used as a DLL, but the
262same DLL must contain Google Test as well.  See
263[Google Test's README][gtest_readme]
264for instructions on how to set up necessary compiler settings.
265
266### Tweaking Google Mock ###
267
268Most of Google Test's control macros apply to Google Mock as well.
269Please see [Google Test's README][gtest_readme] for how to tweak them.
270
271### Upgrading from an Earlier Version ###
272
273We strive to keep Google Mock releases backward compatible.
274Sometimes, though, we have to make some breaking changes for the
275users' long-term benefits.  This section describes what you'll need to
276do if you are upgrading from an earlier version of Google Mock.
277
278#### Upgrading from 1.1.0 or Earlier ####
279
280You may need to explicitly enable or disable Google Test's own TR1
281tuple library.  See the instructions in section "[Choosing a TR1 Tuple
282Library](../googletest/#choosing-a-tr1-tuple-library)".
283
284#### Upgrading from 1.4.0 or Earlier ####
285
286On platforms where the pthread library is available, Google Test and
287Google Mock use it in order to be thread-safe.  For this to work, you
288may need to tweak your compiler and/or linker flags.  Please see the
289"[Multi-threaded Tests](../googletest#multi-threaded-tests
290)" section in file Google Test's README for what you may need to do.
291
292If you have custom matchers defined using `MatcherInterface` or
293`MakePolymorphicMatcher()`, you'll need to update their definitions to
294use the new matcher API (
295[monomorphic](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Monomorphic_Matchers),
296[polymorphic](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Matchers)).
297Matchers defined using `MATCHER()` or `MATCHER_P*()` aren't affected.
298
299### Developing Google Mock ###
300
301This section discusses how to make your own changes to Google Mock.
302
303#### Testing Google Mock Itself ####
304
305To make sure your changes work as intended and don't break existing
306functionality, you'll want to compile and run Google Test's own tests.
307For that you'll need Autotools.  First, make sure you have followed
308the instructions above to configure Google Mock.
309Then, create a build output directory and enter it.  Next,
310
311    ${GMOCK_DIR}/configure  # try --help for more info
312
313Once you have successfully configured Google Mock, the build steps are
314standard for GNU-style OSS packages.
315
316    make        # Standard makefile following GNU conventions
317    make check  # Builds and runs all tests - all should pass.
318
319Note that when building your project against Google Mock, you are building
320against Google Test as well.  There is no need to configure Google Test
321separately.
322
323#### Contributing a Patch ####
324
325We welcome patches.
326Please read the [Developer's Guide](docs/DevGuide.md)
327for how you can contribute. In particular, make sure you have signed
328the Contributor License Agreement, or we won't be able to accept the
329patch.
330
331Happy testing!
332
333[gtest_readme]: ../googletest/README.md "googletest"
trunk/3rdparty/googletest/googlemock/build-aux/.keep
r0r249096
1m4_include(gtest/m4/acx_pthread.m4)
2
3AC_INIT([Google C++ Mocking Framework],
4        [1.7.0],
5        [googlemock@googlegroups.com],
6        [gmock])
7
8# Provide various options to initialize the Autoconf and configure processes.
9AC_PREREQ([2.59])
10AC_CONFIG_SRCDIR([./LICENSE])
11AC_CONFIG_AUX_DIR([build-aux])
12AC_CONFIG_HEADERS([build-aux/config.h])
13AC_CONFIG_FILES([Makefile])
14AC_CONFIG_FILES([scripts/gmock-config], [chmod +x scripts/gmock-config])
15
16# Initialize Automake with various options. We require at least v1.9, prevent
17# pedantic complaints about package files, and enable various distribution
18# targets.
19AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects])
20
21# Check for programs used in building Google Test.
22AC_PROG_CC
23AC_PROG_CXX
24AC_LANG([C++])
25AC_PROG_LIBTOOL
26
27# TODO(chandlerc@google.com): Currently we aren't running the Python tests
28# against the interpreter detected by AM_PATH_PYTHON, and so we condition
29# HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's
30# version to be >= 2.3. This will allow the scripts to use a "/usr/bin/env"
31# hashbang.
32PYTHON=  # We *do not* allow the user to specify a python interpreter
33AC_PATH_PROG([PYTHON],[python],[:])
34AS_IF([test "$PYTHON" != ":"],
35      [AM_PYTHON_CHECK_VERSION([$PYTHON],[2.3],[:],[PYTHON=":"])])
36AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"])
37
38# TODO(chandlerc@google.com) Check for the necessary system headers.
39
40# Configure pthreads.
41AC_ARG_WITH([pthreads],
42            [AS_HELP_STRING([--with-pthreads],
43               [use pthreads (default is yes)])],
44            [with_pthreads=$withval],
45            [with_pthreads=check])
46
47have_pthreads=no
48AS_IF([test "x$with_pthreads" != "xno"],
49      [ACX_PTHREAD(
50        [],
51        [AS_IF([test "x$with_pthreads" != "xcheck"],
52               [AC_MSG_FAILURE(
53                 [--with-pthreads was specified, but unable to be used])])])
54       have_pthreads="$acx_pthread_ok"])
55AM_CONDITIONAL([HAVE_PTHREADS],[test "x$have_pthreads" == "xyes"])
56AC_SUBST(PTHREAD_CFLAGS)
57AC_SUBST(PTHREAD_LIBS)
58
59# GoogleMock currently has hard dependencies upon GoogleTest above and beyond
60# running its own test suite, so we both provide our own version in
61# a subdirectory and provide some logic to use a custom version or a system
62# installed version.
63AC_ARG_WITH([gtest],
64            [AS_HELP_STRING([--with-gtest],
65                            [Specifies how to find the gtest package. If no
66                            arguments are given, the default behavior, a
67                            system installed gtest will be used if present,
68                            and an internal version built otherwise. If a
69                            path is provided, the gtest built or installed at
70                            that prefix will be used.])],
71            [],
72            [with_gtest=yes])
73AC_ARG_ENABLE([external-gtest],
74              [AS_HELP_STRING([--disable-external-gtest],
75                              [Disables any detection or use of a system
76                              installed or user provided gtest. Any option to
77                              '--with-gtest' is ignored. (Default is enabled.)])
78              ], [], [enable_external_gtest=yes])
79AS_IF([test "x$with_gtest" == "xno"],
80      [AC_MSG_ERROR([dnl
81Support for GoogleTest was explicitly disabled. Currently GoogleMock has a hard
82dependency upon GoogleTest to build, please provide a version, or allow
83GoogleMock to use any installed version and fall back upon its internal
84version.])])
85
86# Setup various GTEST variables. TODO(chandlerc@google.com): When these are
87# used below, they should be used such that any pre-existing values always
88# trump values we set them to, so that they can be used to selectively override
89# details of the detection process.
90AC_ARG_VAR([GTEST_CONFIG],
91           [The exact path of Google Test's 'gtest-config' script.])
92AC_ARG_VAR([GTEST_CPPFLAGS],
93           [C-like preprocessor flags for Google Test.])
94AC_ARG_VAR([GTEST_CXXFLAGS],
95           [C++ compile flags for Google Test.])
96AC_ARG_VAR([GTEST_LDFLAGS],
97           [Linker path and option flags for Google Test.])
98AC_ARG_VAR([GTEST_LIBS],
99           [Library linking flags for Google Test.])
100AC_ARG_VAR([GTEST_VERSION],
101           [The version of Google Test available.])
102HAVE_BUILT_GTEST="no"
103
104GTEST_MIN_VERSION="1.7.0"
105
106AS_IF([test "x${enable_external_gtest}" = "xyes"],
107      [# Begin filling in variables as we are able.
108      AS_IF([test "x${with_gtest}" != "xyes"],
109            [AS_IF([test -x "${with_gtest}/scripts/gtest-config"],
110                   [GTEST_CONFIG="${with_gtest}/scripts/gtest-config"],
111                   [GTEST_CONFIG="${with_gtest}/bin/gtest-config"])
112            AS_IF([test -x "${GTEST_CONFIG}"], [],
113                  [AC_MSG_ERROR([dnl
114Unable to locate either a built or installed Google Test at '${with_gtest}'.])
115                  ])])
116
117      AS_IF([test -x "${GTEST_CONFIG}"], [],
118            [AC_PATH_PROG([GTEST_CONFIG], [gtest-config])])
119      AS_IF([test -x "${GTEST_CONFIG}"],
120            [AC_MSG_CHECKING([for Google Test version >= ${GTEST_MIN_VERSION}])
121            AS_IF([${GTEST_CONFIG} --min-version=${GTEST_MIN_VERSION}],
122                  [AC_MSG_RESULT([yes])
123                  HAVE_BUILT_GTEST="yes"],
124                  [AC_MSG_RESULT([no])])])])
125
126AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"],
127      [GTEST_CPPFLAGS=`${GTEST_CONFIG} --cppflags`
128      GTEST_CXXFLAGS=`${GTEST_CONFIG} --cxxflags`
129      GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags`
130      GTEST_LIBS=`${GTEST_CONFIG} --libs`
131      GTEST_VERSION=`${GTEST_CONFIG} --version`],
132      [AC_CONFIG_SUBDIRS([gtest])
133      # GTEST_CONFIG needs to be executable both in a Makefile environmont and
134      # in a shell script environment, so resolve an absolute path for it here.
135      GTEST_CONFIG="`pwd -P`/gtest/scripts/gtest-config"
136      GTEST_CPPFLAGS='-I$(top_srcdir)/gtest/include'
137      GTEST_CXXFLAGS='-g'
138      GTEST_LDFLAGS=''
139      GTEST_LIBS='$(top_builddir)/gtest/lib/libgtest.la'
140      GTEST_VERSION="${GTEST_MIN_VERSION}"])
141
142# TODO(chandlerc@google.com) Check the types, structures, and other compiler
143# and architecture characteristics.
144
145# Output the generated files. No further autoconf macros may be used.
146AC_OUTPUT
trunk/3rdparty/googletest/googlemock/docs/CheatSheet.md
r0r249096
1
2
3# Defining a Mock Class #
4
5## Mocking a Normal Class ##
6
7Given
8```
9class Foo {
10  ...
11  virtual ~Foo();
12  virtual int GetSize() const = 0;
13  virtual string Describe(const char* name) = 0;
14  virtual string Describe(int type) = 0;
15  virtual bool Process(Bar elem, int count) = 0;
16};
17```
18(note that `~Foo()` **must** be virtual) we can define its mock as
19```
20#include "gmock/gmock.h"
21
22class MockFoo : public Foo {
23  MOCK_CONST_METHOD0(GetSize, int());
24  MOCK_METHOD1(Describe, string(const char* name));
25  MOCK_METHOD1(Describe, string(int type));
26  MOCK_METHOD2(Process, bool(Bar elem, int count));
27};
28```
29
30To create a "nice" mock object which ignores all uninteresting calls,
31or a "strict" mock object, which treats them as failures:
32```
33NiceMock<MockFoo> nice_foo;     // The type is a subclass of MockFoo.
34StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
35```
36
37## Mocking a Class Template ##
38
39To mock
40```
41template <typename Elem>
42class StackInterface {
43 public:
44  ...
45  virtual ~StackInterface();
46  virtual int GetSize() const = 0;
47  virtual void Push(const Elem& x) = 0;
48};
49```
50(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros:
51```
52template <typename Elem>
53class MockStack : public StackInterface<Elem> {
54 public:
55  ...
56  MOCK_CONST_METHOD0_T(GetSize, int());
57  MOCK_METHOD1_T(Push, void(const Elem& x));
58};
59```
60
61## Specifying Calling Conventions for Mock Functions ##
62
63If your mock function doesn't use the default calling convention, you
64can specify it by appending `_WITH_CALLTYPE` to any of the macros
65described in the previous two sections and supplying the calling
66convention as the first argument to the macro. For example,
67```
68  MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n));
69  MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y));
70```
71where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
72
73# Using Mocks in Tests #
74
75The typical flow is:
76  1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted.
77  1. Create the mock objects.
78  1. Optionally, set the default actions of the mock objects.
79  1. Set your expectations on the mock objects (How will they be called? What wil they do?).
80  1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions.
81  1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied.
82
83Here is an example:
84```
85using ::testing::Return;                            // #1
86
87TEST(BarTest, DoesThis) {
88  MockFoo foo;                                    // #2
89
90  ON_CALL(foo, GetSize())                         // #3
91      .WillByDefault(Return(1));
92  // ... other default actions ...
93
94  EXPECT_CALL(foo, Describe(5))                   // #4
95      .Times(3)
96      .WillRepeatedly(Return("Category 5"));
97  // ... other expectations ...
98
99  EXPECT_EQ("good", MyProductionFunction(&foo));  // #5
100}                                                 // #6
101```
102
103# Setting Default Actions #
104
105Google Mock has a **built-in default action** for any function that
106returns `void`, `bool`, a numeric value, or a pointer.
107
108To customize the default action for functions with return type `T` globally:
109```
110using ::testing::DefaultValue;
111
112// Sets the default value to be returned. T must be CopyConstructible.
113DefaultValue<T>::Set(value);
114// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
115//   T MakeT();
116DefaultValue<T>::SetFactory(&MakeT);
117// ... use the mocks ...
118// Resets the default value.
119DefaultValue<T>::Clear();
120```
121
122To customize the default action for a particular method, use `ON_CALL()`:
123```
124ON_CALL(mock_object, method(matchers))
125    .With(multi_argument_matcher)  ?
126    .WillByDefault(action);
127```
128
129# Setting Expectations #
130
131`EXPECT_CALL()` sets **expectations** on a mock method (How will it be
132called? What will it do?):
133```
134EXPECT_CALL(mock_object, method(matchers))
135    .With(multi_argument_matcher)  ?
136    .Times(cardinality)            ?
137    .InSequence(sequences)         *
138    .After(expectations)           *
139    .WillOnce(action)              *
140    .WillRepeatedly(action)        ?
141    .RetiresOnSaturation();        ?
142```
143
144If `Times()` is omitted, the cardinality is assumed to be:
145
146  * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
147  * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or
148  * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0.
149
150A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time.
151
152# Matchers #
153
154A **matcher** matches a _single_ argument.  You can use it inside
155`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value
156directly:
157
158| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. |
159|:------------------------------|:----------------------------------------|
160| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. |
161
162Built-in matchers (where `argument` is the function argument) are
163divided into several categories:
164
165## Wildcard ##
166|`_`|`argument` can be any value of the correct type.|
167|:--|:-----------------------------------------------|
168|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`.     |
169
170## Generic Comparison ##
171
172|`Eq(value)` or `value`|`argument == value`|
173|:---------------------|:------------------|
174|`Ge(value)`           |`argument >= value`|
175|`Gt(value)`           |`argument > value` |
176|`Le(value)`           |`argument <= value`|
177|`Lt(value)`           |`argument < value` |
178|`Ne(value)`           |`argument != value`|
179|`IsNull()`            |`argument` is a `NULL` pointer (raw or smart).|
180|`NotNull()`           |`argument` is a non-null pointer (raw or smart).|
181|`Ref(variable)`       |`argument` is a reference to `variable`.|
182|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|
183
184Except `Ref()`, these matchers make a _copy_ of `value` in case it's
185modified or destructed later. If the compiler complains that `value`
186doesn't have a public copy constructor, try wrap it in `ByRef()`,
187e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure
188`non_copyable_value` is not changed afterwards, or the meaning of your
189matcher will be changed.
190
191## Floating-Point Matchers ##
192
193|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
194|:-------------------|:----------------------------------------------------------------------------------------------|
195|`FloatEq(a_float)`  |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal.  |
196|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal.  |
197|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal.    |
198
199The above matchers use ULP-based comparison (the same as used in
200[Google Test](http://code.google.com/p/googletest/)). They
201automatically pick a reasonable error bound based on the absolute
202value of the expected value.  `DoubleEq()` and `FloatEq()` conform to
203the IEEE standard, which requires comparing two NaNs for equality to
204return false. The `NanSensitive*` version instead treats two NaNs as
205equal, which is often what a user wants.
206
207|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.|
208|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------|
209|`FloatNear(a_float, max_abs_error)`  |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal.  |
210|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal.  |
211|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal.    |
212
213## String Matchers ##
214
215The `argument` can be either a C string or a C++ string object:
216
217|`ContainsRegex(string)`|`argument` matches the given regular expression.|
218|:----------------------|:-----------------------------------------------|
219|`EndsWith(suffix)`     |`argument` ends with string `suffix`.           |
220|`HasSubstr(string)`    |`argument` contains `string` as a sub-string.   |
221|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.|
222|`StartsWith(prefix)`   |`argument` starts with string `prefix`.         |
223|`StrCaseEq(string)`    |`argument` is equal to `string`, ignoring case. |
224|`StrCaseNe(string)`    |`argument` is not equal to `string`, ignoring case.|
225|`StrEq(string)`        |`argument` is equal to `string`.                |
226|`StrNe(string)`        |`argument` is not equal to `string`.            |
227
228`ContainsRegex()` and `MatchesRegex()` use the regular expression
229syntax defined
230[here](http://code.google.com/p/googletest/wiki/AdvancedGuide#Regular_Expression_Syntax).
231`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
232strings as well.
233
234## Container Matchers ##
235
236Most STL-style containers support `==`, so you can use
237`Eq(expected_container)` or simply `expected_container` to match a
238container exactly.   If you want to write the elements in-line,
239match them more flexibly, or get more informative messages, you can use:
240
241| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
242|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------|
243| `Contains(e)`            | `argument` contains an element that matches `e`, which can be either a value or a matcher.                                       |
244| `Each(e)`                | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher.                           |
245| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. |
246| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
247| `IsEmpty()`              | `argument` is an empty container (`container.empty()`).                                                                          |
248| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
249| `SizeIs(m)`              | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`.                                           |
250| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. |
251| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
252| `WhenSorted(m)`          | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(UnorderedElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. |
253| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. |
254
255Notes:
256
257  * These matchers can also match:
258    1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and
259    1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)).
260  * The array being matched may be multi-dimensional (i.e. its elements can be arrays).
261  * `m` in `Pointwise(m, ...)` should be a matcher for `::testing::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write:
262
263```
264using ::testing::get;
265MATCHER(FooEq, "") {
266  return get<0>(arg).Equals(get<1>(arg));
267}
268...
269EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
270```
271
272## Member Matchers ##
273
274|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
275|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------|
276|`Key(e)`                 |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
277|`Pair(m1, m2)`           |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.                                                |
278|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
279
280## Matching the Result of a Function or Functor ##
281
282|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
283|:---------------|:---------------------------------------------------------------------|
284
285## Pointer Matchers ##
286
287|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.|
288|:-----------|:-----------------------------------------------------------------------------------------------|
289|`WhenDynamicCastTo<T>(m)`| when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`.                 |
290
291## Multiargument Matchers ##
292
293Technically, all matchers match a _single_ value. A "multi-argument"
294matcher is just one that matches a _tuple_. The following matchers can
295be used to match a tuple `(x, y)`:
296
297|`Eq()`|`x == y`|
298|:-----|:-------|
299|`Ge()`|`x >= y`|
300|`Gt()`|`x > y` |
301|`Le()`|`x <= y`|
302|`Lt()`|`x < y` |
303|`Ne()`|`x != y`|
304
305You can use the following selectors to pick a subset of the arguments
306(or reorder them) to participate in the matching:
307
308|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.|
309|:-----------|:-------------------------------------------------------------------|
310|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.|
311
312## Composite Matchers ##
313
314You can make a matcher from one or more other matchers:
315
316|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.|
317|:-----------------------|:---------------------------------------------------|
318|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.|
319|`Not(m)`                |`argument` doesn't match matcher `m`.               |
320
321## Adapters for Matchers ##
322
323|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.|
324|:------------------|:--------------------------------------|
325|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. |
326|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.|
327
328## Matchers as Predicates ##
329
330|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.|
331|:------------------|:---------------------------------------------------------------------------------------------|
332|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`.       |
333|`Value(value, m)`  |evaluates to `true` if `value` matches `m`.                                                   |
334
335## Defining Matchers ##
336
337| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
338|:-------------------------------------------------|:------------------------------------------------------|
339| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
340| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
341
342**Notes:**
343
344  1. The `MATCHER*` macros cannot be used inside a function or class.
345  1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters).
346  1. You can use `PrintToString(x)` to convert a value `x` of any type to a string.
347
348## Matchers as Test Assertions ##
349
350|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/Primer#Assertions) if the value of `expression` doesn't match matcher `m`.|
351|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------|
352|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.                                                          |
353
354# Actions #
355
356**Actions** specify what a mock function should do when invoked.
357
358## Returning a Value ##
359
360|`Return()`|Return from a `void` mock function.|
361|:---------|:----------------------------------|
362|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.|
363|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
364|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
365|`ReturnNull()`|Return a null pointer.             |
366|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
367|`ReturnRef(variable)`|Return a reference to `variable`.  |
368|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.|
369
370## Side Effects ##
371
372|`Assign(&variable, value)`|Assign `value` to variable.|
373|:-------------------------|:--------------------------|
374| `DeleteArg<N>()`         | Delete the `N`-th (0-based) argument, which must be a pointer. |
375| `SaveArg<N>(pointer)`    | Save the `N`-th (0-based) argument to `*pointer`. |
376| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
377| `SetArgReferee<N>(value)` |   Assign value to the variable referenced by the `N`-th (0-based) argument. |
378|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
379|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.|
380|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
381|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
382|`Throw(exception)`        |Throws the given exception, which can be any copyable value. Available since v1.1.0.|
383
384## Using a Function or a Functor as an Action ##
385
386|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
387|:----------|:-----------------------------------------------------------------------------------------------------------------|
388|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.                                  |
389|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.                       |
390|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.                                                        |
391|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|
392
393The return value of the invoked function is used as the return value
394of the action.
395
396When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
397```
398  double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
399  ...
400  EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
401```
402
403In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example,
404```
405  InvokeArgument<2>(5, string("Hi"), ByRef(foo))
406```
407calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference.
408
409## Default Action ##
410
411|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).|
412|:------------|:--------------------------------------------------------------------|
413
414**Note:** due to technical reasons, `DoDefault()` cannot be used inside  a composite action - trying to do so will result in a run-time error.
415
416## Composite Actions ##
417
418|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
419|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------|
420|`IgnoreResult(a)`       |Perform action `a` and ignore its result. `a` must not return void.                                                           |
421|`WithArg<N>(a)`         |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it.                                         |
422|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it.                                      |
423|`WithoutArgs(a)`        |Perform action `a` without any arguments.                                                                                     |
424
425## Defining Actions ##
426
427| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
428|:--------------------------------------|:---------------------------------------------------------------------------------------|
429| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
430| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`.   |
431
432The `ACTION*` macros cannot be used inside a function or class.
433
434# Cardinalities #
435
436These are used in `Times()` to specify how many times a mock function will be called:
437
438|`AnyNumber()`|The function can be called any number of times.|
439|:------------|:----------------------------------------------|
440|`AtLeast(n)` |The call is expected at least `n` times.       |
441|`AtMost(n)`  |The call is expected at most `n` times.        |
442|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.|
443|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.|
444
445# Expectation Order #
446
447By default, the expectations can be matched in _any_ order.  If some
448or all expectations must be matched in a given order, there are two
449ways to specify it.  They can be used either independently or
450together.
451
452## The After Clause ##
453
454```
455using ::testing::Expectation;
456...
457Expectation init_x = EXPECT_CALL(foo, InitX());
458Expectation init_y = EXPECT_CALL(foo, InitY());
459EXPECT_CALL(foo, Bar())
460    .After(init_x, init_y);
461```
462says that `Bar()` can be called only after both `InitX()` and
463`InitY()` have been called.
464
465If you don't know how many pre-requisites an expectation has when you
466write it, you can use an `ExpectationSet` to collect them:
467
468```
469using ::testing::ExpectationSet;
470...
471ExpectationSet all_inits;
472for (int i = 0; i < element_count; i++) {
473  all_inits += EXPECT_CALL(foo, InitElement(i));
474}
475EXPECT_CALL(foo, Bar())
476    .After(all_inits);
477```
478says that `Bar()` can be called only after all elements have been
479initialized (but we don't care about which elements get initialized
480before the others).
481
482Modifying an `ExpectationSet` after using it in an `.After()` doesn't
483affect the meaning of the `.After()`.
484
485## Sequences ##
486
487When you have a long chain of sequential expectations, it's easier to
488specify the order using **sequences**, which don't require you to given
489each expectation in the chain a different name.  <i>All expected<br>
490calls</i> in the same sequence must occur in the order they are
491specified.
492
493```
494using ::testing::Sequence;
495Sequence s1, s2;
496...
497EXPECT_CALL(foo, Reset())
498    .InSequence(s1, s2)
499    .WillOnce(Return(true));
500EXPECT_CALL(foo, GetSize())
501    .InSequence(s1)
502    .WillOnce(Return(1));
503EXPECT_CALL(foo, Describe(A<const char*>()))
504    .InSequence(s2)
505    .WillOnce(Return("dummy"));
506```
507says that `Reset()` must be called before _both_ `GetSize()` _and_
508`Describe()`, and the latter two can occur in any order.
509
510To put many expectations in a sequence conveniently:
511```
512using ::testing::InSequence;
513{
514  InSequence dummy;
515
516  EXPECT_CALL(...)...;
517  EXPECT_CALL(...)...;
518  ...
519  EXPECT_CALL(...)...;
520}
521```
522says that all expected calls in the scope of `dummy` must occur in
523strict order. The name `dummy` is irrelevant.)
524
525# Verifying and Resetting a Mock #
526
527Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier:
528```
529using ::testing::Mock;
530...
531// Verifies and removes the expectations on mock_obj;
532// returns true iff successful.
533Mock::VerifyAndClearExpectations(&mock_obj);
534...
535// Verifies and removes the expectations on mock_obj;
536// also removes the default actions set by ON_CALL();
537// returns true iff successful.
538Mock::VerifyAndClear(&mock_obj);
539```
540
541You can also tell Google Mock that a mock object can be leaked and doesn't
542need to be verified:
543```
544Mock::AllowLeak(&mock_obj);
545```
546
547# Mock Classes #
548
549Google Mock defines a convenient mock class template
550```
551class MockFunction<R(A1, ..., An)> {
552 public:
553  MOCK_METHODn(Call, R(A1, ..., An));
554};
555```
556See this [recipe](http://code.google.com/p/googlemock/wiki/CookBook#Using_Check_Points) for one application of it.
557
558# Flags #
559
560| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
561|:-------------------------------|:----------------------------------------------|
562| `--gmock_verbose=LEVEL`        | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/CookBook.md
r0r249096
1
2
3You can find recipes for using Google Mock here. If you haven't yet,
4please read the [ForDummies](ForDummies.md) document first to make sure you understand
5the basics.
6
7**Note:** Google Mock lives in the `testing` name space. For
8readability, it is recommended to write `using ::testing::Foo;` once in
9your file before using the name `Foo` defined by Google Mock. We omit
10such `using` statements in this page for brevity, but you should do it
11in your own code.
12
13# Creating Mock Classes #
14
15## Mocking Private or Protected Methods ##
16
17You must always put a mock method definition (`MOCK_METHOD*`) in a
18`public:` section of the mock class, regardless of the method being
19mocked being `public`, `protected`, or `private` in the base class.
20This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function
21from outside of the mock class.  (Yes, C++ allows a subclass to change
22the access level of a virtual function in the base class.)  Example:
23
24```
25class Foo {
26 public:
27  ...
28  virtual bool Transform(Gadget* g) = 0;
29
30 protected:
31  virtual void Resume();
32
33 private:
34  virtual int GetTimeOut();
35};
36
37class MockFoo : public Foo {
38 public:
39  ...
40  MOCK_METHOD1(Transform, bool(Gadget* g));
41
42  // The following must be in the public section, even though the
43  // methods are protected or private in the base class.
44  MOCK_METHOD0(Resume, void());
45  MOCK_METHOD0(GetTimeOut, int());
46};
47```
48
49## Mocking Overloaded Methods ##
50
51You can mock overloaded functions as usual. No special attention is required:
52
53```
54class Foo {
55  ...
56
57  // Must be virtual as we'll inherit from Foo.
58  virtual ~Foo();
59
60  // Overloaded on the types and/or numbers of arguments.
61  virtual int Add(Element x);
62  virtual int Add(int times, Element x);
63
64  // Overloaded on the const-ness of this object.
65  virtual Bar& GetBar();
66  virtual const Bar& GetBar() const;
67};
68
69class MockFoo : public Foo {
70  ...
71  MOCK_METHOD1(Add, int(Element x));
72  MOCK_METHOD2(Add, int(int times, Element x);
73
74  MOCK_METHOD0(GetBar, Bar&());
75  MOCK_CONST_METHOD0(GetBar, const Bar&());
76};
77```
78
79**Note:** if you don't mock all versions of the overloaded method, the
80compiler will give you a warning about some methods in the base class
81being hidden. To fix that, use `using` to bring them in scope:
82
83```
84class MockFoo : public Foo {
85  ...
86  using Foo::Add;
87  MOCK_METHOD1(Add, int(Element x));
88  // We don't want to mock int Add(int times, Element x);
89  ...
90};
91```
92
93## Mocking Class Templates ##
94
95To mock a class template, append `_T` to the `MOCK_*` macros:
96
97```
98template <typename Elem>
99class StackInterface {
100  ...
101  // Must be virtual as we'll inherit from StackInterface.
102  virtual ~StackInterface();
103
104  virtual int GetSize() const = 0;
105  virtual void Push(const Elem& x) = 0;
106};
107
108template <typename Elem>
109class MockStack : public StackInterface<Elem> {
110  ...
111  MOCK_CONST_METHOD0_T(GetSize, int());
112  MOCK_METHOD1_T(Push, void(const Elem& x));
113};
114```
115
116## Mocking Nonvirtual Methods ##
117
118Google Mock can mock non-virtual functions to be used in what we call _hi-perf
119dependency injection_.
120
121In this case, instead of sharing a common base class with the real
122class, your mock class will be _unrelated_ to the real class, but
123contain methods with the same signatures.  The syntax for mocking
124non-virtual methods is the _same_ as mocking virtual methods:
125
126```
127// A simple packet stream class.  None of its members is virtual.
128class ConcretePacketStream {
129 public:
130  void AppendPacket(Packet* new_packet);
131  const Packet* GetPacket(size_t packet_number) const;
132  size_t NumberOfPackets() const;
133  ...
134};
135
136// A mock packet stream class.  It inherits from no other, but defines
137// GetPacket() and NumberOfPackets().
138class MockPacketStream {
139 public:
140  MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
141  MOCK_CONST_METHOD0(NumberOfPackets, size_t());
142  ...
143};
144```
145
146Note that the mock class doesn't define `AppendPacket()`, unlike the
147real class. That's fine as long as the test doesn't need to call it.
148
149Next, you need a way to say that you want to use
150`ConcretePacketStream` in production code, and use `MockPacketStream`
151in tests.  Since the functions are not virtual and the two classes are
152unrelated, you must specify your choice at _compile time_ (as opposed
153to run time).
154
155One way to do it is to templatize your code that needs to use a packet
156stream.  More specifically, you will give your code a template type
157argument for the type of the packet stream.  In production, you will
158instantiate your template with `ConcretePacketStream` as the type
159argument.  In tests, you will instantiate the same template with
160`MockPacketStream`.  For example, you may write:
161
162```
163template <class PacketStream>
164void CreateConnection(PacketStream* stream) { ... }
165
166template <class PacketStream>
167class PacketReader {
168 public:
169  void ReadPackets(PacketStream* stream, size_t packet_num);
170};
171```
172
173Then you can use `CreateConnection<ConcretePacketStream>()` and
174`PacketReader<ConcretePacketStream>` in production code, and use
175`CreateConnection<MockPacketStream>()` and
176`PacketReader<MockPacketStream>` in tests.
177
178```
179  MockPacketStream mock_stream;
180  EXPECT_CALL(mock_stream, ...)...;
181  .. set more expectations on mock_stream ...
182  PacketReader<MockPacketStream> reader(&mock_stream);
183  ... exercise reader ...
184```
185
186## Mocking Free Functions ##
187
188It's possible to use Google Mock to mock a free function (i.e. a
189C-style function or a static method).  You just need to rewrite your
190code to use an interface (abstract class).
191
192Instead of calling a free function (say, `OpenFile`) directly,
193introduce an interface for it and have a concrete subclass that calls
194the free function:
195
196```
197class FileInterface {
198 public:
199  ...
200  virtual bool Open(const char* path, const char* mode) = 0;
201};
202
203class File : public FileInterface {
204 public:
205  ...
206  virtual bool Open(const char* path, const char* mode) {
207    return OpenFile(path, mode);
208  }
209};
210```
211
212Your code should talk to `FileInterface` to open a file.  Now it's
213easy to mock out the function.
214
215This may seem much hassle, but in practice you often have multiple
216related functions that you can put in the same interface, so the
217per-function syntactic overhead will be much lower.
218
219If you are concerned about the performance overhead incurred by
220virtual functions, and profiling confirms your concern, you can
221combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md).
222
223## The Nice, the Strict, and the Naggy ##
224
225If a mock method has no `EXPECT_CALL` spec but is called, Google Mock
226will print a warning about the "uninteresting call". The rationale is:
227
228  * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called.
229  * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning.
230
231However, sometimes you may want to suppress all "uninteresting call"
232warnings, while sometimes you may want the opposite, i.e. to treat all
233of them as errors. Google Mock lets you make the decision on a
234per-mock-object basis.
235
236Suppose your test uses a mock class `MockFoo`:
237
238```
239TEST(...) {
240  MockFoo mock_foo;
241  EXPECT_CALL(mock_foo, DoThis());
242  ... code that uses mock_foo ...
243}
244```
245
246If a method of `mock_foo` other than `DoThis()` is called, it will be
247reported by Google Mock as a warning. However, if you rewrite your
248test to use `NiceMock<MockFoo>` instead, the warning will be gone,
249resulting in a cleaner test output:
250
251```
252using ::testing::NiceMock;
253
254TEST(...) {
255  NiceMock<MockFoo> mock_foo;
256  EXPECT_CALL(mock_foo, DoThis());
257  ... code that uses mock_foo ...
258}
259```
260
261`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used
262wherever `MockFoo` is accepted.
263
264It also works if `MockFoo`'s constructor takes some arguments, as
265`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:
266
267```
268using ::testing::NiceMock;
269
270TEST(...) {
271  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
272  EXPECT_CALL(mock_foo, DoThis());
273  ... code that uses mock_foo ...
274}
275```
276
277The usage of `StrictMock` is similar, except that it makes all
278uninteresting calls failures:
279
280```
281using ::testing::StrictMock;
282
283TEST(...) {
284  StrictMock<MockFoo> mock_foo;
285  EXPECT_CALL(mock_foo, DoThis());
286  ... code that uses mock_foo ...
287
288  // The test will fail if a method of mock_foo other than DoThis()
289  // is called.
290}
291```
292
293There are some caveats though (I don't like them just as much as the
294next guy, but sadly they are side effects of C++'s limitations):
295
296  1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported.
297  1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
298  1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict.  This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual.  In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class.  This rule is required for safety.  Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.)
299
300Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort.
301
302## Simplifying the Interface without Breaking Existing Code ##
303
304Sometimes a method has a long list of arguments that is mostly
305uninteresting. For example,
306
307```
308class LogSink {
309 public:
310  ...
311  virtual void send(LogSeverity severity, const char* full_filename,
312                    const char* base_filename, int line,
313                    const struct tm* tm_time,
314                    const char* message, size_t message_len) = 0;
315};
316```
317
318This method's argument list is lengthy and hard to work with (let's
319say that the `message` argument is not even 0-terminated). If we mock
320it as is, using the mock will be awkward. If, however, we try to
321simplify this interface, we'll need to fix all clients depending on
322it, which is often infeasible.
323
324The trick is to re-dispatch the method in the mock class:
325
326```
327class ScopedMockLog : public LogSink {
328 public:
329  ...
330  virtual void send(LogSeverity severity, const char* full_filename,
331                    const char* base_filename, int line, const tm* tm_time,
332                    const char* message, size_t message_len) {
333    // We are only interested in the log severity, full file name, and
334    // log message.
335    Log(severity, full_filename, std::string(message, message_len));
336  }
337
338  // Implements the mock method:
339  //
340  //   void Log(LogSeverity severity,
341  //            const string& file_path,
342  //            const string& message);
343  MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
344                         const string& message));
345};
346```
347
348By defining a new mock method with a trimmed argument list, we make
349the mock class much more user-friendly.
350
351## Alternative to Mocking Concrete Classes ##
352
353Often you may find yourself using classes that don't implement
354interfaces. In order to test your code that uses such a class (let's
355call it `Concrete`), you may be tempted to make the methods of
356`Concrete` virtual and then mock it.
357
358Try not to do that.
359
360Making a non-virtual function virtual is a big decision. It creates an
361extension point where subclasses can tweak your class' behavior. This
362weakens your control on the class because now it's harder to maintain
363the class' invariants. You should make a function virtual only when
364there is a valid reason for a subclass to override it.
365
366Mocking concrete classes directly is problematic as it creates a tight
367coupling between the class and the tests - any small change in the
368class may invalidate your tests and make test maintenance a pain.
369
370To avoid such problems, many programmers have been practicing "coding
371to interfaces": instead of talking to the `Concrete` class, your code
372would define an interface and talk to it. Then you implement that
373interface as an adaptor on top of `Concrete`. In tests, you can easily
374mock that interface to observe how your code is doing.
375
376This technique incurs some overhead:
377
378  * You pay the cost of virtual function calls (usually not a problem).
379  * There is more abstraction for the programmers to learn.
380
381However, it can also bring significant benefits in addition to better
382testability:
383
384  * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive.
385  * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change.
386
387Some people worry that if everyone is practicing this technique, they
388will end up writing lots of redundant code. This concern is totally
389understandable. However, there are two reasons why it may not be the
390case:
391
392  * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code.
393  * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it.
394
395You need to weigh the pros and cons carefully for your particular
396problem, but I'd like to assure you that the Java community has been
397practicing this for a long time and it's a proven effective technique
398applicable in a wide variety of situations. :-)
399
400## Delegating Calls to a Fake ##
401
402Some times you have a non-trivial fake implementation of an
403interface. For example:
404
405```
406class Foo {
407 public:
408  virtual ~Foo() {}
409  virtual char DoThis(int n) = 0;
410  virtual void DoThat(const char* s, int* p) = 0;
411};
412
413class FakeFoo : public Foo {
414 public:
415  virtual char DoThis(int n) {
416    return (n > 0) ? '+' :
417        (n < 0) ? '-' : '0';
418  }
419
420  virtual void DoThat(const char* s, int* p) {
421    *p = strlen(s);
422  }
423};
424```
425
426Now you want to mock this interface such that you can set expectations
427on it. However, you also want to use `FakeFoo` for the default
428behavior, as duplicating it in the mock object is, well, a lot of
429work.
430
431When you define the mock class using Google Mock, you can have it
432delegate its default action to a fake class you already have, using
433this pattern:
434
435```
436using ::testing::_;
437using ::testing::Invoke;
438
439class MockFoo : public Foo {
440 public:
441  // Normal mock method definitions using Google Mock.
442  MOCK_METHOD1(DoThis, char(int n));
443  MOCK_METHOD2(DoThat, void(const char* s, int* p));
444
445  // Delegates the default actions of the methods to a FakeFoo object.
446  // This must be called *before* the custom ON_CALL() statements.
447  void DelegateToFake() {
448    ON_CALL(*this, DoThis(_))
449        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
450    ON_CALL(*this, DoThat(_, _))
451        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
452  }
453 private:
454  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
455};
456```
457
458With that, you can use `MockFoo` in your tests as usual. Just remember
459that if you don't explicitly set an action in an `ON_CALL()` or
460`EXPECT_CALL()`, the fake will be called upon to do it:
461
462```
463using ::testing::_;
464
465TEST(AbcTest, Xyz) {
466  MockFoo foo;
467  foo.DelegateToFake(); // Enables the fake for delegation.
468
469  // Put your ON_CALL(foo, ...)s here, if any.
470
471  // No action specified, meaning to use the default action.
472  EXPECT_CALL(foo, DoThis(5));
473  EXPECT_CALL(foo, DoThat(_, _));
474
475  int n = 0;
476  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
477  foo.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
478  EXPECT_EQ(2, n);
479}
480```
481
482**Some tips:**
483
484  * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
485  * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use.
486  * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double) const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()` method.).
487  * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code.
488
489Regarding the tip on mixing a mock and a fake, here's an example on
490why it may be a bad sign: Suppose you have a class `System` for
491low-level system operations. In particular, it does file and I/O
492operations. And suppose you want to test how your code uses `System`
493to do I/O, and you just want the file operations to work normally. If
494you mock out the entire `System` class, you'll have to provide a fake
495implementation for the file operation part, which suggests that
496`System` is taking on too many roles.
497
498Instead, you can define a `FileOps` interface and an `IOOps` interface
499and split `System`'s functionalities into the two. Then you can mock
500`IOOps` without mocking `FileOps`.
501
502## Delegating Calls to a Real Object ##
503
504When using testing doubles (mocks, fakes, stubs, and etc), sometimes
505their behaviors will differ from those of the real objects. This
506difference could be either intentional (as in simulating an error such
507that you can test the error handling code) or unintentional. If your
508mocks have different behaviors than the real objects by mistake, you
509could end up with code that passes the tests but fails in production.
510
511You can use the _delegating-to-real_ technique to ensure that your
512mock has the same behavior as the real object while retaining the
513ability to validate calls. This technique is very similar to the
514delegating-to-fake technique, the difference being that we use a real
515object instead of a fake. Here's an example:
516
517```
518using ::testing::_;
519using ::testing::AtLeast;
520using ::testing::Invoke;
521
522class MockFoo : public Foo {
523 public:
524  MockFoo() {
525    // By default, all calls are delegated to the real object.
526    ON_CALL(*this, DoThis())
527        .WillByDefault(Invoke(&real_, &Foo::DoThis));
528    ON_CALL(*this, DoThat(_))
529        .WillByDefault(Invoke(&real_, &Foo::DoThat));
530    ...
531  }
532  MOCK_METHOD0(DoThis, ...);
533  MOCK_METHOD1(DoThat, ...);
534  ...
535 private:
536  Foo real_;
537};
538...
539
540  MockFoo mock;
541
542  EXPECT_CALL(mock, DoThis())
543      .Times(3);
544  EXPECT_CALL(mock, DoThat("Hi"))
545      .Times(AtLeast(1));
546  ... use mock in test ...
547```
548
549With this, Google Mock will verify that your code made the right calls
550(with the right arguments, in the right order, called the right number
551of times, etc), and a real object will answer the calls (so the
552behavior will be the same as in production). This gives you the best
553of both worlds.
554
555## Delegating Calls to a Parent Class ##
556
557Ideally, you should code to interfaces, whose methods are all pure
558virtual. In reality, sometimes you do need to mock a virtual method
559that is not pure (i.e, it already has an implementation). For example:
560
561```
562class Foo {
563 public:
564  virtual ~Foo();
565
566  virtual void Pure(int n) = 0;
567  virtual int Concrete(const char* str) { ... }
568};
569
570class MockFoo : public Foo {
571 public:
572  // Mocking a pure method.
573  MOCK_METHOD1(Pure, void(int n));
574  // Mocking a concrete method.  Foo::Concrete() is shadowed.
575  MOCK_METHOD1(Concrete, int(const char* str));
576};
577```
578
579Sometimes you may want to call `Foo::Concrete()` instead of
580`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub
581action, or perhaps your test doesn't need to mock `Concrete()` at all
582(but it would be oh-so painful to have to define a new mock class
583whenever you don't need to mock one of its methods).
584
585The trick is to leave a back door in your mock class for accessing the
586real methods in the base class:
587
588```
589class MockFoo : public Foo {
590 public:
591  // Mocking a pure method.
592  MOCK_METHOD1(Pure, void(int n));
593  // Mocking a concrete method.  Foo::Concrete() is shadowed.
594  MOCK_METHOD1(Concrete, int(const char* str));
595
596  // Use this to call Concrete() defined in Foo.
597  int FooConcrete(const char* str) { return Foo::Concrete(str); }
598};
599```
600
601Now, you can call `Foo::Concrete()` inside an action by:
602
603```
604using ::testing::_;
605using ::testing::Invoke;
606...
607  EXPECT_CALL(foo, Concrete(_))
608      .WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
609```
610
611or tell the mock object that you don't want to mock `Concrete()`:
612
613```
614using ::testing::Invoke;
615...
616  ON_CALL(foo, Concrete(_))
617      .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
618```
619
620(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do
621that, `MockFoo::Concrete()` will be called (and cause an infinite
622recursion) since `Foo::Concrete()` is virtual. That's just how C++
623works.)
624
625# Using Matchers #
626
627## Matching Argument Values Exactly ##
628
629You can specify exactly which arguments a mock method is expecting:
630
631```
632using ::testing::Return;
633...
634  EXPECT_CALL(foo, DoThis(5))
635      .WillOnce(Return('a'));
636  EXPECT_CALL(foo, DoThat("Hello", bar));
637```
638
639## Using Simple Matchers ##
640
641You can use matchers to match arguments that have a certain property:
642
643```
644using ::testing::Ge;
645using ::testing::NotNull;
646using ::testing::Return;
647...
648  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
649      .WillOnce(Return('a'));
650  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
651  // The second argument must not be NULL.
652```
653
654A frequently used matcher is `_`, which matches anything:
655
656```
657using ::testing::_;
658using ::testing::NotNull;
659...
660  EXPECT_CALL(foo, DoThat(_, NotNull()));
661```
662
663## Combining Matchers ##
664
665You can build complex matchers from existing ones using `AllOf()`,
666`AnyOf()`, and `Not()`:
667
668```
669using ::testing::AllOf;
670using ::testing::Gt;
671using ::testing::HasSubstr;
672using ::testing::Ne;
673using ::testing::Not;
674...
675  // The argument must be > 5 and != 10.
676  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
677                                Ne(10))));
678
679  // The first argument must not contain sub-string "blah".
680  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
681                          NULL));
682```
683
684## Casting Matchers ##
685
686Google Mock matchers are statically typed, meaning that the compiler
687can catch your mistake if you use a matcher of the wrong type (for
688example, if you use `Eq(5)` to match a `string` argument). Good for
689you!
690
691Sometimes, however, you know what you're doing and want the compiler
692to give you some slack. One example is that you have a matcher for
693`long` and the argument you want to match is `int`. While the two
694types aren't exactly the same, there is nothing really wrong with
695using a `Matcher<long>` to match an `int` - after all, we can first
696convert the `int` argument to a `long` before giving it to the
697matcher.
698
699To support this need, Google Mock gives you the
700`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type
701`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the
702type `m` accepts):
703
704  1. Type `T` can be implicitly cast to type `U`;
705  1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and
706  1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value).
707
708The code won't compile if any of these conditions isn't met.
709
710Here's one example:
711
712```
713using ::testing::SafeMatcherCast;
714
715// A base class and a child class.
716class Base { ... };
717class Derived : public Base { ... };
718
719class MockFoo : public Foo {
720 public:
721  MOCK_METHOD1(DoThis, void(Derived* derived));
722};
723...
724
725  MockFoo foo;
726  // m is a Matcher<Base*> we got from somewhere.
727  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
728```
729
730If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar
731function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works
732as long as you can `static_cast` type `T` to type `U`.
733
734`MatcherCast` essentially lets you bypass C++'s type system
735(`static_cast` isn't always safe as it could throw away information,
736for example), so be careful not to misuse/abuse it.
737
738## Selecting Between Overloaded Functions ##
739
740If you expect an overloaded function to be called, the compiler may
741need some help on which overloaded version it is.
742
743To disambiguate functions overloaded on the const-ness of this object,
744use the `Const()` argument wrapper.
745
746```
747using ::testing::ReturnRef;
748
749class MockFoo : public Foo {
750  ...
751  MOCK_METHOD0(GetBar, Bar&());
752  MOCK_CONST_METHOD0(GetBar, const Bar&());
753};
754...
755
756  MockFoo foo;
757  Bar bar1, bar2;
758  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
759      .WillOnce(ReturnRef(bar1));
760  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
761      .WillOnce(ReturnRef(bar2));
762```
763
764(`Const()` is defined by Google Mock and returns a `const` reference
765to its argument.)
766
767To disambiguate overloaded functions with the same number of arguments
768but different argument types, you may need to specify the exact type
769of a matcher, either by wrapping your matcher in `Matcher<type>()`, or
770using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`,
771etc):
772
773```
774using ::testing::An;
775using ::testing::Lt;
776using ::testing::Matcher;
777using ::testing::TypedEq;
778
779class MockPrinter : public Printer {
780 public:
781  MOCK_METHOD1(Print, void(int n));
782  MOCK_METHOD1(Print, void(char c));
783};
784
785TEST(PrinterTest, Print) {
786  MockPrinter printer;
787
788  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
789  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
790  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);
791
792  printer.Print(3);
793  printer.Print(6);
794  printer.Print('a');
795}
796```
797
798## Performing Different Actions Based on the Arguments ##
799
800When a mock method is called, the _last_ matching expectation that's
801still active will be selected (think "newer overrides older"). So, you
802can make a method do different things depending on its argument values
803like this:
804
805```
806using ::testing::_;
807using ::testing::Lt;
808using ::testing::Return;
809...
810  // The default case.
811  EXPECT_CALL(foo, DoThis(_))
812      .WillRepeatedly(Return('b'));
813
814  // The more specific case.
815  EXPECT_CALL(foo, DoThis(Lt(5)))
816      .WillRepeatedly(Return('a'));
817```
818
819Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will
820be returned; otherwise `'b'` will be returned.
821
822## Matching Multiple Arguments as a Whole ##
823
824Sometimes it's not enough to match the arguments individually. For
825example, we may want to say that the first argument must be less than
826the second argument. The `With()` clause allows us to match
827all arguments of a mock function as a whole. For example,
828
829```
830using ::testing::_;
831using ::testing::Lt;
832using ::testing::Ne;
833...
834  EXPECT_CALL(foo, InRange(Ne(0), _))
835      .With(Lt());
836```
837
838says that the first argument of `InRange()` must not be 0, and must be
839less than the second argument.
840
841The expression inside `With()` must be a matcher of type
842`Matcher< ::testing::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the
843types of the function arguments.
844
845You can also write `AllArgs(m)` instead of `m` inside `.With()`. The
846two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable
847than `.With(Lt())`.
848
849You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments
850(as a tuple) against `m`. For example,
851
852```
853using ::testing::_;
854using ::testing::AllOf;
855using ::testing::Args;
856using ::testing::Lt;
857...
858  EXPECT_CALL(foo, Blah(_, _, _))
859      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
860```
861
862says that `Blah()` will be called with arguments `x`, `y`, and `z` where
863`x < y < z`.
864
865As a convenience and example, Google Mock provides some matchers for
8662-tuples, including the `Lt()` matcher above. See the [CheatSheet](CheatSheet.md) for
867the complete list.
868
869Note that if you want to pass the arguments to a predicate of your own
870(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be
871written to take a `::testing::tuple` as its argument; Google Mock will pass the `n` selected arguments as _one_ single tuple to the predicate.
872
873## Using Matchers as Predicates ##
874
875Have you noticed that a matcher is just a fancy predicate that also
876knows how to describe itself? Many existing algorithms take predicates
877as arguments (e.g. those defined in STL's `<algorithm>` header), and
878it would be a shame if Google Mock matchers are not allowed to
879participate.
880
881Luckily, you can use a matcher where a unary predicate functor is
882expected by wrapping it inside the `Matches()` function. For example,
883
884```
885#include <algorithm>
886#include <vector>
887
888std::vector<int> v;
889...
890// How many elements in v are >= 10?
891const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
892```
893
894Since you can build complex matchers from simpler ones easily using
895Google Mock, this gives you a way to conveniently construct composite
896predicates (doing the same using STL's `<functional>` header is just
897painful). For example, here's a predicate that's satisfied by any
898number that is >= 0, <= 100, and != 50:
899
900```
901Matches(AllOf(Ge(0), Le(100), Ne(50)))
902```
903
904## Using Matchers in Google Test Assertions ##
905
906Since matchers are basically predicates that also know how to describe
907themselves, there is a way to take advantage of them in
908[Google Test](http://code.google.com/p/googletest/) assertions. It's
909called `ASSERT_THAT` and `EXPECT_THAT`:
910
911```
912  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
913  EXPECT_THAT(value, matcher);  // The non-fatal version.
914```
915
916For example, in a Google Test test you can write:
917
918```
919#include "gmock/gmock.h"
920
921using ::testing::AllOf;
922using ::testing::Ge;
923using ::testing::Le;
924using ::testing::MatchesRegex;
925using ::testing::StartsWith;
926...
927
928  EXPECT_THAT(Foo(), StartsWith("Hello"));
929  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
930  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
931```
932
933which (as you can probably guess) executes `Foo()`, `Bar()`, and
934`Baz()`, and verifies that:
935
936  * `Foo()` returns a string that starts with `"Hello"`.
937  * `Bar()` returns a string that matches regular expression `"Line \\d+"`.
938  * `Baz()` returns a number in the range [5, 10].
939
940The nice thing about these macros is that _they read like
941English_. They generate informative messages too. For example, if the
942first `EXPECT_THAT()` above fails, the message will be something like:
943
944```
945Value of: Foo()
946  Actual: "Hi, world!"
947Expected: starts with "Hello"
948```
949
950**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the
951[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds
952`assertThat()` to JUnit.
953
954## Using Predicates as Matchers ##
955
956Google Mock provides a built-in set of matchers. In case you find them
957lacking, you can use an arbitray unary predicate function or functor
958as a matcher - as long as the predicate accepts a value of the type
959you want. You do this by wrapping the predicate inside the `Truly()`
960function, for example:
961
962```
963using ::testing::Truly;
964
965int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
966...
967
968  // Bar() must be called with an even number.
969  EXPECT_CALL(foo, Bar(Truly(IsEven)));
970```
971
972Note that the predicate function / functor doesn't have to return
973`bool`. It works as long as the return value can be used as the
974condition in statement `if (condition) ...`.
975
976## Matching Arguments that Are Not Copyable ##
977
978When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves
979away a copy of `bar`. When `Foo()` is called later, Google Mock
980compares the argument to `Foo()` with the saved copy of `bar`. This
981way, you don't need to worry about `bar` being modified or destroyed
982after the `EXPECT_CALL()` is executed. The same is true when you use
983matchers like `Eq(bar)`, `Le(bar)`, and so on.
984
985But what if `bar` cannot be copied (i.e. has no copy constructor)? You
986could define your own matcher function and use it with `Truly()`, as
987the previous couple of recipes have shown. Or, you may be able to get
988away from it if you can guarantee that `bar` won't be changed after
989the `EXPECT_CALL()` is executed. Just tell Google Mock that it should
990save a reference to `bar`, instead of a copy of it. Here's how:
991
992```
993using ::testing::Eq;
994using ::testing::ByRef;
995using ::testing::Lt;
996...
997  // Expects that Foo()'s argument == bar.
998  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
999
1000  // Expects that Foo()'s argument < bar.
1001  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
1002```
1003
1004Remember: if you do this, don't change `bar` after the
1005`EXPECT_CALL()`, or the result is undefined.
1006
1007## Validating a Member of an Object ##
1008
1009Often a mock function takes a reference to object as an argument. When
1010matching the argument, you may not want to compare the entire object
1011against a fixed object, as that may be over-specification. Instead,
1012you may need to validate a certain member variable or the result of a
1013certain getter method of the object. You can do this with `Field()`
1014and `Property()`. More specifically,
1015
1016```
1017Field(&Foo::bar, m)
1018```
1019
1020is a matcher that matches a `Foo` object whose `bar` member variable
1021satisfies matcher `m`.
1022
1023```
1024Property(&Foo::baz, m)
1025```
1026
1027is a matcher that matches a `Foo` object whose `baz()` method returns
1028a value that satisfies matcher `m`.
1029
1030For example:
1031
1032> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
1033|:-----------------------------|:-----------------------------------|
1034> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
1035
1036Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no
1037argument and be declared as `const`.
1038
1039BTW, `Field()` and `Property()` can also match plain pointers to
1040objects. For instance,
1041
1042```
1043Field(&Foo::number, Ge(3))
1044```
1045
1046matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`,
1047the match will always fail regardless of the inner matcher.
1048
1049What if you want to validate more than one members at the same time?
1050Remember that there is `AllOf()`.
1051
1052## Validating the Value Pointed to by a Pointer Argument ##
1053
1054C++ functions often take pointers as arguments. You can use matchers
1055like `IsNull()`, `NotNull()`, and other comparison matchers to match a
1056pointer, but what if you want to make sure the value _pointed to_ by
1057the pointer, instead of the pointer itself, has a certain property?
1058Well, you can use the `Pointee(m)` matcher.
1059
1060`Pointee(m)` matches a pointer iff `m` matches the value the pointer
1061points to. For example:
1062
1063```
1064using ::testing::Ge;
1065using ::testing::Pointee;
1066...
1067  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
1068```
1069
1070expects `foo.Bar()` to be called with a pointer that points to a value
1071greater than or equal to 3.
1072
1073One nice thing about `Pointee()` is that it treats a `NULL` pointer as
1074a match failure, so you can write `Pointee(m)` instead of
1075
1076```
1077  AllOf(NotNull(), Pointee(m))
1078```
1079
1080without worrying that a `NULL` pointer will crash your test.
1081
1082Also, did we tell you that `Pointee()` works with both raw pointers
1083**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and
1084etc)?
1085
1086What if you have a pointer to pointer? You guessed it - you can use
1087nested `Pointee()` to probe deeper inside the value. For example,
1088`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer
1089that points to a number less than 3 (what a mouthful...).
1090
1091## Testing a Certain Property of an Object ##
1092
1093Sometimes you want to specify that an object argument has a certain
1094property, but there is no existing matcher that does this. If you want
1095good error messages, you should define a matcher. If you want to do it
1096quick and dirty, you could get away with writing an ordinary function.
1097
1098Let's say you have a mock function that takes an object of type `Foo`,
1099which has an `int bar()` method and an `int baz()` method, and you
1100want to constrain that the argument's `bar()` value plus its `baz()`
1101value is a given number. Here's how you can define a matcher to do it:
1102
1103```
1104using ::testing::MatcherInterface;
1105using ::testing::MatchResultListener;
1106
1107class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
1108 public:
1109  explicit BarPlusBazEqMatcher(int expected_sum)
1110      : expected_sum_(expected_sum) {}
1111
1112  virtual bool MatchAndExplain(const Foo& foo,
1113                               MatchResultListener* listener) const {
1114    return (foo.bar() + foo.baz()) == expected_sum_;
1115  }
1116
1117  virtual void DescribeTo(::std::ostream* os) const {
1118    *os << "bar() + baz() equals " << expected_sum_;
1119  }
1120
1121  virtual void DescribeNegationTo(::std::ostream* os) const {
1122    *os << "bar() + baz() does not equal " << expected_sum_;
1123  }
1124 private:
1125  const int expected_sum_;
1126};
1127
1128inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
1129  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
1130}
1131
1132...
1133
1134  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
1135```
1136
1137## Matching Containers ##
1138
1139Sometimes an STL container (e.g. list, vector, map, ...) is passed to
1140a mock function and you may want to validate it. Since most STL
1141containers support the `==` operator, you can write
1142`Eq(expected_container)` or simply `expected_container` to match a
1143container exactly.
1144
1145Sometimes, though, you may want to be more flexible (for example, the
1146first element must be an exact match, but the second element can be
1147any positive number, and so on). Also, containers used in tests often
1148have a small number of elements, and having to define the expected
1149container out-of-line is a bit of a hassle.
1150
1151You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in
1152such cases:
1153
1154```
1155using ::testing::_;
1156using ::testing::ElementsAre;
1157using ::testing::Gt;
1158...
1159
1160  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
1161...
1162
1163  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
1164```
1165
1166The above matcher says that the container must have 4 elements, which
1167must be 1, greater than 0, anything, and 5 respectively.
1168
1169If you instead write:
1170
1171```
1172using ::testing::_;
1173using ::testing::Gt;
1174using ::testing::UnorderedElementsAre;
1175...
1176
1177  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
1178...
1179
1180  EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5)));
1181```
1182
1183It means that the container must have 4 elements, which under some
1184permutation must be 1, greater than 0, anything, and 5 respectively.
1185
1186`ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0
1187to 10 arguments. If more are needed, you can place them in a C-style
1188array and use `ElementsAreArray()` or `UnorderedElementsAreArray()`
1189instead:
1190
1191```
1192using ::testing::ElementsAreArray;
1193...
1194
1195  // ElementsAreArray accepts an array of element values.
1196  const int expected_vector1[] = { 1, 5, 2, 4, ... };
1197  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));
1198
1199  // Or, an array of element matchers.
1200  Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
1201  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
1202```
1203
1204In case the array needs to be dynamically created (and therefore the
1205array size cannot be inferred by the compiler), you can give
1206`ElementsAreArray()` an additional argument to specify the array size:
1207
1208```
1209using ::testing::ElementsAreArray;
1210...
1211  int* const expected_vector3 = new int[count];
1212  ... fill expected_vector3 with values ...
1213  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
1214```
1215
1216**Tips:**
1217
1218  * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern.
1219  * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers.
1220  * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`.
1221  * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`).
1222
1223## Sharing Matchers ##
1224
1225Under the hood, a Google Mock matcher object consists of a pointer to
1226a ref-counted implementation object. Copying matchers is allowed and
1227very efficient, as only the pointer is copied. When the last matcher
1228that references the implementation object dies, the implementation
1229object will be deleted.
1230
1231Therefore, if you have some complex matcher that you want to use again
1232and again, there is no need to build it everytime. Just assign it to a
1233matcher variable and use that variable repeatedly! For example,
1234
1235```
1236  Matcher<int> in_range = AllOf(Gt(5), Le(10));
1237  ... use in_range as a matcher in multiple EXPECT_CALLs ...
1238```
1239
1240# Setting Expectations #
1241
1242## Knowing When to Expect ##
1243
1244`ON_CALL` is likely the single most under-utilized construct in Google Mock.
1245
1246There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too).
1247
1248Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints.
1249
1250This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests?
1251
1252The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed.
1253
1254Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself.
1255
1256So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them).
1257
1258If you are bothered by the "Uninteresting mock function call" message printed when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` instead to suppress all such messages for the mock object, or suppress the message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test that's a pain to maintain.
1259
1260## Ignoring Uninteresting Calls ##
1261
1262If you are not interested in how a mock method is called, just don't
1263say anything about it. In this case, if the method is ever called,
1264Google Mock will perform its default action to allow the test program
1265to continue. If you are not happy with the default action taken by
1266Google Mock, you can override it using `DefaultValue<T>::Set()`
1267(described later in this document) or `ON_CALL()`.
1268
1269Please note that once you expressed interest in a particular mock
1270method (via `EXPECT_CALL()`), all invocations to it must match some
1271expectation. If this function is called but the arguments don't match
1272any `EXPECT_CALL()` statement, it will be an error.
1273
1274## Disallowing Unexpected Calls ##
1275
1276If a mock method shouldn't be called at all, explicitly say so:
1277
1278```
1279using ::testing::_;
1280...
1281  EXPECT_CALL(foo, Bar(_))
1282      .Times(0);
1283```
1284
1285If some calls to the method are allowed, but the rest are not, just
1286list all the expected calls:
1287
1288```
1289using ::testing::AnyNumber;
1290using ::testing::Gt;
1291...
1292  EXPECT_CALL(foo, Bar(5));
1293  EXPECT_CALL(foo, Bar(Gt(10)))
1294      .Times(AnyNumber());
1295```
1296
1297A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()`
1298statements will be an error.
1299
1300## Understanding Uninteresting vs Unexpected Calls ##
1301
1302_Uninteresting_ calls and _unexpected_ calls are different concepts in Google Mock. _Very_ different.
1303
1304A call `x.Y(...)` is **uninteresting** if there's _not even a single_ `EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the `x.Y()` method at all, as evident in that the test doesn't care to say anything about it.
1305
1306A call `x.Y(...)` is **unexpected** if there are some `EXPECT_CALL(x, Y(...))s` set, but none of them matches the call. Put another way, the test is interested in the `x.Y()` method (therefore it _explicitly_ sets some `EXPECT_CALL` to verify how it's called); however, the verification fails as the test doesn't expect this particular call to happen.
1307
1308**An unexpected call is always an error,** as the code under test doesn't behave the way the test expects it to behave.
1309
1310**By default, an uninteresting call is not an error,** as it violates no constraint specified by the test. (Google Mock's philosophy is that saying nothing means there is no constraint.) However, it leads to a warning, as it _might_ indicate a problem (e.g. the test author might have forgotten to specify a constraint).
1311
1312In Google Mock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or "strict". How does this affect uninteresting calls and unexpected calls?
1313
1314A **nice mock** suppresses uninteresting call warnings. It is less chatty than the default mock, but otherwise is the same. If a test fails with a default mock, it will also fail using a nice mock instead. And vice versa. Don't expect making a mock nice to change the test's result.
1315
1316A **strict mock** turns uninteresting call warnings into errors. So making a mock strict may change the test's result.
1317
1318Let's look at an example:
1319
1320```
1321TEST(...) {
1322  NiceMock<MockDomainRegistry> mock_registry;
1323  EXPECT_CALL(mock_registry, GetDomainOwner("google.com"))
1324          .WillRepeatedly(Return("Larry Page"));
1325
1326  // Use mock_registry in code under test.
1327  ... &mock_registry ...
1328}
1329```
1330
1331The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have `"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it will be an unexpected call, and thus an error. Having a nice mock doesn't change the severity of an unexpected call.
1332
1333So how do we tell Google Mock that `GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`:
1334
1335```
1336  EXPECT_CALL(mock_registry, GetDomainOwner(_))
1337        .Times(AnyNumber());  // catches all other calls to this method.
1338  EXPECT_CALL(mock_registry, GetDomainOwner("google.com"))
1339        .WillRepeatedly(Return("Larry Page"));
1340```
1341
1342Remember that `_` is the wildcard matcher that matches anything. With this, if `GetDomainOwner("google.com")` is called, it will do what the second `EXPECT_CALL` says; if it is called with a different argument, it will do what the first `EXPECT_CALL` says.
1343
1344Note that the order of the two `EXPECT_CALLs` is important, as a newer `EXPECT_CALL` takes precedence over an older one.
1345
1346For more on uninteresting calls, nice mocks, and strict mocks, read ["The Nice, the Strict, and the Naggy"](https://code.google.com/p/googlemock/wiki/CookBook#The_Nice,_the_Strict,_and_the_Naggy).
1347
1348## Expecting Ordered Calls ##
1349
1350Although an `EXPECT_CALL()` statement defined earlier takes precedence
1351when Google Mock tries to match a function call with an expectation,
1352by default calls don't have to happen in the order `EXPECT_CALL()`
1353statements are written. For example, if the arguments match the
1354matchers in the third `EXPECT_CALL()`, but not those in the first two,
1355then the third expectation will be used.
1356
1357If you would rather have all calls occur in the order of the
1358expectations, put the `EXPECT_CALL()` statements in a block where you
1359define a variable of type `InSequence`:
1360
1361```
1362  using ::testing::_;
1363  using ::testing::InSequence;
1364
1365  {
1366    InSequence s;
1367
1368    EXPECT_CALL(foo, DoThis(5));
1369    EXPECT_CALL(bar, DoThat(_))
1370        .Times(2);
1371    EXPECT_CALL(foo, DoThis(6));
1372  }
1373```
1374
1375In this example, we expect a call to `foo.DoThis(5)`, followed by two
1376calls to `bar.DoThat()` where the argument can be anything, which are
1377in turn followed by a call to `foo.DoThis(6)`. If a call occurred
1378out-of-order, Google Mock will report an error.
1379
1380## Expecting Partially Ordered Calls ##
1381
1382Sometimes requiring everything to occur in a predetermined order can
1383lead to brittle tests. For example, we may care about `A` occurring
1384before both `B` and `C`, but aren't interested in the relative order
1385of `B` and `C`. In this case, the test should reflect our real intent,
1386instead of being overly constraining.
1387
1388Google Mock allows you to impose an arbitrary DAG (directed acyclic
1389graph) on the calls. One way to express the DAG is to use the
1390[After](http://code.google.com/p/googlemock/wiki/CheatSheet#The_After_Clause) clause of `EXPECT_CALL`.
1391
1392Another way is via the `InSequence()` clause (not the same as the
1393`InSequence` class), which we borrowed from jMock 2. It's less
1394flexible than `After()`, but more convenient when you have long chains
1395of sequential calls, as it doesn't require you to come up with
1396different names for the expectations in the chains.  Here's how it
1397works:
1398
1399If we view `EXPECT_CALL()` statements as nodes in a graph, and add an
1400edge from node A to node B wherever A must occur before B, we can get
1401a DAG. We use the term "sequence" to mean a directed path in this
1402DAG. Now, if we decompose the DAG into sequences, we just need to know
1403which sequences each `EXPECT_CALL()` belongs to in order to be able to
1404reconstruct the orginal DAG.
1405
1406So, to specify the partial order on the expectations we need to do two
1407things: first to define some `Sequence` objects, and then for each
1408`EXPECT_CALL()` say which `Sequence` objects it is part
1409of. Expectations in the same sequence must occur in the order they are
1410written. For example,
1411
1412```
1413  using ::testing::Sequence;
1414
1415  Sequence s1, s2;
1416
1417  EXPECT_CALL(foo, A())
1418      .InSequence(s1, s2);
1419  EXPECT_CALL(bar, B())
1420      .InSequence(s1);
1421  EXPECT_CALL(bar, C())
1422      .InSequence(s2);
1423  EXPECT_CALL(foo, D())
1424      .InSequence(s2);
1425```
1426
1427specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A ->
1428C -> D`):
1429
1430```
1431       +---> B
1432       |
1433  A ---|
1434       |
1435       +---> C ---> D
1436```
1437
1438This means that A must occur before B and C, and C must occur before
1439D. There's no restriction about the order other than these.
1440
1441## Controlling When an Expectation Retires ##
1442
1443When a mock method is called, Google Mock only consider expectations
1444that are still active. An expectation is active when created, and
1445becomes inactive (aka _retires_) when a call that has to occur later
1446has occurred. For example, in
1447
1448```
1449  using ::testing::_;
1450  using ::testing::Sequence;
1451
1452  Sequence s1, s2;
1453
1454  EXPECT_CALL(log, Log(WARNING, _, "File too large."))     // #1
1455      .Times(AnyNumber())
1456      .InSequence(s1, s2);
1457  EXPECT_CALL(log, Log(WARNING, _, "Data set is empty."))  // #2
1458      .InSequence(s1);
1459  EXPECT_CALL(log, Log(WARNING, _, "User not found."))     // #3
1460      .InSequence(s2);
1461```
1462
1463as soon as either #2 or #3 is matched, #1 will retire. If a warning
1464`"File too large."` is logged after this, it will be an error.
1465
1466Note that an expectation doesn't retire automatically when it's
1467saturated. For example,
1468
1469```
1470using ::testing::_;
1471...
1472  EXPECT_CALL(log, Log(WARNING, _, _));                  // #1
1473  EXPECT_CALL(log, Log(WARNING, _, "File too large."));  // #2
1474```
1475
1476says that there will be exactly one warning with the message `"File
1477too large."`. If the second warning contains this message too, #2 will
1478match again and result in an upper-bound-violated error.
1479
1480If this is not what you want, you can ask an expectation to retire as
1481soon as it becomes saturated:
1482
1483```
1484using ::testing::_;
1485...
1486  EXPECT_CALL(log, Log(WARNING, _, _));                 // #1
1487  EXPECT_CALL(log, Log(WARNING, _, "File too large."))  // #2
1488      .RetiresOnSaturation();
1489```
1490
1491Here #2 can be used only once, so if you have two warnings with the
1492message `"File too large."`, the first will match #2 and the second
1493will match #1 - there will be no error.
1494
1495# Using Actions #
1496
1497## Returning References from Mock Methods ##
1498
1499If a mock function's return type is a reference, you need to use
1500`ReturnRef()` instead of `Return()` to return a result:
1501
1502```
1503using ::testing::ReturnRef;
1504
1505class MockFoo : public Foo {
1506 public:
1507  MOCK_METHOD0(GetBar, Bar&());
1508};
1509...
1510
1511  MockFoo foo;
1512  Bar bar;
1513  EXPECT_CALL(foo, GetBar())
1514      .WillOnce(ReturnRef(bar));
1515```
1516
1517## Returning Live Values from Mock Methods ##
1518
1519The `Return(x)` action saves a copy of `x` when the action is
1520_created_, and always returns the same value whenever it's
1521executed. Sometimes you may want to instead return the _live_ value of
1522`x` (i.e. its value at the time when the action is _executed_.).
1523
1524If the mock function's return type is a reference, you can do it using
1525`ReturnRef(x)`, as shown in the previous recipe ("Returning References
1526from Mock Methods"). However, Google Mock doesn't let you use
1527`ReturnRef()` in a mock function whose return type is not a reference,
1528as doing that usually indicates a user error. So, what shall you do?
1529
1530You may be tempted to try `ByRef()`:
1531
1532```
1533using testing::ByRef;
1534using testing::Return;
1535
1536class MockFoo : public Foo {
1537 public:
1538  MOCK_METHOD0(GetValue, int());
1539};
1540...
1541  int x = 0;
1542  MockFoo foo;
1543  EXPECT_CALL(foo, GetValue())
1544      .WillRepeatedly(Return(ByRef(x)));
1545  x = 42;
1546  EXPECT_EQ(42, foo.GetValue());
1547```
1548
1549Unfortunately, it doesn't work here. The above code will fail with error:
1550
1551```
1552Value of: foo.GetValue()
1553  Actual: 0
1554Expected: 42
1555```
1556
1557The reason is that `Return(value)` converts `value` to the actual
1558return type of the mock function at the time when the action is
1559_created_, not when it is _executed_. (This behavior was chosen for
1560the action to be safe when `value` is a proxy object that references
1561some temporary objects.) As a result, `ByRef(x)` is converted to an
1562`int` value (instead of a `const int&`) when the expectation is set,
1563and `Return(ByRef(x))` will always return 0.
1564
1565`ReturnPointee(pointer)` was provided to solve this problem
1566specifically. It returns the value pointed to by `pointer` at the time
1567the action is _executed_:
1568
1569```
1570using testing::ReturnPointee;
1571...
1572  int x = 0;
1573  MockFoo foo;
1574  EXPECT_CALL(foo, GetValue())
1575      .WillRepeatedly(ReturnPointee(&x));  // Note the & here.
1576  x = 42;
1577  EXPECT_EQ(42, foo.GetValue());  // This will succeed now.
1578```
1579
1580## Combining Actions ##
1581
1582Want to do more than one thing when a function is called? That's
1583fine. `DoAll()` allow you to do sequence of actions every time. Only
1584the return value of the last action in the sequence will be used.
1585
1586```
1587using ::testing::DoAll;
1588
1589class MockFoo : public Foo {
1590 public:
1591  MOCK_METHOD1(Bar, bool(int n));
1592};
1593...
1594
1595  EXPECT_CALL(foo, Bar(_))
1596      .WillOnce(DoAll(action_1,
1597                      action_2,
1598                      ...
1599                      action_n));
1600```
1601
1602## Mocking Side Effects ##
1603
1604Sometimes a method exhibits its effect not via returning a value but
1605via side effects. For example, it may change some global state or
1606modify an output argument. To mock side effects, in general you can
1607define your own action by implementing `::testing::ActionInterface`.
1608
1609If all you need to do is to change an output argument, the built-in
1610`SetArgPointee()` action is convenient:
1611
1612```
1613using ::testing::SetArgPointee;
1614
1615class MockMutator : public Mutator {
1616 public:
1617  MOCK_METHOD2(Mutate, void(bool mutate, int* value));
1618  ...
1619};
1620...
1621
1622  MockMutator mutator;
1623  EXPECT_CALL(mutator, Mutate(true, _))
1624      .WillOnce(SetArgPointee<1>(5));
1625```
1626
1627In this example, when `mutator.Mutate()` is called, we will assign 5
1628to the `int` variable pointed to by argument #1
1629(0-based).
1630
1631`SetArgPointee()` conveniently makes an internal copy of the
1632value you pass to it, removing the need to keep the value in scope and
1633alive. The implication however is that the value must have a copy
1634constructor and assignment operator.
1635
1636If the mock method also needs to return a value as well, you can chain
1637`SetArgPointee()` with `Return()` using `DoAll()`:
1638
1639```
1640using ::testing::_;
1641using ::testing::Return;
1642using ::testing::SetArgPointee;
1643
1644class MockMutator : public Mutator {
1645 public:
1646  ...
1647  MOCK_METHOD1(MutateInt, bool(int* value));
1648};
1649...
1650
1651  MockMutator mutator;
1652  EXPECT_CALL(mutator, MutateInt(_))
1653      .WillOnce(DoAll(SetArgPointee<0>(5),
1654                      Return(true)));
1655```
1656
1657If the output argument is an array, use the
1658`SetArrayArgument<N>(first, last)` action instead. It copies the
1659elements in source range `[first, last)` to the array pointed to by
1660the `N`-th (0-based) argument:
1661
1662```
1663using ::testing::NotNull;
1664using ::testing::SetArrayArgument;
1665
1666class MockArrayMutator : public ArrayMutator {
1667 public:
1668  MOCK_METHOD2(Mutate, void(int* values, int num_values));
1669  ...
1670};
1671...
1672
1673  MockArrayMutator mutator;
1674  int values[5] = { 1, 2, 3, 4, 5 };
1675  EXPECT_CALL(mutator, Mutate(NotNull(), 5))
1676      .WillOnce(SetArrayArgument<0>(values, values + 5));
1677```
1678
1679This also works when the argument is an output iterator:
1680
1681```
1682using ::testing::_;
1683using ::testing::SeArrayArgument;
1684
1685class MockRolodex : public Rolodex {
1686 public:
1687  MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
1688  ...
1689};
1690...
1691
1692  MockRolodex rolodex;
1693  vector<string> names;
1694  names.push_back("George");
1695  names.push_back("John");
1696  names.push_back("Thomas");
1697  EXPECT_CALL(rolodex, GetNames(_))
1698      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
1699```
1700
1701## Changing a Mock Object's Behavior Based on the State ##
1702
1703If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:
1704
1705```
1706using ::testing::InSequence;
1707using ::testing::Return;
1708
1709...
1710  {
1711    InSequence seq;
1712    EXPECT_CALL(my_mock, IsDirty())
1713        .WillRepeatedly(Return(true));
1714    EXPECT_CALL(my_mock, Flush());
1715    EXPECT_CALL(my_mock, IsDirty())
1716        .WillRepeatedly(Return(false));
1717  }
1718  my_mock.FlushIfDirty();
1719```
1720
1721This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards.
1722
1723If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
1724
1725```
1726using ::testing::_;
1727using ::testing::SaveArg;
1728using ::testing::Return;
1729
1730ACTION_P(ReturnPointee, p) { return *p; }
1731...
1732  int previous_value = 0;
1733  EXPECT_CALL(my_mock, GetPrevValue())
1734      .WillRepeatedly(ReturnPointee(&previous_value));
1735  EXPECT_CALL(my_mock, UpdateValue(_))
1736      .WillRepeatedly(SaveArg<0>(&previous_value));
1737  my_mock.DoSomethingToUpdateValue();
1738```
1739
1740Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call.
1741
1742## Setting the Default Value for a Return Type ##
1743
1744If a mock method's return type is a built-in C++ type or pointer, by
1745default it will return 0 when invoked. Also, in C++ 11 and above, a mock
1746method whose return type has a default constructor will return a default-constructed
1747value by default.  You only need to specify an
1748action if this default value doesn't work for you.
1749
1750Sometimes, you may want to change this default value, or you may want
1751to specify a default value for types Google Mock doesn't know
1752about. You can do this using the `::testing::DefaultValue` class
1753template:
1754
1755```
1756class MockFoo : public Foo {
1757 public:
1758  MOCK_METHOD0(CalculateBar, Bar());
1759};
1760...
1761
1762  Bar default_bar;
1763  // Sets the default return value for type Bar.
1764  DefaultValue<Bar>::Set(default_bar);
1765
1766  MockFoo foo;
1767
1768  // We don't need to specify an action here, as the default
1769  // return value works for us.
1770  EXPECT_CALL(foo, CalculateBar());
1771
1772  foo.CalculateBar();  // This should return default_bar.
1773
1774  // Unsets the default return value.
1775  DefaultValue<Bar>::Clear();
1776```
1777
1778Please note that changing the default value for a type can make you
1779tests hard to understand. We recommend you to use this feature
1780judiciously. For example, you may want to make sure the `Set()` and
1781`Clear()` calls are right next to the code that uses your mock.
1782
1783## Setting the Default Actions for a Mock Method ##
1784
1785You've learned how to change the default value of a given
1786type. However, this may be too coarse for your purpose: perhaps you
1787have two mock methods with the same return type and you want them to
1788have different behaviors. The `ON_CALL()` macro allows you to
1789customize your mock's behavior at the method level:
1790
1791```
1792using ::testing::_;
1793using ::testing::AnyNumber;
1794using ::testing::Gt;
1795using ::testing::Return;
1796...
1797  ON_CALL(foo, Sign(_))
1798      .WillByDefault(Return(-1));
1799  ON_CALL(foo, Sign(0))
1800      .WillByDefault(Return(0));
1801  ON_CALL(foo, Sign(Gt(0)))
1802      .WillByDefault(Return(1));
1803
1804  EXPECT_CALL(foo, Sign(_))
1805      .Times(AnyNumber());
1806
1807  foo.Sign(5);   // This should return 1.
1808  foo.Sign(-9);  // This should return -1.
1809  foo.Sign(0);   // This should return 0.
1810```
1811
1812As you may have guessed, when there are more than one `ON_CALL()`
1813statements, the news order take precedence over the older ones. In
1814other words, the **last** one that matches the function arguments will
1815be used. This matching order allows you to set up the common behavior
1816in a mock object's constructor or the test fixture's set-up phase and
1817specialize the mock's behavior later.
1818
1819## Using Functions/Methods/Functors as Actions ##
1820
1821If the built-in actions don't suit you, you can easily use an existing
1822function, method, or functor as an action:
1823
1824```
1825using ::testing::_;
1826using ::testing::Invoke;
1827
1828class MockFoo : public Foo {
1829 public:
1830  MOCK_METHOD2(Sum, int(int x, int y));
1831  MOCK_METHOD1(ComplexJob, bool(int x));
1832};
1833
1834int CalculateSum(int x, int y) { return x + y; }
1835
1836class Helper {
1837 public:
1838  bool ComplexJob(int x);
1839};
1840...
1841
1842  MockFoo foo;
1843  Helper helper;
1844  EXPECT_CALL(foo, Sum(_, _))
1845      .WillOnce(Invoke(CalculateSum));
1846  EXPECT_CALL(foo, ComplexJob(_))
1847      .WillOnce(Invoke(&helper, &Helper::ComplexJob));
1848
1849  foo.Sum(5, 6);       // Invokes CalculateSum(5, 6).
1850  foo.ComplexJob(10);  // Invokes helper.ComplexJob(10);
1851```
1852
1853The only requirement is that the type of the function, etc must be
1854_compatible_ with the signature of the mock function, meaning that the
1855latter's arguments can be implicitly converted to the corresponding
1856arguments of the former, and the former's return type can be
1857implicitly converted to that of the latter. So, you can invoke
1858something whose type is _not_ exactly the same as the mock function,
1859as long as it's safe to do so - nice, huh?
1860
1861## Invoking a Function/Method/Functor Without Arguments ##
1862
1863`Invoke()` is very useful for doing actions that are more complex. It
1864passes the mock function's arguments to the function or functor being
1865invoked such that the callee has the full context of the call to work
1866with. If the invoked function is not interested in some or all of the
1867arguments, it can simply ignore them.
1868
1869Yet, a common pattern is that a test author wants to invoke a function
1870without the arguments of the mock function. `Invoke()` allows her to
1871do that using a wrapper function that throws away the arguments before
1872invoking an underlining nullary function. Needless to say, this can be
1873tedious and obscures the intent of the test.
1874
1875`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except
1876that it doesn't pass the mock function's arguments to the
1877callee. Here's an example:
1878
1879```
1880using ::testing::_;
1881using ::testing::InvokeWithoutArgs;
1882
1883class MockFoo : public Foo {
1884 public:
1885  MOCK_METHOD1(ComplexJob, bool(int n));
1886};
1887
1888bool Job1() { ... }
1889...
1890
1891  MockFoo foo;
1892  EXPECT_CALL(foo, ComplexJob(_))
1893      .WillOnce(InvokeWithoutArgs(Job1));
1894
1895  foo.ComplexJob(10);  // Invokes Job1().
1896```
1897
1898## Invoking an Argument of the Mock Function ##
1899
1900Sometimes a mock function will receive a function pointer or a functor
1901(in other words, a "callable") as an argument, e.g.
1902
1903```
1904class MockFoo : public Foo {
1905 public:
1906  MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
1907};
1908```
1909
1910and you may want to invoke this callable argument:
1911
1912```
1913using ::testing::_;
1914...
1915  MockFoo foo;
1916  EXPECT_CALL(foo, DoThis(_, _))
1917      .WillOnce(...);
1918  // Will execute (*fp)(5), where fp is the
1919  // second argument DoThis() receives.
1920```
1921
1922Arghh, you need to refer to a mock function argument but C++ has no
1923lambda (yet), so you have to define your own action. :-( Or do you
1924really?
1925
1926Well, Google Mock has an action to solve _exactly_ this problem:
1927
1928```
1929  InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
1930```
1931
1932will invoke the `N`-th (0-based) argument the mock function receives,
1933with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is
1934a function pointer or a functor, Google Mock handles them both.
1935
1936With that, you could write:
1937
1938```
1939using ::testing::_;
1940using ::testing::InvokeArgument;
1941...
1942  EXPECT_CALL(foo, DoThis(_, _))
1943      .WillOnce(InvokeArgument<1>(5));
1944  // Will execute (*fp)(5), where fp is the
1945  // second argument DoThis() receives.
1946```
1947
1948What if the callable takes an argument by reference? No problem - just
1949wrap it inside `ByRef()`:
1950
1951```
1952...
1953  MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
1954...
1955using ::testing::_;
1956using ::testing::ByRef;
1957using ::testing::InvokeArgument;
1958...
1959
1960  MockFoo foo;
1961  Helper helper;
1962  ...
1963  EXPECT_CALL(foo, Bar(_))
1964      .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
1965  // ByRef(helper) guarantees that a reference to helper, not a copy of it,
1966  // will be passed to the callable.
1967```
1968
1969What if the callable takes an argument by reference and we do **not**
1970wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a
1971copy_ of the argument, and pass a _reference to the copy_, instead of
1972a reference to the original value, to the callable. This is especially
1973handy when the argument is a temporary value:
1974
1975```
1976...
1977  MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
1978...
1979using ::testing::_;
1980using ::testing::InvokeArgument;
1981...
1982
1983  MockFoo foo;
1984  ...
1985  EXPECT_CALL(foo, DoThat(_))
1986      .WillOnce(InvokeArgument<0>(5.0, string("Hi")));
1987  // Will execute (*f)(5.0, string("Hi")), where f is the function pointer
1988  // DoThat() receives.  Note that the values 5.0 and string("Hi") are
1989  // temporary and dead once the EXPECT_CALL() statement finishes.  Yet
1990  // it's fine to perform this action later, since a copy of the values
1991  // are kept inside the InvokeArgument action.
1992```
1993
1994## Ignoring an Action's Result ##
1995
1996Sometimes you have an action that returns _something_, but you need an
1997action that returns `void` (perhaps you want to use it in a mock
1998function that returns `void`, or perhaps it needs to be used in
1999`DoAll()` and it's not the last in the list). `IgnoreResult()` lets
2000you do that. For example:
2001
2002```
2003using ::testing::_;
2004using ::testing::Invoke;
2005using ::testing::Return;
2006
2007int Process(const MyData& data);
2008string DoSomething();
2009
2010class MockFoo : public Foo {
2011 public:
2012  MOCK_METHOD1(Abc, void(const MyData& data));
2013  MOCK_METHOD0(Xyz, bool());
2014};
2015...
2016
2017  MockFoo foo;
2018  EXPECT_CALL(foo, Abc(_))
2019  // .WillOnce(Invoke(Process));
2020  // The above line won't compile as Process() returns int but Abc() needs
2021  // to return void.
2022      .WillOnce(IgnoreResult(Invoke(Process)));
2023
2024  EXPECT_CALL(foo, Xyz())
2025      .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
2026      // Ignores the string DoSomething() returns.
2027                      Return(true)));
2028```
2029
2030Note that you **cannot** use `IgnoreResult()` on an action that already
2031returns `void`. Doing so will lead to ugly compiler errors.
2032
2033## Selecting an Action's Arguments ##
2034
2035Say you have a mock function `Foo()` that takes seven arguments, and
2036you have a custom action that you want to invoke when `Foo()` is
2037called. Trouble is, the custom action only wants three arguments:
2038
2039```
2040using ::testing::_;
2041using ::testing::Invoke;
2042...
2043  MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
2044                         const map<pair<int, int>, double>& weight,
2045                         double min_weight, double max_wight));
2046...
2047
2048bool IsVisibleInQuadrant1(bool visible, int x, int y) {
2049  return visible && x >= 0 && y >= 0;
2050}
2051...
2052
2053  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
2054      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(
2055```
2056
2057To please the compiler God, you can to define an "adaptor" that has
2058the same signature as `Foo()` and calls the custom action with the
2059right arguments:
2060
2061```
2062using ::testing::_;
2063using ::testing::Invoke;
2064
2065bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
2066                            const map<pair<int, int>, double>& weight,
2067                            double min_weight, double max_wight) {
2068  return IsVisibleInQuadrant1(visible, x, y);
2069}
2070...
2071
2072  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
2073      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.
2074```
2075
2076But isn't this awkward?
2077
2078Google Mock provides a generic _action adaptor_, so you can spend your
2079time minding more important business than writing your own
2080adaptors. Here's the syntax:
2081
2082```
2083  WithArgs<N1, N2, ..., Nk>(action)
2084```
2085
2086creates an action that passes the arguments of the mock function at
2087the given indices (0-based) to the inner `action` and performs
2088it. Using `WithArgs`, our original example can be written as:
2089
2090```
2091using ::testing::_;
2092using ::testing::Invoke;
2093using ::testing::WithArgs;
2094...
2095  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
2096      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
2097      // No need to define your own adaptor.
2098```
2099
2100For better readability, Google Mock also gives you:
2101
2102  * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and
2103  * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument.
2104
2105As you may have realized, `InvokeWithoutArgs(...)` is just syntactic
2106sugar for `WithoutArgs(Inovke(...))`.
2107
2108Here are more tips:
2109
2110  * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything.
2111  * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`.
2112  * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.
2113  * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work.
2114
2115## Ignoring Arguments in Action Functions ##
2116
2117The selecting-an-action's-arguments recipe showed us one way to make a
2118mock function and an action with incompatible argument lists fit
2119together. The downside is that wrapping the action in
2120`WithArgs<...>()` can get tedious for people writing the tests.
2121
2122If you are defining a function, method, or functor to be used with
2123`Invoke*()`, and you are not interested in some of its arguments, an
2124alternative to `WithArgs` is to declare the uninteresting arguments as
2125`Unused`. This makes the definition less cluttered and less fragile in
2126case the types of the uninteresting arguments change. It could also
2127increase the chance the action function can be reused. For example,
2128given
2129
2130```
2131  MOCK_METHOD3(Foo, double(const string& label, double x, double y));
2132  MOCK_METHOD3(Bar, double(int index, double x, double y));
2133```
2134
2135instead of
2136
2137```
2138using ::testing::_;
2139using ::testing::Invoke;
2140
2141double DistanceToOriginWithLabel(const string& label, double x, double y) {
2142  return sqrt(x*x + y*y);
2143}
2144
2145double DistanceToOriginWithIndex(int index, double x, double y) {
2146  return sqrt(x*x + y*y);
2147}
2148...
2149
2150  EXEPCT_CALL(mock, Foo("abc", _, _))
2151      .WillOnce(Invoke(DistanceToOriginWithLabel));
2152  EXEPCT_CALL(mock, Bar(5, _, _))
2153      .WillOnce(Invoke(DistanceToOriginWithIndex));
2154```
2155
2156you could write
2157
2158```
2159using ::testing::_;
2160using ::testing::Invoke;
2161using ::testing::Unused;
2162
2163double DistanceToOrigin(Unused, double x, double y) {
2164  return sqrt(x*x + y*y);
2165}
2166...
2167
2168  EXEPCT_CALL(mock, Foo("abc", _, _))
2169      .WillOnce(Invoke(DistanceToOrigin));
2170  EXEPCT_CALL(mock, Bar(5, _, _))
2171      .WillOnce(Invoke(DistanceToOrigin));
2172```
2173
2174## Sharing Actions ##
2175
2176Just like matchers, a Google Mock action object consists of a pointer
2177to a ref-counted implementation object. Therefore copying actions is
2178also allowed and very efficient. When the last action that references
2179the implementation object dies, the implementation object will be
2180deleted.
2181
2182If you have some complex action that you want to use again and again,
2183you may not have to build it from scratch everytime. If the action
2184doesn't have an internal state (i.e. if it always does the same thing
2185no matter how many times it has been called), you can assign it to an
2186action variable and use that variable repeatedly. For example:
2187
2188```
2189  Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5),
2190                                      Return(true));
2191  ... use set_flag in .WillOnce() and .WillRepeatedly() ...
2192```
2193
2194However, if the action has its own state, you may be surprised if you
2195share the action object. Suppose you have an action factory
2196`IncrementCounter(init)` which creates an action that increments and
2197returns a counter whose initial value is `init`, using two actions
2198created from the same expression and using a shared action will
2199exihibit different behaviors. Example:
2200
2201```
2202  EXPECT_CALL(foo, DoThis())
2203      .WillRepeatedly(IncrementCounter(0));
2204  EXPECT_CALL(foo, DoThat())
2205      .WillRepeatedly(IncrementCounter(0));
2206  foo.DoThis();  // Returns 1.
2207  foo.DoThis();  // Returns 2.
2208  foo.DoThat();  // Returns 1 - Blah() uses a different
2209                 // counter than Bar()'s.
2210```
2211
2212versus
2213
2214```
2215  Action<int()> increment = IncrementCounter(0);
2216
2217  EXPECT_CALL(foo, DoThis())
2218      .WillRepeatedly(increment);
2219  EXPECT_CALL(foo, DoThat())
2220      .WillRepeatedly(increment);
2221  foo.DoThis();  // Returns 1.
2222  foo.DoThis();  // Returns 2.
2223  foo.DoThat();  // Returns 3 - the counter is shared.
2224```
2225
2226# Misc Recipes on Using Google Mock #
2227
2228## Mocking Methods That Use Move-Only Types ##
2229
2230C++11 introduced <em>move-only types</em>.  A move-only-typed value can be moved from one object to another, but cannot be copied.  `std::unique_ptr<T>` is probably the most commonly used move-only type.
2231
2232Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable.  This recipe shows you how you can do it.
2233
2234Let’s say we are working on a fictional project that lets one post and share snippets called “buzzes”.  Your code uses these types:
2235
2236```
2237enum class AccessLevel { kInternal, kPublic };
2238
2239class Buzz {
2240 public:
2241  explicit Buzz(AccessLevel access) { … }
2242  ...
2243};
2244
2245class Buzzer {
2246 public:
2247  virtual ~Buzzer() {}
2248  virtual std::unique_ptr<Buzz> MakeBuzz(const std::string& text) = 0;
2249  virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) = 0;
2250  ...
2251};
2252```
2253
2254A `Buzz` object represents a snippet being posted.  A class that implements the `Buzzer` interface is capable of creating and sharing `Buzz`.  Methods in `Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`.  Now we need to mock `Buzzer` in our tests.
2255
2256To mock a method that returns a move-only type, you just use the familiar `MOCK_METHOD` syntax as usual:
2257
2258```
2259class MockBuzzer : public Buzzer {
2260 public:
2261  MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
2262  …
2263};
2264```
2265
2266However, if you attempt to use the same `MOCK_METHOD` pattern to mock a method that takes a move-only parameter, you’ll get a compiler error currently:
2267
2268```
2269  // Does NOT compile!
2270  MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, Time timestamp));
2271```
2272
2273While it’s highly desirable to make this syntax just work, it’s not trivial and the work hasn’t been done yet.  Fortunately, there is a trick you can apply today to get something that works nearly as well as this.
2274
2275The trick, is to delegate the `ShareBuzz()` method to a mock method (let’s call it `DoShareBuzz()`) that does not take move-only parameters:
2276
2277```
2278class MockBuzzer : public Buzzer {
2279 public:
2280  MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
2281  MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
2282  bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) {
2283    return DoShareBuzz(buzz.get(), timestamp);
2284  }
2285};
2286```
2287
2288Note that there's no need to define or declare `DoShareBuzz()` in a base class.  You only need to define it as a `MOCK_METHOD` in the mock class.
2289
2290Now that we have the mock class defined, we can use it in tests.  In the following code examples, we assume that we have defined a `MockBuzzer` object named `mock_buzzer_`:
2291
2292```
2293  MockBuzzer mock_buzzer_;
2294```
2295
2296First let’s see how we can set expectations on the `MakeBuzz()` method, which returns a `unique_ptr<Buzz>`.
2297
2298As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or `.WillRepeated()` clause), when that expectation fires, the default action for that method will be taken.  Since `unique_ptr<>` has a default constructor that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an action:
2299
2300```
2301  // Use the default action.
2302  EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
2303
2304  // Triggers the previous EXPECT_CALL.
2305  EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
2306```
2307
2308If you are not happy with the default action, you can tweak it.  Depending on what you need, you may either tweak the default action for a specific (mock object, mock method) combination using `ON_CALL()`, or you may tweak the default action for all mock methods that return a specific type.  The usage of `ON_CALL()` is similar to `EXPECT_CALL()`, so we’ll skip it and just explain how to do the latter (tweaking the default action for a specific return type).  You do this via the `DefaultValue<>::SetFactory()` and `DefaultValue<>::Clear()` API:
2309
2310```
2311  // Sets the default action for return type std::unique_ptr<Buzz> to
2312  // creating a new Buzz every time.
2313  DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
2314      [] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
2315
2316  // When this fires, the default action of MakeBuzz() will run, which
2317  // will return a new Buzz object.
2318  EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
2319
2320  auto buzz1 = mock_buzzer_.MakeBuzz("hello");
2321  auto buzz2 = mock_buzzer_.MakeBuzz("hello");
2322  EXPECT_NE(nullptr, buzz1);
2323  EXPECT_NE(nullptr, buzz2);
2324  EXPECT_NE(buzz1, buzz2);
2325
2326  // Resets the default action for return type std::unique_ptr<Buzz>,
2327  // to avoid interfere with other tests.
2328  DefaultValue<std::unique_ptr<Buzz>>::Clear();
2329```
2330
2331What if you want the method to do something other than the default action?  If you just need to return a pre-defined move-only value, you can use the `Return(ByMove(...))` action:
2332
2333```
2334  // When this fires, the unique_ptr<> specified by ByMove(...) will
2335  // be returned.
2336  EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
2337      .WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));
2338
2339  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
2340```
2341
2342Note that `ByMove()` is essential here - if you drop it, the code won’t compile.
2343
2344Quiz time!  What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write `….WillRepeatedly(Return(ByMove(...)));`)?  Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))` can only be run once.
2345
2346If you need your mock method to do more than just moving a pre-defined value, remember that you can always use `Invoke()` to call a lambda or a callable object, which can do pretty much anything you want:
2347
2348```
2349  EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
2350      .WillRepeatedly(Invoke([](const std::string& text) {
2351        return std::make_unique<Buzz>(AccessLevel::kInternal);
2352      }));
2353
2354  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
2355  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
2356```
2357
2358Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created and returned.  You cannot do this with `Return(ByMove(...))`.
2359
2360Now there’s one topic we haven’t covered: how do you set expectations on `ShareBuzz()`, which takes a move-only-typed parameter?  The answer is you don’t.  Instead, you set expectations on the `DoShareBuzz()` mock method (remember that we defined a `MOCK_METHOD` for `DoShareBuzz()`, not `ShareBuzz()`):
2361
2362```
2363  EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _));
2364
2365  // When one calls ShareBuzz() on the MockBuzzer like this, the call is
2366  // forwarded to DoShareBuzz(), which is mocked.  Therefore this statement
2367  // will trigger the above EXPECT_CALL.
2368  mock_buzzer_.ShareBuzz(MakeUnique&lt;Buzz&gt;(AccessLevel::kInternal),
2369                         ::base::Now());
2370```
2371
2372Some of you may have spotted one problem with this approach: the `DoShareBuzz()` mock method differs from the real `ShareBuzz()` method in that it cannot take ownership of the buzz parameter - `ShareBuzz()` will always delete buzz after `DoShareBuzz()` returns.  What if you need to save the buzz object somewhere for later use when `ShareBuzz()` is called?  Indeed, you'd be stuck.
2373
2374Another problem with the `DoShareBuzz()` we had is that it can surprise people reading or maintaining the test, as one would expect that `DoShareBuzz()` has (logically) the same contract as `ShareBuzz()`.
2375
2376Fortunately, these problems can be fixed with a bit more code.  Let's try to get it right this time:
2377
2378```
2379class MockBuzzer : public Buzzer {
2380 public:
2381  MockBuzzer() {
2382    // Since DoShareBuzz(buzz, time) is supposed to take ownership of
2383    // buzz, define a default behavior for DoShareBuzz(buzz, time) to
2384    // delete buzz.
2385    ON_CALL(*this, DoShareBuzz(_, _))
2386        .WillByDefault(Invoke([](Buzz* buzz, Time timestamp) {
2387          delete buzz;
2388          return true;
2389        }));
2390  }
2391
2392  MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
2393
2394  // Takes ownership of buzz.
2395  MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
2396  bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) {
2397    return DoShareBuzz(buzz.release(), timestamp);
2398  }
2399};
2400```
2401
2402Now, the mock `DoShareBuzz()` method is free to save the buzz argument for later use if this is what you want:
2403
2404```
2405  std::unique_ptr<Buzz> intercepted_buzz;
2406  EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _))
2407      .WillOnce(Invoke([&amp;intercepted_buzz](Buzz* buzz, Time timestamp) {
2408        // Save buzz in intercepted_buzz for analysis later.
2409        intercepted_buzz.reset(buzz);
2410        return false;
2411      }));
2412
2413  mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal),
2414                         Now());
2415  EXPECT_NE(nullptr, intercepted_buzz);
2416```
2417
2418Using the tricks covered in this recipe, you are now able to mock methods that take and/or return move-only types.  Put your newly-acquired power to good use - when you design a new API, you can now feel comfortable using `unique_ptrs` as appropriate, without fearing that doing so will compromise your tests.
2419
2420## Making the Compilation Faster ##
2421
2422Believe it or not, the _vast majority_ of the time spent on compiling
2423a mock class is in generating its constructor and destructor, as they
2424perform non-trivial tasks (e.g. verification of the
2425expectations). What's more, mock methods with different signatures
2426have different types and thus their constructors/destructors need to
2427be generated by the compiler separately. As a result, if you mock many
2428different types of methods, compiling your mock class can get really
2429slow.
2430
2431If you are experiencing slow compilation, you can move the definition
2432of your mock class' constructor and destructor out of the class body
2433and into a `.cpp` file. This way, even if you `#include` your mock
2434class in N files, the compiler only needs to generate its constructor
2435and destructor once, resulting in a much faster compilation.
2436
2437Let's illustrate the idea using an example. Here's the definition of a
2438mock class before applying this recipe:
2439
2440```
2441// File mock_foo.h.
2442...
2443class MockFoo : public Foo {
2444 public:
2445  // Since we don't declare the constructor or the destructor,
2446  // the compiler will generate them in every translation unit
2447  // where this mock class is used.
2448
2449  MOCK_METHOD0(DoThis, int());
2450  MOCK_METHOD1(DoThat, bool(const char* str));
2451  ... more mock methods ...
2452};
2453```
2454
2455After the change, it would look like:
2456
2457```
2458// File mock_foo.h.
2459...
2460class MockFoo : public Foo {
2461 public:
2462  // The constructor and destructor are declared, but not defined, here.
2463  MockFoo();
2464  virtual ~MockFoo();
2465
2466  MOCK_METHOD0(DoThis, int());
2467  MOCK_METHOD1(DoThat, bool(const char* str));
2468  ... more mock methods ...
2469};
2470```
2471and
2472```
2473// File mock_foo.cpp.
2474#include "path/to/mock_foo.h"
2475
2476// The definitions may appear trivial, but the functions actually do a
2477// lot of things through the constructors/destructors of the member
2478// variables used to implement the mock methods.
2479MockFoo::MockFoo() {}
2480MockFoo::~MockFoo() {}
2481```
2482
2483## Forcing a Verification ##
2484
2485When it's being destoyed, your friendly mock object will automatically
2486verify that all expectations on it have been satisfied, and will
2487generate [Google Test](http://code.google.com/p/googletest/) failures
2488if not. This is convenient as it leaves you with one less thing to
2489worry about. That is, unless you are not sure if your mock object will
2490be destoyed.
2491
2492How could it be that your mock object won't eventually be destroyed?
2493Well, it might be created on the heap and owned by the code you are
2494testing. Suppose there's a bug in that code and it doesn't delete the
2495mock object properly - you could end up with a passing test when
2496there's actually a bug.
2497
2498Using a heap checker is a good idea and can alleviate the concern, but
2499its implementation may not be 100% reliable. So, sometimes you do want
2500to _force_ Google Mock to verify a mock object before it is
2501(hopefully) destructed. You can do this with
2502`Mock::VerifyAndClearExpectations(&mock_object)`:
2503
2504```
2505TEST(MyServerTest, ProcessesRequest) {
2506  using ::testing::Mock;
2507
2508  MockFoo* const foo = new MockFoo;
2509  EXPECT_CALL(*foo, ...)...;
2510  // ... other expectations ...
2511
2512  // server now owns foo.
2513  MyServer server(foo);
2514  server.ProcessRequest(...);
2515
2516  // In case that server's destructor will forget to delete foo,
2517  // this will verify the expectations anyway.
2518  Mock::VerifyAndClearExpectations(foo);
2519}  // server is destroyed when it goes out of scope here.
2520```
2521
2522**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a
2523`bool` to indicate whether the verification was successful (`true` for
2524yes), so you can wrap that function call inside a `ASSERT_TRUE()` if
2525there is no point going further when the verification has failed.
2526
2527## Using Check Points ##
2528
2529Sometimes you may want to "reset" a mock object at various check
2530points in your test: at each check point, you verify that all existing
2531expectations on the mock object have been satisfied, and then you set
2532some new expectations on it as if it's newly created. This allows you
2533to work with a mock object in "phases" whose sizes are each
2534manageable.
2535
2536One such scenario is that in your test's `SetUp()` function, you may
2537want to put the object you are testing into a certain state, with the
2538help from a mock object. Once in the desired state, you want to clear
2539all expectations on the mock, such that in the `TEST_F` body you can
2540set fresh expectations on it.
2541
2542As you may have figured out, the `Mock::VerifyAndClearExpectations()`
2543function we saw in the previous recipe can help you here. Or, if you
2544are using `ON_CALL()` to set default actions on the mock object and
2545want to clear the default actions as well, use
2546`Mock::VerifyAndClear(&mock_object)` instead. This function does what
2547`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the
2548same `bool`, **plus** it clears the `ON_CALL()` statements on
2549`mock_object` too.
2550
2551Another trick you can use to achieve the same effect is to put the
2552expectations in sequences and insert calls to a dummy "check-point"
2553function at specific places. Then you can verify that the mock
2554function calls do happen at the right time. For example, if you are
2555exercising code:
2556
2557```
2558Foo(1);
2559Foo(2);
2560Foo(3);
2561```
2562
2563and want to verify that `Foo(1)` and `Foo(3)` both invoke
2564`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write:
2565
2566```
2567using ::testing::MockFunction;
2568
2569TEST(FooTest, InvokesBarCorrectly) {
2570  MyMock mock;
2571  // Class MockFunction<F> has exactly one mock method.  It is named
2572  // Call() and has type F.
2573  MockFunction<void(string check_point_name)> check;
2574  {
2575    InSequence s;
2576
2577    EXPECT_CALL(mock, Bar("a"));
2578    EXPECT_CALL(check, Call("1"));
2579    EXPECT_CALL(check, Call("2"));
2580    EXPECT_CALL(mock, Bar("a"));
2581  }
2582  Foo(1);
2583  check.Call("1");
2584  Foo(2);
2585  check.Call("2");
2586  Foo(3);
2587}
2588```
2589
2590The expectation spec says that the first `Bar("a")` must happen before
2591check point "1", the second `Bar("a")` must happen after check point "2",
2592and nothing should happen between the two check points. The explicit
2593check points make it easy to tell which `Bar("a")` is called by which
2594call to `Foo()`.
2595
2596## Mocking Destructors ##
2597
2598Sometimes you want to make sure a mock object is destructed at the
2599right time, e.g. after `bar->A()` is called but before `bar->B()` is
2600called. We already know that you can specify constraints on the order
2601of mock function calls, so all we need to do is to mock the destructor
2602of the mock function.
2603
2604This sounds simple, except for one problem: a destructor is a special
2605function with special syntax and special semantics, and the
2606`MOCK_METHOD0` macro doesn't work for it:
2607
2608```
2609  MOCK_METHOD0(~MockFoo, void());  // Won't compile!
2610```
2611
2612The good news is that you can use a simple pattern to achieve the same
2613effect. First, add a mock function `Die()` to your mock class and call
2614it in the destructor, like this:
2615
2616```
2617class MockFoo : public Foo {
2618  ...
2619  // Add the following two lines to the mock class.
2620  MOCK_METHOD0(Die, void());
2621  virtual ~MockFoo() { Die(); }
2622};
2623```
2624
2625(If the name `Die()` clashes with an existing symbol, choose another
2626name.) Now, we have translated the problem of testing when a `MockFoo`
2627object dies to testing when its `Die()` method is called:
2628
2629```
2630  MockFoo* foo = new MockFoo;
2631  MockBar* bar = new MockBar;
2632  ...
2633  {
2634    InSequence s;
2635
2636    // Expects *foo to die after bar->A() and before bar->B().
2637    EXPECT_CALL(*bar, A());
2638    EXPECT_CALL(*foo, Die());
2639    EXPECT_CALL(*bar, B());
2640  }
2641```
2642
2643And that's that.
2644
2645## Using Google Mock and Threads ##
2646
2647**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on
2648platforms where Google Mock is thread-safe. Currently these are only
2649platforms that support the pthreads library (this includes Linux and Mac).
2650To make it thread-safe on other platforms we only need to implement
2651some synchronization operations in `"gtest/internal/gtest-port.h"`.
2652
2653In a **unit** test, it's best if you could isolate and test a piece of
2654code in a single-threaded context. That avoids race conditions and
2655dead locks, and makes debugging your test much easier.
2656
2657Yet many programs are multi-threaded, and sometimes to test something
2658we need to pound on it from more than one thread. Google Mock works
2659for this purpose too.
2660
2661Remember the steps for using a mock:
2662
2663  1. Create a mock object `foo`.
2664  1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`.
2665  1. The code under test calls methods of `foo`.
2666  1. Optionally, verify and reset the mock.
2667  1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.
2668
2669If you follow the following simple rules, your mocks and threads can
2670live happily together:
2671
2672  * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow.
2673  * Obviously, you can do step #1 without locking.
2674  * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh?
2675  * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic.
2676
2677If you violate the rules (for example, if you set expectations on a
2678mock while another thread is calling its methods), you get undefined
2679behavior. That's not fun, so don't do it.
2680
2681Google Mock guarantees that the action for a mock function is done in
2682the same thread that called the mock function. For example, in
2683
2684```
2685  EXPECT_CALL(mock, Foo(1))
2686      .WillOnce(action1);
2687  EXPECT_CALL(mock, Foo(2))
2688      .WillOnce(action2);
2689```
2690
2691if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2,
2692Google Mock will execute `action1` in thread 1 and `action2` in thread
26932.
2694
2695Google Mock does _not_ impose a sequence on actions performed in
2696different threads (doing so may create deadlocks as the actions may
2697need to cooperate). This means that the execution of `action1` and
2698`action2` in the above example _may_ interleave. If this is a problem,
2699you should add proper synchronization logic to `action1` and `action2`
2700to make the test thread-safe.
2701
2702
2703Also, remember that `DefaultValue<T>` is a global resource that
2704potentially affects _all_ living mock objects in your
2705program. Naturally, you won't want to mess with it from multiple
2706threads or when there still are mocks in action.
2707
2708## Controlling How Much Information Google Mock Prints ##
2709
2710When Google Mock sees something that has the potential of being an
2711error (e.g. a mock function with no expectation is called, a.k.a. an
2712uninteresting call, which is allowed but perhaps you forgot to
2713explicitly ban the call), it prints some warning messages, including
2714the arguments of the function and the return value. Hopefully this
2715will remind you to take a look and see if there is indeed a problem.
2716
2717Sometimes you are confident that your tests are correct and may not
2718appreciate such friendly messages. Some other times, you are debugging
2719your tests or learning about the behavior of the code you are testing,
2720and wish you could observe every mock call that happens (including
2721argument values and the return value). Clearly, one size doesn't fit
2722all.
2723
2724You can control how much Google Mock tells you using the
2725`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string
2726with three possible values:
2727
2728  * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros.
2729  * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default.
2730  * `error`: Google Mock will print errors only (least verbose).
2731
2732Alternatively, you can adjust the value of that flag from within your
2733tests like so:
2734
2735```
2736  ::testing::FLAGS_gmock_verbose = "error";
2737```
2738
2739Now, judiciously use the right flag to enable Google Mock serve you better!
2740
2741## Gaining Super Vision into Mock Calls ##
2742
2743You have a test using Google Mock. It fails: Google Mock tells you
2744that some expectations aren't satisfied. However, you aren't sure why:
2745Is there a typo somewhere in the matchers? Did you mess up the order
2746of the `EXPECT_CALL`s? Or is the code under test doing something
2747wrong?  How can you find out the cause?
2748
2749Won't it be nice if you have X-ray vision and can actually see the
2750trace of all `EXPECT_CALL`s and mock method calls as they are made?
2751For each call, would you like to see its actual argument values and
2752which `EXPECT_CALL` Google Mock thinks it matches?
2753
2754You can unlock this power by running your test with the
2755`--gmock_verbose=info` flag. For example, given the test program:
2756
2757```
2758using testing::_;
2759using testing::HasSubstr;
2760using testing::Return;
2761
2762class MockFoo {
2763 public:
2764  MOCK_METHOD2(F, void(const string& x, const string& y));
2765};
2766
2767TEST(Foo, Bar) {
2768  MockFoo mock;
2769  EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return());
2770  EXPECT_CALL(mock, F("a", "b"));
2771  EXPECT_CALL(mock, F("c", HasSubstr("d")));
2772
2773  mock.F("a", "good");
2774  mock.F("a", "b");
2775}
2776```
2777
2778if you run it with `--gmock_verbose=info`, you will see this output:
2779
2780```
2781[ RUN      ] Foo.Bar
2782
2783foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked
2784foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked
2785foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked
2786foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))...
2787    Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good")
2788foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))...
2789    Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b")
2790foo_test.cc:16: Failure
2791Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))...
2792         Expected: to be called once
2793           Actual: never called - unsatisfied and active
2794[  FAILED  ] Foo.Bar
2795```
2796
2797Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo
2798and should actually be `"a"`. With the above message, you should see
2799that the actual `F("a", "good")` call is matched by the first
2800`EXPECT_CALL`, not the third as you thought. From that it should be
2801obvious that the third `EXPECT_CALL` is written wrong. Case solved.
2802
2803## Running Tests in Emacs ##
2804
2805If you build and run your tests in Emacs, the source file locations of
2806Google Mock and [Google Test](http://code.google.com/p/googletest/)
2807errors will be highlighted. Just press `<Enter>` on one of them and
2808you'll be taken to the offending line. Or, you can just type `C-x ``
2809to jump to the next error.
2810
2811To make it even easier, you can add the following lines to your
2812`~/.emacs` file:
2813
2814```
2815(global-set-key "\M-m"   'compile)  ; m is for make
2816(global-set-key [M-down] 'next-error)
2817(global-set-key [M-up]   '(lambda () (interactive) (next-error -1)))
2818```
2819
2820Then you can type `M-m` to start a build, or `M-up`/`M-down` to move
2821back and forth between errors.
2822
2823## Fusing Google Mock Source Files ##
2824
2825Google Mock's implementation consists of dozens of files (excluding
2826its own tests).  Sometimes you may want them to be packaged up in
2827fewer files instead, such that you can easily copy them to a new
2828machine and start hacking there.  For this we provide an experimental
2829Python script `fuse_gmock_files.py` in the `scripts/` directory
2830(starting with release 1.2.0).  Assuming you have Python 2.4 or above
2831installed on your machine, just go to that directory and run
2832```
2833python fuse_gmock_files.py OUTPUT_DIR
2834```
2835
2836and you should see an `OUTPUT_DIR` directory being created with files
2837`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it.
2838These three files contain everything you need to use Google Mock (and
2839Google Test).  Just copy them to anywhere you want and you are ready
2840to write tests and use mocks.  You can use the
2841[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests
2842against them.
2843
2844# Extending Google Mock #
2845
2846## Writing New Matchers Quickly ##
2847
2848The `MATCHER*` family of macros can be used to define custom matchers
2849easily.  The syntax:
2850
2851```
2852MATCHER(name, description_string_expression) { statements; }
2853```
2854
2855will define a matcher with the given name that executes the
2856statements, which must return a `bool` to indicate if the match
2857succeeds.  Inside the statements, you can refer to the value being
2858matched by `arg`, and refer to its type by `arg_type`.
2859
2860The description string is a `string`-typed expression that documents
2861what the matcher does, and is used to generate the failure message
2862when the match fails.  It can (and should) reference the special
2863`bool` variable `negation`, and should evaluate to the description of
2864the matcher when `negation` is `false`, or that of the matcher's
2865negation when `negation` is `true`.
2866
2867For convenience, we allow the description string to be empty (`""`),
2868in which case Google Mock will use the sequence of words in the
2869matcher name as the description.
2870
2871For example:
2872```
2873MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
2874```
2875allows you to write
2876```
2877  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.
2878  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
2879```
2880or,
2881```
2882using ::testing::Not;
2883...
2884  EXPECT_THAT(some_expression, IsDivisibleBy7());
2885  EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));
2886```
2887If the above assertions fail, they will print something like:
2888```
2889  Value of: some_expression
2890  Expected: is divisible by 7
2891    Actual: 27
2892...
2893  Value of: some_other_expression
2894  Expected: not (is divisible by 7)
2895    Actual: 21
2896```
2897where the descriptions `"is divisible by 7"` and `"not (is divisible
2898by 7)"` are automatically calculated from the matcher name
2899`IsDivisibleBy7`.
2900
2901As you may have noticed, the auto-generated descriptions (especially
2902those for the negation) may not be so great. You can always override
2903them with a string expression of your own:
2904```
2905MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") +
2906                        " divisible by 7") {
2907  return (arg % 7) == 0;
2908}
2909```
2910
2911Optionally, you can stream additional information to a hidden argument
2912named `result_listener` to explain the match result. For example, a
2913better definition of `IsDivisibleBy7` is:
2914```
2915MATCHER(IsDivisibleBy7, "") {
2916  if ((arg % 7) == 0)
2917    return true;
2918
2919  *result_listener << "the remainder is " << (arg % 7);
2920  return false;
2921}
2922```
2923
2924With this definition, the above assertion will give a better message:
2925```
2926  Value of: some_expression
2927  Expected: is divisible by 7
2928    Actual: 27 (the remainder is 6)
2929```
2930
2931You should let `MatchAndExplain()` print _any additional information_
2932that can help a user understand the match result. Note that it should
2933explain why the match succeeds in case of a success (unless it's
2934obvious) - this is useful when the matcher is used inside
2935`Not()`. There is no need to print the argument value itself, as
2936Google Mock already prints it for you.
2937
2938**Notes:**
2939
2940  1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you).  This allows the matcher to be polymorphic.  For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`.  In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on.
2941  1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock.
2942
2943## Writing New Parameterized Matchers Quickly ##
2944
2945Sometimes you'll want to define a matcher that has parameters.  For that you
2946can use the macro:
2947```
2948MATCHER_P(name, param_name, description_string) { statements; }
2949```
2950where the description string can be either `""` or a string expression
2951that references `negation` and `param_name`.
2952
2953For example:
2954```
2955MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2956```
2957will allow you to write:
2958```
2959  EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2960```
2961which may lead to this message (assuming `n` is 10):
2962```
2963  Value of: Blah("a")
2964  Expected: has absolute value 10
2965    Actual: -9
2966```
2967
2968Note that both the matcher description and its parameter are
2969printed, making the message human-friendly.
2970
2971In the matcher definition body, you can write `foo_type` to
2972reference the type of a parameter named `foo`.  For example, in the
2973body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write
2974`value_type` to refer to the type of `value`.
2975
2976Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to
2977`MATCHER_P10` to support multi-parameter matchers:
2978```
2979MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }
2980```
2981
2982Please note that the custom description string is for a particular
2983**instance** of the matcher, where the parameters have been bound to
2984actual values.  Therefore usually you'll want the parameter values to
2985be part of the description.  Google Mock lets you do that by
2986referencing the matcher parameters in the description string
2987expression.
2988
2989For example,
2990```
2991  using ::testing::PrintToString;
2992  MATCHER_P2(InClosedRange, low, hi,
2993             std::string(negation ? "isn't" : "is") + " in range [" +
2994             PrintToString(low) + ", " + PrintToString(hi) + "]") {
2995    return low <= arg && arg <= hi;
2996  }
2997  ...
2998  EXPECT_THAT(3, InClosedRange(4, 6));
2999```
3000would generate a failure that contains the message:
3001```
3002  Expected: is in range [4, 6]
3003```
3004
3005If you specify `""` as the description, the failure message will
3006contain the sequence of words in the matcher name followed by the
3007parameter values printed as a tuple.  For example,
3008```
3009  MATCHER_P2(InClosedRange, low, hi, "") { ... }
3010  ...
3011  EXPECT_THAT(3, InClosedRange(4, 6));
3012```
3013would generate a failure that contains the text:
3014```
3015  Expected: in closed range (4, 6)
3016```
3017
3018For the purpose of typing, you can view
3019```
3020MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
3021```
3022as shorthand for
3023```
3024template <typename p1_type, ..., typename pk_type>
3025FooMatcherPk<p1_type, ..., pk_type>
3026Foo(p1_type p1, ..., pk_type pk) { ... }
3027```
3028
3029When you write `Foo(v1, ..., vk)`, the compiler infers the types of
3030the parameters `v1`, ..., and `vk` for you.  If you are not happy with
3031the result of the type inference, you can specify the types by
3032explicitly instantiating the template, as in `Foo<long, bool>(5, false)`.
3033As said earlier, you don't get to (or need to) specify
3034`arg_type` as that's determined by the context in which the matcher
3035is used.
3036
3037You can assign the result of expression `Foo(p1, ..., pk)` to a
3038variable of type `FooMatcherPk<p1_type, ..., pk_type>`.  This can be
3039useful when composing matchers.  Matchers that don't have a parameter
3040or have only one parameter have special types: you can assign `Foo()`
3041to a `FooMatcher`-typed variable, and assign `Foo(p)` to a
3042`FooMatcherP<p_type>`-typed variable.
3043
3044While you can instantiate a matcher template with reference types,
3045passing the parameters by pointer usually makes your code more
3046readable.  If, however, you still want to pass a parameter by
3047reference, be aware that in the failure message generated by the
3048matcher you will see the value of the referenced object but not its
3049address.
3050
3051You can overload matchers with different numbers of parameters:
3052```
3053MATCHER_P(Blah, a, description_string_1) { ... }
3054MATCHER_P2(Blah, a, b, description_string_2) { ... }
3055```
3056
3057While it's tempting to always use the `MATCHER*` macros when defining
3058a new matcher, you should also consider implementing
3059`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see
3060the recipes that follow), especially if you need to use the matcher a
3061lot.  While these approaches require more work, they give you more
3062control on the types of the value being matched and the matcher
3063parameters, which in general leads to better compiler error messages
3064that pay off in the long run.  They also allow overloading matchers
3065based on parameter types (as opposed to just based on the number of
3066parameters).
3067
3068## Writing New Monomorphic Matchers ##
3069
3070A matcher of argument type `T` implements
3071`::testing::MatcherInterface<T>` and does two things: it tests whether a
3072value of type `T` matches the matcher, and can describe what kind of
3073values it matches. The latter ability is used for generating readable
3074error messages when expectations are violated.
3075
3076The interface looks like this:
3077
3078```
3079class MatchResultListener {
3080 public:
3081  ...
3082  // Streams x to the underlying ostream; does nothing if the ostream
3083  // is NULL.
3084  template <typename T>
3085  MatchResultListener& operator<<(const T& x);
3086
3087  // Returns the underlying ostream.
3088  ::std::ostream* stream();
3089};
3090
3091template <typename T>
3092class MatcherInterface {
3093 public:
3094  virtual ~MatcherInterface();
3095
3096  // Returns true iff the matcher matches x; also explains the match
3097  // result to 'listener'.
3098  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
3099
3100  // Describes this matcher to an ostream.
3101  virtual void DescribeTo(::std::ostream* os) const = 0;
3102
3103  // Describes the negation of this matcher to an ostream.
3104  virtual void DescribeNegationTo(::std::ostream* os) const;
3105};
3106```
3107
3108If you need a custom matcher but `Truly()` is not a good option (for
3109example, you may not be happy with the way `Truly(predicate)`
3110describes itself, or you may want your matcher to be polymorphic as
3111`Eq(value)` is), you can define a matcher to do whatever you want in
3112two steps: first implement the matcher interface, and then define a
3113factory function to create a matcher instance. The second step is not
3114strictly needed but it makes the syntax of using the matcher nicer.
3115
3116For example, you can define a matcher to test whether an `int` is
3117divisible by 7 and then use it like this:
3118```
3119using ::testing::MakeMatcher;
3120using ::testing::Matcher;
3121using ::testing::MatcherInterface;
3122using ::testing::MatchResultListener;
3123
3124class DivisibleBy7Matcher : public MatcherInterface<int> {
3125 public:
3126  virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
3127    return (n % 7) == 0;
3128  }
3129
3130  virtual void DescribeTo(::std::ostream* os) const {
3131    *os << "is divisible by 7";
3132  }
3133
3134  virtual void DescribeNegationTo(::std::ostream* os) const {
3135    *os << "is not divisible by 7";
3136  }
3137};
3138
3139inline Matcher<int> DivisibleBy7() {
3140  return MakeMatcher(new DivisibleBy7Matcher);
3141}
3142...
3143
3144  EXPECT_CALL(foo, Bar(DivisibleBy7()));
3145```
3146
3147You may improve the matcher message by streaming additional
3148information to the `listener` argument in `MatchAndExplain()`:
3149
3150```
3151class DivisibleBy7Matcher : public MatcherInterface<int> {
3152 public:
3153  virtual bool MatchAndExplain(int n,
3154                               MatchResultListener* listener) const {
3155    const int remainder = n % 7;
3156    if (remainder != 0) {
3157      *listener << "the remainder is " << remainder;
3158    }
3159    return remainder == 0;
3160  }
3161  ...
3162};
3163```
3164
3165Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this:
3166```
3167Value of: x
3168Expected: is divisible by 7
3169  Actual: 23 (the remainder is 2)
3170```
3171
3172## Writing New Polymorphic Matchers ##
3173
3174You've learned how to write your own matchers in the previous
3175recipe. Just one problem: a matcher created using `MakeMatcher()` only
3176works for one particular type of arguments. If you want a
3177_polymorphic_ matcher that works with arguments of several types (for
3178instance, `Eq(x)` can be used to match a `value` as long as `value` ==
3179`x` compiles -- `value` and `x` don't have to share the same type),
3180you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit
3181involved.
3182
3183Fortunately, most of the time you can define a polymorphic matcher
3184easily with the help of `MakePolymorphicMatcher()`. Here's how you can
3185define `NotNull()` as an example:
3186
3187```
3188using ::testing::MakePolymorphicMatcher;
3189using ::testing::MatchResultListener;
3190using ::testing::NotNull;
3191using ::testing::PolymorphicMatcher;
3192
3193class NotNullMatcher {
3194 public:
3195  // To implement a polymorphic matcher, first define a COPYABLE class
3196  // that has three members MatchAndExplain(), DescribeTo(), and
3197  // DescribeNegationTo(), like the following.
3198
3199  // In this example, we want to use NotNull() with any pointer, so
3200  // MatchAndExplain() accepts a pointer of any type as its first argument.
3201  // In general, you can define MatchAndExplain() as an ordinary method or
3202  // a method template, or even overload it.
3203  template <typename T>
3204  bool MatchAndExplain(T* p,
3205                       MatchResultListener* /* listener */) const {
3206    return p != NULL;
3207  }
3208
3209  // Describes the property of a value matching this matcher.
3210  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
3211
3212  // Describes the property of a value NOT matching this matcher.
3213  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
3214};
3215
3216// To construct a polymorphic matcher, pass an instance of the class
3217// to MakePolymorphicMatcher().  Note the return type.
3218inline PolymorphicMatcher<NotNullMatcher> NotNull() {
3219  return MakePolymorphicMatcher(NotNullMatcher());
3220}
3221...
3222
3223  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.
3224```
3225
3226**Note:** Your polymorphic matcher class does **not** need to inherit from
3227`MatcherInterface` or any other class, and its methods do **not** need
3228to be virtual.
3229
3230Like in a monomorphic matcher, you may explain the match result by
3231streaming additional information to the `listener` argument in
3232`MatchAndExplain()`.
3233
3234## Writing New Cardinalities ##
3235
3236A cardinality is used in `Times()` to tell Google Mock how many times
3237you expect a call to occur. It doesn't have to be exact. For example,
3238you can say `AtLeast(5)` or `Between(2, 4)`.
3239
3240If the built-in set of cardinalities doesn't suit you, you are free to
3241define your own by implementing the following interface (in namespace
3242`testing`):
3243
3244```
3245class CardinalityInterface {
3246 public:
3247  virtual ~CardinalityInterface();
3248
3249  // Returns true iff call_count calls will satisfy this cardinality.
3250  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
3251
3252  // Returns true iff call_count calls will saturate this cardinality.
3253  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
3254
3255  // Describes self to an ostream.
3256  virtual void DescribeTo(::std::ostream* os) const = 0;
3257};
3258```
3259
3260For example, to specify that a call must occur even number of times,
3261you can write
3262
3263```
3264using ::testing::Cardinality;
3265using ::testing::CardinalityInterface;
3266using ::testing::MakeCardinality;
3267
3268class EvenNumberCardinality : public CardinalityInterface {
3269 public:
3270  virtual bool IsSatisfiedByCallCount(int call_count) const {
3271    return (call_count % 2) == 0;
3272  }
3273
3274  virtual bool IsSaturatedByCallCount(int call_count) const {
3275    return false;
3276  }
3277
3278  virtual void DescribeTo(::std::ostream* os) const {
3279    *os << "called even number of times";
3280  }
3281};
3282
3283Cardinality EvenNumber() {
3284  return MakeCardinality(new EvenNumberCardinality);
3285}
3286...
3287
3288  EXPECT_CALL(foo, Bar(3))
3289      .Times(EvenNumber());
3290```
3291
3292## Writing New Actions Quickly ##
3293
3294If the built-in actions don't work for you, and you find it
3295inconvenient to use `Invoke()`, you can use a macro from the `ACTION*`
3296family to quickly define a new action that can be used in your code as
3297if it's a built-in action.
3298
3299By writing
3300```
3301ACTION(name) { statements; }
3302```
3303in a namespace scope (i.e. not inside a class or function), you will
3304define an action with the given name that executes the statements.
3305The value returned by `statements` will be used as the return value of
3306the action.  Inside the statements, you can refer to the K-th
3307(0-based) argument of the mock function as `argK`.  For example:
3308```
3309ACTION(IncrementArg1) { return ++(*arg1); }
3310```
3311allows you to write
3312```
3313... WillOnce(IncrementArg1());
3314```
3315
3316Note that you don't need to specify the types of the mock function
3317arguments.  Rest assured that your code is type-safe though:
3318you'll get a compiler error if `*arg1` doesn't support the `++`
3319operator, or if the type of `++(*arg1)` isn't compatible with the mock
3320function's return type.
3321
3322Another example:
3323```
3324ACTION(Foo) {
3325  (*arg2)(5);
3326  Blah();
3327  *arg1 = 0;
3328  return arg0;
3329}
3330```
3331defines an action `Foo()` that invokes argument #2 (a function pointer)
3332with 5, calls function `Blah()`, sets the value pointed to by argument
3333#1 to 0, and returns argument #0.
3334
3335For more convenience and flexibility, you can also use the following
3336pre-defined symbols in the body of `ACTION`:
3337
3338| `argK_type` | The type of the K-th (0-based) argument of the mock function |
3339|:------------|:-------------------------------------------------------------|
3340| `args`      | All arguments of the mock function as a tuple                |
3341| `args_type` | The type of all arguments of the mock function as a tuple    |
3342| `return_type` | The return type of the mock function                         |
3343| `function_type` | The type of the mock function                                |
3344
3345For example, when using an `ACTION` as a stub action for mock function:
3346```
3347int DoSomething(bool flag, int* ptr);
3348```
3349we have:
3350| **Pre-defined Symbol** | **Is Bound To** |
3351|:-----------------------|:----------------|
3352| `arg0`                 | the value of `flag` |
3353| `arg0_type`            | the type `bool` |
3354| `arg1`                 | the value of `ptr` |
3355| `arg1_type`            | the type `int*` |
3356| `args`                 | the tuple `(flag, ptr)` |
3357| `args_type`            | the type `::testing::tuple<bool, int*>` |
3358| `return_type`          | the type `int`  |
3359| `function_type`        | the type `int(bool, int*)` |
3360
3361## Writing New Parameterized Actions Quickly ##
3362
3363Sometimes you'll want to parameterize an action you define.  For that
3364we have another macro
3365```
3366ACTION_P(name, param) { statements; }
3367```
3368
3369For example,
3370```
3371ACTION_P(Add, n) { return arg0 + n; }
3372```
3373will allow you to write
3374```
3375// Returns argument #0 + 5.
3376... WillOnce(Add(5));
3377```
3378
3379For convenience, we use the term _arguments_ for the values used to
3380invoke the mock function, and the term _parameters_ for the values
3381used to instantiate an action.
3382
3383Note that you don't need to provide the type of the parameter either.
3384Suppose the parameter is named `param`, you can also use the
3385Google-Mock-defined symbol `param_type` to refer to the type of the
3386parameter as inferred by the compiler.  For example, in the body of
3387`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`.
3388
3389Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support
3390multi-parameter actions.  For example,
3391```
3392ACTION_P2(ReturnDistanceTo, x, y) {
3393  double dx = arg0 - x;
3394  double dy = arg1 - y;
3395  return sqrt(dx*dx + dy*dy);
3396}
3397```
3398lets you write
3399```
3400... WillOnce(ReturnDistanceTo(5.0, 26.5));
3401```
3402
3403You can view `ACTION` as a degenerated parameterized action where the
3404number of parameters is 0.
3405
3406You can also easily define actions overloaded on the number of parameters:
3407```
3408ACTION_P(Plus, a) { ... }
3409ACTION_P2(Plus, a, b) { ... }
3410```
3411
3412## Restricting the Type of an Argument or Parameter in an ACTION ##
3413
3414For maximum brevity and reusability, the `ACTION*` macros don't ask
3415you to provide the types of the mock function arguments and the action
3416parameters.  Instead, we let the compiler infer the types for us.
3417
3418Sometimes, however, we may want to be more explicit about the types.
3419There are several tricks to do that.  For example:
3420```
3421ACTION(Foo) {
3422  // Makes sure arg0 can be converted to int.
3423  int n = arg0;
3424  ... use n instead of arg0 here ...
3425}
3426
3427ACTION_P(Bar, param) {
3428  // Makes sure the type of arg1 is const char*.
3429  ::testing::StaticAssertTypeEq<const char*, arg1_type>();
3430
3431  // Makes sure param can be converted to bool.
3432  bool flag = param;
3433}
3434```
3435where `StaticAssertTypeEq` is a compile-time assertion in Google Test
3436that verifies two types are the same.
3437
3438## Writing New Action Templates Quickly ##
3439
3440Sometimes you want to give an action explicit template parameters that
3441cannot be inferred from its value parameters.  `ACTION_TEMPLATE()`
3442supports that and can be viewed as an extension to `ACTION()` and
3443`ACTION_P*()`.
3444
3445The syntax:
3446```
3447ACTION_TEMPLATE(ActionName,
3448                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
3449                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
3450```
3451
3452defines an action template that takes _m_ explicit template parameters
3453and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is
3454between 0 and 10.  `name_i` is the name of the i-th template
3455parameter, and `kind_i` specifies whether it's a `typename`, an
3456integral constant, or a template.  `p_i` is the name of the i-th value
3457parameter.
3458
3459Example:
3460```
3461// DuplicateArg<k, T>(output) converts the k-th argument of the mock
3462// function to type T and copies it to *output.
3463ACTION_TEMPLATE(DuplicateArg,
3464                // Note the comma between int and k:
3465                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
3466                AND_1_VALUE_PARAMS(output)) {
3467  *output = T(::testing::get<k>(args));
3468}
3469```
3470
3471To create an instance of an action template, write:
3472```
3473  ActionName<t1, ..., t_m>(v1, ..., v_n)
3474```
3475where the `t`s are the template arguments and the
3476`v`s are the value arguments.  The value argument
3477types are inferred by the compiler.  For example:
3478```
3479using ::testing::_;
3480...
3481  int n;
3482  EXPECT_CALL(mock, Foo(_, _))
3483      .WillOnce(DuplicateArg<1, unsigned char>(&n));
3484```
3485
3486If you want to explicitly specify the value argument types, you can
3487provide additional template arguments:
3488```
3489  ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
3490```
3491where `u_i` is the desired type of `v_i`.
3492
3493`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the
3494number of value parameters, but not on the number of template
3495parameters.  Without the restriction, the meaning of the following is
3496unclear:
3497
3498```
3499  OverloadedAction<int, bool>(x);
3500```
3501
3502Are we using a single-template-parameter action where `bool` refers to
3503the type of `x`, or a two-template-parameter action where the compiler
3504is asked to infer the type of `x`?
3505
3506## Using the ACTION Object's Type ##
3507
3508If you are writing a function that returns an `ACTION` object, you'll
3509need to know its type.  The type depends on the macro used to define
3510the action and the parameter types.  The rule is relatively simple:
3511| **Given Definition** | **Expression** | **Has Type** |
3512|:---------------------|:---------------|:-------------|
3513| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
3514| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` |   `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
3515| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
3516| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` |
3517| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
3518| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` |
3519| ...                  | ...            | ...          |
3520
3521Note that we have to pick different suffixes (`Action`, `ActionP`,
3522`ActionP2`, and etc) for actions with different numbers of value
3523parameters, or the action definitions cannot be overloaded on the
3524number of them.
3525
3526## Writing New Monomorphic Actions ##
3527
3528While the `ACTION*` macros are very convenient, sometimes they are
3529inappropriate.  For example, despite the tricks shown in the previous
3530recipes, they don't let you directly specify the types of the mock
3531function arguments and the action parameters, which in general leads
3532to unoptimized compiler error messages that can baffle unfamiliar
3533users.  They also don't allow overloading actions based on parameter
3534types without jumping through some hoops.
3535
3536An alternative to the `ACTION*` macros is to implement
3537`::testing::ActionInterface<F>`, where `F` is the type of the mock
3538function in which the action will be used. For example:
3539
3540```
3541template <typename F>class ActionInterface {
3542 public:
3543  virtual ~ActionInterface();
3544
3545  // Performs the action.  Result is the return type of function type
3546  // F, and ArgumentTuple is the tuple of arguments of F.
3547  //
3548  // For example, if F is int(bool, const string&), then Result would
3549  // be int, and ArgumentTuple would be ::testing::tuple<bool, const string&>.
3550  virtual Result Perform(const ArgumentTuple& args) = 0;
3551};
3552
3553using ::testing::_;
3554using ::testing::Action;
3555using ::testing::ActionInterface;
3556using ::testing::MakeAction;
3557
3558typedef int IncrementMethod(int*);
3559
3560class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
3561 public:
3562  virtual int Perform(const ::testing::tuple<int*>& args) {
3563    int* p = ::testing::get<0>(args);  // Grabs the first argument.
3564    return *p++;
3565  }
3566};
3567
3568Action<IncrementMethod> IncrementArgument() {
3569  return MakeAction(new IncrementArgumentAction);
3570}
3571...
3572
3573  EXPECT_CALL(foo, Baz(_))
3574      .WillOnce(IncrementArgument());
3575
3576  int n = 5;
3577  foo.Baz(&n);  // Should return 5 and change n to 6.
3578```
3579
3580## Writing New Polymorphic Actions ##
3581
3582The previous recipe showed you how to define your own action. This is
3583all good, except that you need to know the type of the function in
3584which the action will be used. Sometimes that can be a problem. For
3585example, if you want to use the action in functions with _different_
3586types (e.g. like `Return()` and `SetArgPointee()`).
3587
3588If an action can be used in several types of mock functions, we say
3589it's _polymorphic_. The `MakePolymorphicAction()` function template
3590makes it easy to define such an action:
3591
3592```
3593namespace testing {
3594
3595template <typename Impl>
3596PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);
3597
3598}  // namespace testing
3599```
3600
3601As an example, let's define an action that returns the second argument
3602in the mock function's argument list. The first step is to define an
3603implementation class:
3604
3605```
3606class ReturnSecondArgumentAction {
3607 public:
3608  template <typename Result, typename ArgumentTuple>
3609  Result Perform(const ArgumentTuple& args) const {
3610    // To get the i-th (0-based) argument, use ::testing::get<i>(args).
3611    return ::testing::get<1>(args);
3612  }
3613};
3614```
3615
3616This implementation class does _not_ need to inherit from any
3617particular class. What matters is that it must have a `Perform()`
3618method template. This method template takes the mock function's
3619arguments as a tuple in a **single** argument, and returns the result of
3620the action. It can be either `const` or not, but must be invokable
3621with exactly one template argument, which is the result type. In other
3622words, you must be able to call `Perform<R>(args)` where `R` is the
3623mock function's return type and `args` is its arguments in a tuple.
3624
3625Next, we use `MakePolymorphicAction()` to turn an instance of the
3626implementation class into the polymorphic action we need. It will be
3627convenient to have a wrapper for this:
3628
3629```
3630using ::testing::MakePolymorphicAction;
3631using ::testing::PolymorphicAction;
3632
3633PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
3634  return MakePolymorphicAction(ReturnSecondArgumentAction());
3635}
3636```
3637
3638Now, you can use this polymorphic action the same way you use the
3639built-in ones:
3640
3641```
3642using ::testing::_;
3643
3644class MockFoo : public Foo {
3645 public:
3646  MOCK_METHOD2(DoThis, int(bool flag, int n));
3647  MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
3648};
3649...
3650
3651  MockFoo foo;
3652  EXPECT_CALL(foo, DoThis(_, _))
3653      .WillOnce(ReturnSecondArgument());
3654  EXPECT_CALL(foo, DoThat(_, _, _))
3655      .WillOnce(ReturnSecondArgument());
3656  ...
3657  foo.DoThis(true, 5);         // Will return 5.
3658  foo.DoThat(1, "Hi", "Bye");  // Will return "Hi".
3659```
3660
3661## Teaching Google Mock How to Print Your Values ##
3662
3663When an uninteresting or unexpected call occurs, Google Mock prints the
3664argument values and the stack trace to help you debug.  Assertion
3665macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in
3666question when the assertion fails.  Google Mock and Google Test do this using
3667Google Test's user-extensible value printer.
3668
3669This printer knows how to print built-in C++ types, native arrays, STL
3670containers, and any type that supports the `<<` operator.  For other
3671types, it prints the raw bytes in the value and hopes that you the
3672user can figure it out.
3673[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values)
3674explains how to extend the printer to do a better job at
3675printing your particular type than to dump the bytes.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/DesignDoc.md
r0r249096
1This page discusses the design of new Google Mock features.
2
3
4
5# Macros for Defining Actions #
6
7## Problem ##
8
9Due to the lack of closures in C++, it currently requires some
10non-trivial effort to define a custom action in Google Mock.  For
11example, suppose you want to "increment the value pointed to by the
12second argument of the mock function and return it", you could write:
13
14```
15int IncrementArg1(Unused, int* p, Unused) {
16  return ++(*p);
17}
18
19... WillOnce(Invoke(IncrementArg1));
20```
21
22There are several things unsatisfactory about this approach:
23
24  * Even though the action only cares about the second argument of the mock function, its definition needs to list other arguments as dummies.  This is tedious.
25  * The defined action is usable only in mock functions that takes exactly 3 arguments - an unnecessary restriction.
26  * To use the action, one has to say `Invoke(IncrementArg1)`, which isn't as nice as `IncrementArg1()`.
27
28The latter two problems can be overcome using `MakePolymorphicAction()`,
29but it requires much more boilerplate code:
30
31```
32class IncrementArg1Action {
33 public:
34  template <typename Result, typename ArgumentTuple>
35  Result Perform(const ArgumentTuple& args) const {
36    return ++(*tr1::get<1>(args));
37  }
38};
39
40PolymorphicAction<IncrementArg1Action> IncrementArg1() {
41  return MakePolymorphicAction(IncrementArg1Action());
42}
43
44... WillOnce(IncrementArg1());
45```
46
47Our goal is to allow defining custom actions with the least amount of
48boiler-plate C++ requires.
49
50## Solution ##
51
52We propose to introduce a new macro:
53```
54ACTION(name) { statements; }
55```
56
57Using this in a namespace scope will define an action with the given
58name that executes the statements.  Inside the statements, you can
59refer to the K-th (0-based) argument of the mock function as `argK`.
60For example:
61```
62ACTION(IncrementArg1) { return ++(*arg1); }
63```
64allows you to write
65```
66... WillOnce(IncrementArg1());
67```
68
69Note that you don't need to specify the types of the mock function
70arguments, as brevity is a top design goal here.  Rest assured that
71your code is still type-safe though: you'll get a compiler error if
72`*arg1` doesn't support the `++` operator, or if the type of
73`++(*arg1)` isn't compatible with the mock function's return type.
74
75Another example:
76```
77ACTION(Foo) {
78  (*arg2)(5);
79  Blah();
80  *arg1 = 0;
81  return arg0;
82}
83```
84defines an action `Foo()` that invokes argument #2 (a function pointer)
85with 5, calls function `Blah()`, sets the value pointed to by argument
86#1 to 0, and returns argument #0.
87
88For more convenience and flexibility, you can also use the following
89pre-defined symbols in the body of `ACTION`:
90
91| `argK_type` | The type of the K-th (0-based) argument of the mock function |
92|:------------|:-------------------------------------------------------------|
93| `args`      | All arguments of the mock function as a tuple                |
94| `args_type` | The type of all arguments of the mock function as a tuple    |
95| `return_type` | The return type of the mock function                         |
96| `function_type` | The type of the mock function                                |
97
98For example, when using an `ACTION` as a stub action for mock function:
99```
100int DoSomething(bool flag, int* ptr);
101```
102we have:
103| **Pre-defined Symbol** | **Is Bound To** |
104|:-----------------------|:----------------|
105| `arg0`                 | the value of `flag` |
106| `arg0_type`            | the type `bool` |
107| `arg1`                 | the value of `ptr` |
108| `arg1_type`            | the type `int*` |
109| `args`                 | the tuple `(flag, ptr)` |
110| `args_type`            | the type `std::tr1::tuple<bool, int*>` |
111| `return_type`          | the type `int`  |
112| `function_type`        | the type `int(bool, int*)` |
113
114## Parameterized actions ##
115
116Sometimes you'll want to parameterize the action.   For that we propose
117another macro
118```
119ACTION_P(name, param) { statements; }
120```
121
122For example,
123```
124ACTION_P(Add, n) { return arg0 + n; }
125```
126will allow you to write
127```
128// Returns argument #0 + 5.
129... WillOnce(Add(5));
130```
131
132For convenience, we use the term _arguments_ for the values used to
133invoke the mock function, and the term _parameters_ for the values
134used to instantiate an action.
135
136Note that you don't need to provide the type of the parameter either.
137Suppose the parameter is named `param`, you can also use the
138Google-Mock-defined symbol `param_type` to refer to the type of the
139parameter as inferred by the compiler.
140
141We will also provide `ACTION_P2`, `ACTION_P3`, and etc to support
142multi-parameter actions.  For example,
143```
144ACTION_P2(ReturnDistanceTo, x, y) {
145  double dx = arg0 - x;
146  double dy = arg1 - y;
147  return sqrt(dx*dx + dy*dy);
148}
149```
150lets you write
151```
152... WillOnce(ReturnDistanceTo(5.0, 26.5));
153```
154
155You can view `ACTION` as a degenerated parameterized action where the
156number of parameters is 0.
157
158## Advanced Usages ##
159
160### Overloading Actions ###
161
162You can easily define actions overloaded on the number of parameters:
163```
164ACTION_P(Plus, a) { ... }
165ACTION_P2(Plus, a, b) { ... }
166```
167
168### Restricting the Type of an Argument or Parameter ###
169
170For maximum brevity and reusability, the `ACTION*` macros don't let
171you specify the types of the mock function arguments and the action
172parameters.  Instead, we let the compiler infer the types for us.
173
174Sometimes, however, we may want to be more explicit about the types.
175There are several tricks to do that.  For example:
176```
177ACTION(Foo) {
178  // Makes sure arg0 can be converted to int.
179  int n = arg0;
180  ... use n instead of arg0 here ...
181}
182
183ACTION_P(Bar, param) {
184  // Makes sure the type of arg1 is const char*.
185  ::testing::StaticAssertTypeEq<const char*, arg1_type>();
186
187  // Makes sure param can be converted to bool.
188  bool flag = param;
189}
190```
191where `StaticAssertTypeEq` is a compile-time assertion we plan to add to
192Google Test (the name is chosen to match `static_assert` in C++0x).
193
194### Using the ACTION Object's Type ###
195
196If you are writing a function that returns an `ACTION` object, you'll
197need to know its type.  The type depends on the macro used to define
198the action and the parameter types.  The rule is relatively simple:
199| **Given Definition** | **Expression** | **Has Type** |
200|:---------------------|:---------------|:-------------|
201| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
202| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
203| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
204| ...                  | ...            | ...          |
205
206Note that we have to pick different suffixes (`Action`, `ActionP`,
207`ActionP2`, and etc) for actions with different numbers of parameters,
208or the action definitions cannot be overloaded on the number of
209parameters.
210
211## When to Use ##
212
213While the new macros are very convenient, please also consider other
214means of implementing actions (e.g. via `ActionInterface` or
215`MakePolymorphicAction()`), especially if you need to use the defined
216action a lot.  While the other approaches require more work, they give
217you more control on the types of the mock function arguments and the
218action parameters, which in general leads to better compiler error
219messages that pay off in the long run.  They also allow overloading
220actions based on parameter types, as opposed to just the number of
221parameters.
222
223## Related Work ##
224
225As you may have realized, the `ACTION*` macros resemble closures (also
226known as lambda expressions or anonymous functions).  Indeed, both of
227them seek to lower the syntactic overhead for defining a function.
228
229C++0x will support lambdas, but they are not part of C++ right now.
230Some non-standard libraries (most notably BLL or Boost Lambda Library)
231try to alleviate this problem.  However, they are not a good choice
232for defining actions as:
233
234  * They are non-standard and not widely installed.  Google Mock only depends on standard libraries and `tr1::tuple`, which is part of the new C++ standard and comes with gcc 4+.  We want to keep it that way.
235  * They are not trivial to learn.
236  * They will become obsolete when C++0x's lambda feature is widely supported.  We don't want to make our users use a dying library.
237  * Since they are based on operators, they are rather ad hoc: you cannot use statements, and you cannot pass the lambda arguments to a function, for example.
238  * They have subtle semantics that easily confuses new users.  For example, in expression `_1++ + foo++`, `foo` will be incremented only once where the expression is evaluated, while `_1` will be incremented every time the unnamed function is invoked.  This is far from intuitive.
239
240`ACTION*` avoid all these problems.
241
242## Future Improvements ##
243
244There may be a need for composing `ACTION*` definitions (i.e. invoking
245another `ACTION` inside the definition of one `ACTION*`).  We are not
246sure we want it yet, as one can get a similar effect by putting
247`ACTION` definitions in function templates and composing the function
248templates.  We'll revisit this based on user feedback.
249
250The reason we don't allow `ACTION*()` inside a function body is that
251the current C++ standard doesn't allow function-local types to be used
252to instantiate templates.  The upcoming C++0x standard will lift this
253restriction.  Once this feature is widely supported by compilers, we
254can revisit the implementation and add support for using `ACTION*()`
255inside a function.
256
257C++0x will also support lambda expressions.  When they become
258available, we may want to support using lambdas as actions.
259
260# Macros for Defining Matchers #
261
262Once the macros for defining actions are implemented, we plan to do
263the same for matchers:
264
265```
266MATCHER(name) { statements; }
267```
268
269where you can refer to the value being matched as `arg`.  For example,
270given:
271
272```
273MATCHER(IsPositive) { return arg > 0; }
274```
275
276you can use `IsPositive()` as a matcher that matches a value iff it is
277greater than 0.
278
279We will also add `MATCHER_P`, `MATCHER_P2`, and etc for parameterized
280matchers.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/DevGuide.md
r0r249096
1
2
3If you are interested in understanding the internals of Google Mock,
4building from source, or contributing ideas or modifications to the
5project, then this document is for you.
6
7# Introduction #
8
9First, let's give you some background of the project.
10
11## Licensing ##
12
13All Google Mock source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php).
14
15## The Google Mock Community ##
16
17The Google Mock community exists primarily through the [discussion group](http://groups.google.com/group/googlemock), the
18[issue tracker](http://code.google.com/p/googlemock/issues/list) and, to a lesser extent, the [source control repository](http://code.google.com/p/googlemock/source/checkout). You are definitely encouraged to contribute to the
19discussion and you can also help us to keep the effectiveness of the
20group high by following and promoting the guidelines listed here.
21
22### Please Be Friendly ###
23
24Showing courtesy and respect to others is a vital part of the Google
25culture, and we strongly encourage everyone participating in Google
26Mock development to join us in accepting nothing less. Of course,
27being courteous is not the same as failing to constructively disagree
28with each other, but it does mean that we should be respectful of each
29other when enumerating the 42 technical reasons that a particular
30proposal may not be the best choice. There's never a reason to be
31antagonistic or dismissive toward anyone who is sincerely trying to
32contribute to a discussion.
33
34Sure, C++ testing is serious business and all that, but it's also
35a lot of fun. Let's keep it that way. Let's strive to be one of the
36friendliest communities in all of open source.
37
38### Where to Discuss Google Mock ###
39
40As always, discuss Google Mock in the official [Google C++ Mocking Framework discussion group](http://groups.google.com/group/googlemock).  You don't have to actually submit
41code in order to sign up. Your participation itself is a valuable
42contribution.
43
44# Working with the Code #
45
46If you want to get your hands dirty with the code inside Google Mock,
47this is the section for you.
48
49## Checking Out the Source from Subversion ##
50
51Checking out the Google Mock source is most useful if you plan to
52tweak it yourself.  You check out the source for Google Mock using a
53[Subversion](http://subversion.tigris.org/) client as you would for any
54other project hosted on Google Code.  Please see the instruction on
55the [source code access page](http://code.google.com/p/googlemock/source/checkout) for how to do it.
56
57## Compiling from Source ##
58
59Once you check out the code, you can find instructions on how to
60compile it in the [README](http://code.google.com/p/googlemock/source/browse/trunk/README) file.
61
62## Testing ##
63
64A mocking framework is of no good if itself is not thoroughly tested.
65Tests should be written for any new code, and changes should be
66verified to not break existing tests before they are submitted for
67review. To perform the tests, follow the instructions in [README](http://code.google.com/p/googlemock/source/browse/trunk/README) and
68verify that there are no failures.
69
70# Contributing Code #
71
72We are excited that Google Mock is now open source, and hope to get
73great patches from the community. Before you fire up your favorite IDE
74and begin hammering away at that new feature, though, please take the
75time to read this section and understand the process. While it seems
76rigorous, we want to keep a high standard of quality in the code
77base.
78
79## Contributor License Agreements ##
80
81You must sign a Contributor License Agreement (CLA) before we can
82accept any code.  The CLA protects you and us.
83
84  * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html).
85  * If you work for a company that wants to allow you to contribute your work to Google Mock, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html).
86
87Follow either of the two links above to access the appropriate CLA and
88instructions for how to sign and return it.
89
90## Coding Style ##
91
92To keep the source consistent, readable, diffable and easy to merge,
93we use a fairly rigid coding style, as defined by the [google-styleguide](http://code.google.com/p/google-styleguide/) project.  All patches will be expected
94to conform to the style outlined [here](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
95
96## Submitting Patches ##
97
98Please do submit code. Here's what you need to do:
99
100  1. Normally you should make your change against the SVN trunk instead of a branch or a tag, as the latter two are for release control and should be treated mostly as read-only.
101  1. Decide which code you want to submit. A submission should be a set of changes that addresses one issue in the [Google Mock issue tracker](http://code.google.com/p/googlemock/issues/list). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one.
102  1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches.
103  1. Ensure that your code adheres to the [Google Mock source code style](#Coding_Style.md).
104  1. Ensure that there are unit tests for your code.
105  1. Sign a Contributor License Agreement.
106  1. Create a patch file using `svn diff`.
107  1. We use [Rietveld](http://codereview.appspot.com/) to do web-based code reviews.  You can read about the tool [here](http://code.google.com/p/rietveld/wiki/CodeReviewHelp).  When you are ready, upload your patch via Rietveld and notify `googlemock@googlegroups.com` to review it.  There are several ways to upload the patch.  We recommend using the [upload\_gmock.py](http://code.google.com/p/googlemock/source/browse/trunk/scripts/upload_gmock.py) script, which you can find in the `scripts/` folder in the SVN trunk.
108
109## Google Mock Committers ##
110
111The current members of the Google Mock engineering team are the only
112committers at present. In the great tradition of eating one's own
113dogfood, we will be requiring each new Google Mock engineering team
114member to earn the right to become a committer by following the
115procedures in this document, writing consistently great code, and
116demonstrating repeatedly that he or she truly gets the zen of Google
117Mock.
118
119# Release Process #
120
121We follow the typical release process for Subversion-based projects:
122
123  1. A release branch named `release-X.Y` is created.
124  1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable.
125  1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch.
126  1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time).
127  1. Go back to step 1 to create another release branch and so on.
128
129
130---
131
132This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project.  Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/).
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/Documentation.md
r0r249096
1This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)**
2- **if you use a released version of Google Mock, please read the documentation for that specific version instead.**
3
4  * [ForDummies](ForDummies.md) -- start here if you are new to Google Mock.
5  * [CheatSheet](CheatSheet.md) -- a quick reference.
6  * [CookBook](CookBook.md) -- recipes for doing various tasks using Google Mock.
7  * [FrequentlyAskedQuestions](FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list.
8
9To contribute code to Google Mock, read:
10
11  * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch.
12  * [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/ForDummies.md
r0r249096
1
2
3(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).)
4
5# What Is Google C++ Mocking Framework? #
6When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc).
7
8**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community:
9
10  * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
11  * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive.
12
13If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks.
14
15**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java.
16
17Using Google Mock involves three basic steps:
18
19  1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class;
20  1. Create some mock objects and specify its expectations and behavior using an intuitive syntax;
21  1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises.
22
23# Why Google Mock? #
24While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_:
25
26  * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it.
27  * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions.
28  * The knowledge you gained from using one mock doesn't transfer to the next.
29
30In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference.
31
32Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you:
33
34  * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid".
35  * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database).
36  * Your tests are brittle as some resources they use are unreliable (e.g. the network).
37  * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one.
38  * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best.
39  * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks.
40
41We encourage you to use Google Mock as:
42
43  * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs!
44  * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators.
45
46# Getting Started #
47Using Google Mock is easy! Inside your C++ source file, just #include `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go.
48
49# A Case for Mock Turtles #
50Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
51
52```
53class Turtle {
54  ...
55  virtual ~Turtle() {}
56  virtual void PenUp() = 0;
57  virtual void PenDown() = 0;
58  virtual void Forward(int distance) = 0;
59  virtual void Turn(int degrees) = 0;
60  virtual void GoTo(int x, int y) = 0;
61  virtual int GetX() const = 0;
62  virtual int GetY() const = 0;
63};
64```
65
66(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.)
67
68You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle.
69
70Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_.
71
72# Writing the Mock Class #
73If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.)
74
75## How to Define It ##
76Using the `Turtle` interface as example, here are the simple steps you need to follow:
77
78  1. Derive a class `MockTurtle` from `Turtle`.
79  1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has.
80  1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so.
81  1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_).
82  1. Repeat until all virtual functions you want to mock are done.
83
84After the process, you should have something like:
85
86```
87#include "gmock/gmock.h"  // Brings in Google Mock.
88class MockTurtle : public Turtle {
89 public:
90  ...
91  MOCK_METHOD0(PenUp, void());
92  MOCK_METHOD0(PenDown, void());
93  MOCK_METHOD1(Forward, void(int distance));
94  MOCK_METHOD1(Turn, void(int degrees));
95  MOCK_METHOD2(GoTo, void(int x, int y));
96  MOCK_CONST_METHOD0(GetX, int());
97  MOCK_CONST_METHOD0(GetY, int());
98};
99```
100
101You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins.
102
103**Tip:** If even this is too much work for you, you'll find the
104`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful.  This command-line
105tool requires that you have Python 2.4 installed.  You give it a C++ file and the name of an abstract class defined in it,
106and it will print the definition of the mock class for you.  Due to the
107complexity of the C++ language, this script may not always work, but
108it can be quite handy when it does.  For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README).
109
110## Where to Put It ##
111When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?)
112
113So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed.
114
115Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does.
116
117# Using Mocks in Tests #
118Once you have a mock class, using it is easy. The typical work flow is:
119
120  1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.).
121  1. Create some mock objects.
122  1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.).
123  1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately.
124  1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.
125
126Here's an example:
127
128```
129#include "path/to/mock-turtle.h"
130#include "gmock/gmock.h"
131#include "gtest/gtest.h"
132using ::testing::AtLeast;                     // #1
133
134TEST(PainterTest, CanDrawSomething) {
135  MockTurtle turtle;                          // #2
136  EXPECT_CALL(turtle, PenDown())              // #3
137      .Times(AtLeast(1));
138
139  Painter painter(&turtle);                   // #4
140
141  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
142}                                             // #5
143
144int main(int argc, char** argv) {
145  // The following line must be executed to initialize Google Mock
146  // (and Google Test) before running the tests.
147  ::testing::InitGoogleMock(&argc, argv);
148  return RUN_ALL_TESTS();
149}
150```
151
152As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this:
153
154```
155path/to/my_test.cc:119: Failure
156Actual function call count doesn't match this expectation:
157Actually: never called;
158Expected: called at least once.
159```
160
161**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation.
162
163**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap.
164
165**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions.
166
167This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier.
168
169Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks.
170
171## Using Google Mock with Any Testing Framework ##
172If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or
173[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to:
174```
175int main(int argc, char** argv) {
176  // The following line causes Google Mock to throw an exception on failure,
177  // which will be interpreted by your testing framework as a test failure.
178  ::testing::GTEST_FLAG(throw_on_failure) = true;
179  ::testing::InitGoogleMock(&argc, argv);
180  ... whatever your testing framework requires ...
181}
182```
183
184This approach has a catch: it makes Google Mock throw an exception
185from a mock object's destructor sometimes.  With some compilers, this
186sometimes causes the test program to crash.  You'll still be able to
187notice that the test has failed, but it's not a graceful failure.
188
189A better solution is to use Google Test's
190[event listener API](http://code.google.com/p/googletest/wiki/AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events)
191to report a test failure to your testing framework properly.  You'll need to
192implement the `OnTestPartResult()` method of the event listener interface, but it
193should be straightforward.
194
195If this turns out to be too much work, we suggest that you stick with
196Google Test, which works with Google Mock seamlessly (in fact, it is
197technically part of Google Mock.).  If there is a reason that you
198cannot use Google Test, please let us know.
199
200# Setting Expectations #
201The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right."
202
203## General Syntax ##
204In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
205
206```
207EXPECT_CALL(mock_object, method(matchers))
208    .Times(cardinality)
209    .WillOnce(action)
210    .WillRepeatedly(action);
211```
212
213The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.)
214
215The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections.
216
217This syntax is designed to make an expectation read like English. For example, you can probably guess that
218
219```
220using ::testing::Return;...
221EXPECT_CALL(turtle, GetX())
222    .Times(5)
223    .WillOnce(Return(100))
224    .WillOnce(Return(150))
225    .WillRepeatedly(Return(200));
226```
227
228says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL).
229
230**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier.
231
232## Matchers: What Arguments Do We Expect? ##
233When a mock function takes arguments, we must specify what arguments we are expecting; for example:
234
235```
236// Expects the turtle to move forward by 100 units.
237EXPECT_CALL(turtle, Forward(100));
238```
239
240Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
241
242```
243using ::testing::_;
244...
245// Expects the turtle to move forward.
246EXPECT_CALL(turtle, Forward(_));
247```
248
249`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected.
250
251A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
252
253```
254using ::testing::Ge;...
255EXPECT_CALL(turtle, Forward(Ge(100)));
256```
257
258This checks that the turtle will be told to go forward by at least 100 units.
259
260## Cardinalities: How Many Times Will It Be Called? ##
261The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly.
262
263An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called.
264
265We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](CheatSheet.md).
266
267The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember:
268
269  * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
270  * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`.
271  * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`.
272
273**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times?
274
275## Actions: What Should It Do? ##
276Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock.
277
278First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). In addition, in C++ 11 and above, a mock function whose return type is default-constructible (i.e. has a default constructor) has a default action of returning a default-constructed value.  If you don't say anything, this behavior will be used.
279
280Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
281
282```
283using ::testing::Return;...
284EXPECT_CALL(turtle, GetX())
285    .WillOnce(Return(100))
286    .WillOnce(Return(200))
287    .WillOnce(Return(300));
288```
289
290This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
291
292```
293using ::testing::Return;...
294EXPECT_CALL(turtle, GetY())
295    .WillOnce(Return(100))
296    .WillOnce(Return(200))
297    .WillRepeatedly(Return(300));
298```
299
300says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on.
301
302Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).
303
304What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/CheatSheet#Actions).
305
306**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
307
308```
309int n = 100;
310EXPECT_CALL(turtle, GetX())
311.Times(4)
312.WillRepeatedly(Return(n++));
313```
314
315Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](CookBook.md).
316
317Time for another quiz! What do you think the following means?
318
319```
320using ::testing::Return;...
321EXPECT_CALL(turtle, GetY())
322.Times(4)
323.WillOnce(Return(100));
324```
325
326Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions.
327
328## Using Multiple Expectations ##
329So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects.
330
331By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:
332
333```
334using ::testing::_;...
335EXPECT_CALL(turtle, Forward(_));  // #1
336EXPECT_CALL(turtle, Forward(10))  // #2
337    .Times(2);
338```
339
340If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation.
341
342**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it.
343
344## Ordered vs Unordered Calls ##
345By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified.
346
347Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
348
349```
350using ::testing::InSequence;...
351TEST(FooTest, DrawsLineSegment) {
352  ...
353  {
354    InSequence dummy;
355
356    EXPECT_CALL(turtle, PenDown());
357    EXPECT_CALL(turtle, Forward(100));
358    EXPECT_CALL(turtle, PenUp());
359  }
360  Foo();
361}
362```
363
364By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant.
365
366In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error.
367
368(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook#Expecting_Partially_Ordered_Calls.md).)
369
370## All Expectations Are Sticky (Unless Said Otherwise) ##
371Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)?
372
373After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
374
375```
376using ::testing::_;...
377EXPECT_CALL(turtle, GoTo(_, _))  // #1
378    .Times(AnyNumber());
379EXPECT_CALL(turtle, GoTo(0, 0))  // #2
380    .Times(2);
381```
382
383Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above.
384
385This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.).
386
387Simple? Let's see if you've really understood it: what does the following code say?
388
389```
390using ::testing::Return;
391...
392for (int i = n; i > 0; i--) {
393  EXPECT_CALL(turtle, GetX())
394      .WillOnce(Return(10*i));
395}
396```
397
398If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful!
399
400One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
401
402```
403using ::testing::Return;
404...
405for (int i = n; i > 0; i--) {
406  EXPECT_CALL(turtle, GetX())
407    .WillOnce(Return(10*i))
408    .RetiresOnSaturation();
409}
410```
411
412And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:
413
414```
415using ::testing::InSequence;
416using ::testing::Return;
417...
418{
419  InSequence s;
420
421  for (int i = 1; i <= n; i++) {
422    EXPECT_CALL(turtle, GetX())
423        .WillOnce(Return(10*i))
424        .RetiresOnSaturation();
425  }
426}
427```
428
429By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call).
430
431## Uninteresting Calls ##
432A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called.
433
434In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure.
435
436# What Now? #
437Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.
438
439Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/FrequentlyAskedQuestions.md
r0r249096
1
2
3Please send your questions to the
4[googlemock](http://groups.google.com/group/googlemock) discussion
5group. If you need help with compiler errors, make sure you have
6tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.
7
8## When I call a method on my mock object, the method for the real object is invoked instead.  What's the problem? ##
9
10In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/CookBook#Mocking_Nonvirtual_Methods).
11
12## I wrote some matchers.  After I upgraded to a new version of Google Mock, they no longer compile.  What's going on? ##
13
14After version 1.4.0 of Google Mock was released, we had an idea on how
15to make it easier to write matchers that can generate informative
16messages efficiently.  We experimented with this idea and liked what
17we saw.  Therefore we decided to implement it.
18
19Unfortunately, this means that if you have defined your own matchers
20by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
21your definitions will no longer compile.  Matchers defined using the
22`MATCHER*` family of macros are not affected.
23
24Sorry for the hassle if your matchers are affected.  We believe it's
25in everyone's long-term interest to make this change sooner than
26later.  Fortunately, it's usually not hard to migrate an existing
27matcher to the new API.  Here's what you need to do:
28
29If you wrote your matcher like this:
30```
31// Old matcher definition that doesn't work with the latest
32// Google Mock.
33using ::testing::MatcherInterface;
34...
35class MyWonderfulMatcher : public MatcherInterface<MyType> {
36 public:
37  ...
38  virtual bool Matches(MyType value) const {
39    // Returns true if value matches.
40    return value.GetFoo() > 5;
41  }
42  ...
43};
44```
45
46you'll need to change it to:
47```
48// New matcher definition that works with the latest Google Mock.
49using ::testing::MatcherInterface;
50using ::testing::MatchResultListener;
51...
52class MyWonderfulMatcher : public MatcherInterface<MyType> {
53 public:
54  ...
55  virtual bool MatchAndExplain(MyType value,
56                               MatchResultListener* listener) const {
57    // Returns true if value matches.
58    return value.GetFoo() > 5;
59  }
60  ...
61};
62```
63(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
64argument of type `MatchResultListener*`.)
65
66If you were also using `ExplainMatchResultTo()` to improve the matcher
67message:
68```
69// Old matcher definition that doesn't work with the lastest
70// Google Mock.
71using ::testing::MatcherInterface;
72...
73class MyWonderfulMatcher : public MatcherInterface<MyType> {
74 public:
75  ...
76  virtual bool Matches(MyType value) const {
77    // Returns true if value matches.
78    return value.GetFoo() > 5;
79  }
80
81  virtual void ExplainMatchResultTo(MyType value,
82                                    ::std::ostream* os) const {
83    // Prints some helpful information to os to help
84    // a user understand why value matches (or doesn't match).
85    *os << "the Foo property is " << value.GetFoo();
86  }
87  ...
88};
89```
90
91you should move the logic of `ExplainMatchResultTo()` into
92`MatchAndExplain()`, using the `MatchResultListener` argument where
93the `::std::ostream` was used:
94```
95// New matcher definition that works with the latest Google Mock.
96using ::testing::MatcherInterface;
97using ::testing::MatchResultListener;
98...
99class MyWonderfulMatcher : public MatcherInterface<MyType> {
100 public:
101  ...
102  virtual bool MatchAndExplain(MyType value,
103                               MatchResultListener* listener) const {
104    // Returns true if value matches.
105    *listener << "the Foo property is " << value.GetFoo();
106    return value.GetFoo() > 5;
107  }
108  ...
109};
110```
111
112If your matcher is defined using `MakePolymorphicMatcher()`:
113```
114// Old matcher definition that doesn't work with the latest
115// Google Mock.
116using ::testing::MakePolymorphicMatcher;
117...
118class MyGreatMatcher {
119 public:
120  ...
121  bool Matches(MyType value) const {
122    // Returns true if value matches.
123    return value.GetBar() < 42;
124  }
125  ...
126};
127... MakePolymorphicMatcher(MyGreatMatcher()) ...
128```
129
130you should rename the `Matches()` method to `MatchAndExplain()` and
131add a `MatchResultListener*` argument (the same as what you need to do
132for matchers defined by implementing `MatcherInterface`):
133```
134// New matcher definition that works with the latest Google Mock.
135using ::testing::MakePolymorphicMatcher;
136using ::testing::MatchResultListener;
137...
138class MyGreatMatcher {
139 public:
140  ...
141  bool MatchAndExplain(MyType value,
142                       MatchResultListener* listener) const {
143    // Returns true if value matches.
144    return value.GetBar() < 42;
145  }
146  ...
147};
148... MakePolymorphicMatcher(MyGreatMatcher()) ...
149```
150
151If your polymorphic matcher uses `ExplainMatchResultTo()` for better
152failure messages:
153```
154// Old matcher definition that doesn't work with the latest
155// Google Mock.
156using ::testing::MakePolymorphicMatcher;
157...
158class MyGreatMatcher {
159 public:
160  ...
161  bool Matches(MyType value) const {
162    // Returns true if value matches.
163    return value.GetBar() < 42;
164  }
165  ...
166};
167void ExplainMatchResultTo(const MyGreatMatcher& matcher,
168                          MyType value,
169                          ::std::ostream* os) {
170  // Prints some helpful information to os to help
171  // a user understand why value matches (or doesn't match).
172  *os << "the Bar property is " << value.GetBar();
173}
174... MakePolymorphicMatcher(MyGreatMatcher()) ...
175```
176
177you'll need to move the logic inside `ExplainMatchResultTo()` to
178`MatchAndExplain()`:
179```
180// New matcher definition that works with the latest Google Mock.
181using ::testing::MakePolymorphicMatcher;
182using ::testing::MatchResultListener;
183...
184class MyGreatMatcher {
185 public:
186  ...
187  bool MatchAndExplain(MyType value,
188                       MatchResultListener* listener) const {
189    // Returns true if value matches.
190    *listener << "the Bar property is " << value.GetBar();
191    return value.GetBar() < 42;
192  }
193  ...
194};
195... MakePolymorphicMatcher(MyGreatMatcher()) ...
196```
197
198For more information, you can read these
199[two](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Monomorphic_Matchers)
200[recipes](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Matchers)
201from the cookbook.  As always, you
202are welcome to post questions on `googlemock@googlegroups.com` if you
203need any help.
204
205## When using Google Mock, do I have to use Google Test as the testing framework?  I have my favorite testing framework and don't want to switch. ##
206
207Google Mock works out of the box with Google Test.  However, it's easy
208to configure it to work with any testing framework of your choice.
209[Here](http://code.google.com/p/googlemock/wiki/ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how.
210
211## How am I supposed to make sense of these horrible template errors? ##
212
213If you are confused by the compiler errors gcc threw at you,
214try consulting the _Google Mock Doctor_ tool first.  What it does is to
215scan stdin for gcc error messages, and spit out diagnoses on the
216problems (we call them diseases) your code has.
217
218To "install", run command:
219```
220alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
221```
222
223To use it, do:
224```
225<your-favorite-build-command> <your-test> 2>&1 | gmd
226```
227
228For example:
229```
230make my_test 2>&1 | gmd
231```
232
233Or you can run `gmd` and copy-n-paste gcc's error messages to it.
234
235## Can I mock a variadic function? ##
236
237You cannot mock a variadic function (i.e. a function taking ellipsis
238(`...`) arguments) directly in Google Mock.
239
240The problem is that in general, there is _no way_ for a mock object to
241know how many arguments are passed to the variadic method, and what
242the arguments' types are.  Only the _author of the base class_ knows
243the protocol, and we cannot look into his head.
244
245Therefore, to mock such a function, the _user_ must teach the mock
246object how to figure out the number of arguments and their types.  One
247way to do it is to provide overloaded versions of the function.
248
249Ellipsis arguments are inherited from C and not really a C++ feature.
250They are unsafe to use and don't work with arguments that have
251constructors or destructors.  Therefore we recommend to avoid them in
252C++ as much as possible.
253
254## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter.  Why? ##
255
256If you compile this using Microsoft Visual C++ 2005 SP1:
257```
258class Foo {
259  ...
260  virtual void Bar(const int i) = 0;
261};
262
263class MockFoo : public Foo {
264  ...
265  MOCK_METHOD1(Bar, void(const int i));
266};
267```
268You may get the following warning:
269```
270warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
271```
272
273This is a MSVC bug.  The same code compiles fine with gcc ,for
274example.  If you use Visual C++ 2008 SP1, you would get the warning:
275```
276warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
277```
278
279In C++, if you _declare_ a function with a `const` parameter, the
280`const` modifier is _ignored_.  Therefore, the `Foo` base class above
281is equivalent to:
282```
283class Foo {
284  ...
285  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
286};
287```
288
289In fact, you can _declare_ Bar() with an `int` parameter, and _define_
290it with a `const int` parameter.  The compiler will still match them
291up.
292
293Since making a parameter `const` is meaningless in the method
294_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
295That should workaround the VC bug.
296
297Note that we are talking about the _top-level_ `const` modifier here.
298If the function parameter is passed by pointer or reference, declaring
299the _pointee_ or _referee_ as `const` is still meaningful.  For
300example, the following two declarations are _not_ equivalent:
301```
302void Bar(int* p);        // Neither p nor *p is const.
303void Bar(const int* p);  // p is not const, but *p is.
304```
305
306## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it.  What can I do? ##
307
308We've noticed that when the `/clr` compiler flag is used, Visual C++
309uses 5~6 times as much memory when compiling a mock class.  We suggest
310to avoid `/clr` when compiling native C++ mocks.
311
312## I can't figure out why Google Mock thinks my expectations are not satisfied.  What should I do? ##
313
314You might want to run your test with
315`--gmock_verbose=info`.  This flag lets Google Mock print a trace
316of every mock function call it receives.  By studying the trace,
317you'll gain insights on why the expectations you set are not met.
318
319## How can I assert that a function is NEVER called? ##
320
321```
322EXPECT_CALL(foo, Bar(_))
323    .Times(0);
324```
325
326## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied.  Isn't this redundant? ##
327
328When Google Mock detects a failure, it prints relevant information
329(the mock function arguments, the state of relevant expectations, and
330etc) to help the user debug.  If another failure is detected, Google
331Mock will do the same, including printing the state of relevant
332expectations.
333
334Sometimes an expectation's state didn't change between two failures,
335and you'll see the same description of the state twice.  They are
336however _not_ redundant, as they refer to _different points in time_.
337The fact they are the same _is_ interesting information.
338
339## I get a heap check failure when using a mock object, but using a real object is fine.  What can be wrong? ##
340
341Does the class (hopefully a pure interface) you are mocking have a
342virtual destructor?
343
344Whenever you derive from a base class, make sure its destructor is
345virtual.  Otherwise Bad Things will happen.  Consider the following
346code:
347
348```
349class Base {
350 public:
351  // Not virtual, but should be.
352  ~Base() { ... }
353  ...
354};
355
356class Derived : public Base {
357 public:
358  ...
359 private:
360  std::string value_;
361};
362
363...
364  Base* p = new Derived;
365  ...
366  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not
367             // - value_ is leaked.
368```
369
370By changing `~Base()` to virtual, `~Derived()` will be correctly
371called when `delete p` is executed, and the heap checker
372will be happy.
373
374## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##
375
376When people complain about this, often they are referring to code like:
377
378```
379// foo.Bar() should be called twice, return 1 the first time, and return
380// 2 the second time.  However, I have to write the expectations in the
381// reverse order.  This sucks big time!!!
382EXPECT_CALL(foo, Bar())
383    .WillOnce(Return(2))
384    .RetiresOnSaturation();
385EXPECT_CALL(foo, Bar())
386    .WillOnce(Return(1))
387    .RetiresOnSaturation();
388```
389
390The problem is that they didn't pick the **best** way to express the test's
391intent.
392
393By default, expectations don't have to be matched in _any_ particular
394order.  If you want them to match in a certain order, you need to be
395explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
396easy to accidentally over-specify your tests, and we want to make it
397harder to do so.
398
399There are two better ways to write the test spec.  You could either
400put the expectations in sequence:
401
402```
403// foo.Bar() should be called twice, return 1 the first time, and return
404// 2 the second time.  Using a sequence, we can write the expectations
405// in their natural order.
406{
407  InSequence s;
408  EXPECT_CALL(foo, Bar())
409      .WillOnce(Return(1))
410      .RetiresOnSaturation();
411  EXPECT_CALL(foo, Bar())
412      .WillOnce(Return(2))
413      .RetiresOnSaturation();
414}
415```
416
417or you can put the sequence of actions in the same expectation:
418
419```
420// foo.Bar() should be called twice, return 1 the first time, and return
421// 2 the second time.
422EXPECT_CALL(foo, Bar())
423    .WillOnce(Return(1))
424    .WillOnce(Return(2))
425    .RetiresOnSaturation();
426```
427
428Back to the original questions: why does Google Mock search the
429expectations (and `ON_CALL`s) from back to front?  Because this
430allows a user to set up a mock's behavior for the common case early
431(e.g. in the mock's constructor or the test fixture's set-up phase)
432and customize it with more specific rules later.  If Google Mock
433searches from front to back, this very useful pattern won't be
434possible.
435
436## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL.  Would it be reasonable not to show the warning in this case? ##
437
438When choosing between being neat and being safe, we lean toward the
439latter.  So the answer is that we think it's better to show the
440warning.
441
442Often people write `ON_CALL`s in the mock object's
443constructor or `SetUp()`, as the default behavior rarely changes from
444test to test.  Then in the test body they set the expectations, which
445are often different for each test.  Having an `ON_CALL` in the set-up
446part of a test doesn't mean that the calls are expected.  If there's
447no `EXPECT_CALL` and the method is called, it's possibly an error.  If
448we quietly let the call go through without notifying the user, bugs
449may creep in unnoticed.
450
451If, however, you are sure that the calls are OK, you can write
452
453```
454EXPECT_CALL(foo, Bar(_))
455    .WillRepeatedly(...);
456```
457
458instead of
459
460```
461ON_CALL(foo, Bar(_))
462    .WillByDefault(...);
463```
464
465This tells Google Mock that you do expect the calls and no warning should be
466printed.
467
468Also, you can control the verbosity using the `--gmock_verbose` flag.
469If you find the output too noisy when debugging, just choose a less
470verbose level.
471
472## How can I delete the mock function's argument in an action? ##
473
474If you find yourself needing to perform some action that's not
475supported by Google Mock directly, remember that you can define your own
476actions using
477[MakeAction()](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Actions) or
478[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Actions),
479or you can write a stub function and invoke it using
480[Invoke()](http://code.google.com/p/googlemock/wiki/CookBook#Using_Functions_Methods_Functors).
481
482## MOCK\_METHODn()'s second argument looks funny.  Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##
483
484What?!  I think it's beautiful. :-)
485
486While which syntax looks more natural is a subjective matter to some
487extent, Google Mock's syntax was chosen for several practical advantages it
488has.
489
490Try to mock a function that takes a map as an argument:
491```
492virtual int GetSize(const map<int, std::string>& m);
493```
494
495Using the proposed syntax, it would be:
496```
497MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
498```
499
500Guess what?  You'll get a compiler error as the compiler thinks that
501`const map<int, std::string>& m` are **two**, not one, arguments. To work
502around this you can use `typedef` to give the map type a name, but
503that gets in the way of your work.  Google Mock's syntax avoids this
504problem as the function's argument types are protected inside a pair
505of parentheses:
506```
507// This compiles fine.
508MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
509```
510
511You still need a `typedef` if the return type contains an unprotected
512comma, but that's much rarer.
513
514Other advantages include:
515  1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
516  1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it.  The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively.  Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
517  1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features.  We'd as well stick to the same syntax in `MOCK_METHOD*`!
518
519## My code calls a static/global function.  Can I mock it? ##
520
521You can, but you need to make some changes.
522
523In general, if you find yourself needing to mock a static function,
524it's a sign that your modules are too tightly coupled (and less
525flexible, less reusable, less testable, etc).  You are probably better
526off defining a small interface and call the function through that
527interface, which then can be easily mocked.  It's a bit of work
528initially, but usually pays for itself quickly.
529
530This Google Testing Blog
531[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
532says it excellently.  Check it out.
533
534## My mock object needs to do complex stuff.  It's a lot of pain to specify the actions.  Google Mock sucks! ##
535
536I know it's not a question, but you get an answer for free any way. :-)
537
538With Google Mock, you can create mocks in C++ easily.  And people might be
539tempted to use them everywhere. Sometimes they work great, and
540sometimes you may find them, well, a pain to use. So, what's wrong in
541the latter case?
542
543When you write a test without using mocks, you exercise the code and
544assert that it returns the correct value or that the system is in an
545expected state.  This is sometimes called "state-based testing".
546
547Mocks are great for what some call "interaction-based" testing:
548instead of checking the system state at the very end, mock objects
549verify that they are invoked the right way and report an error as soon
550as it arises, giving you a handle on the precise context in which the
551error was triggered.  This is often more effective and economical to
552do than state-based testing.
553
554If you are doing state-based testing and using a test double just to
555simulate the real object, you are probably better off using a fake.
556Using a mock in this case causes pain, as it's not a strong point for
557mocks to perform complex actions.  If you experience this and think
558that mocks suck, you are just not using the right tool for your
559problem. Or, you might be trying to solve the wrong problem. :-)
560
561## I got a warning "Uninteresting function call encountered - default action taken.."  Should I panic? ##
562
563By all means, NO!  It's just an FYI.
564
565What it means is that you have a mock function, you haven't set any
566expectations on it (by Google Mock's rule this means that you are not
567interested in calls to this function and therefore it can be called
568any number of times), and it is called.  That's OK - you didn't say
569it's not OK to call the function!
570
571What if you actually meant to disallow this function to be called, but
572forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
573one can argue that it's the user's fault, Google Mock tries to be nice and
574prints you a note.
575
576So, when you see the message and believe that there shouldn't be any
577uninteresting calls, you should investigate what's going on.  To make
578your life easier, Google Mock prints the function name and arguments
579when an uninteresting call is encountered.
580
581## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##
582
583Either way is fine - you want to choose the one that's more convenient
584for your circumstance.
585
586Usually, if your action is for a particular function type, defining it
587using `Invoke()` should be easier; if your action can be used in
588functions of different types (e.g. if you are defining
589`Return(value)`), `MakePolymorphicAction()` is
590easiest.  Sometimes you want precise control on what types of
591functions the action can be used in, and implementing
592`ActionInterface` is the way to go here. See the implementation of
593`Return()` in `include/gmock/gmock-actions.h` for an example.
594
595## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified".  What does it mean? ##
596
597You got this error as Google Mock has no idea what value it should return
598when the mock method is called.  `SetArgPointee()` says what the
599side effect is, but doesn't say what the return value should be.  You
600need `DoAll()` to chain a `SetArgPointee()` with a `Return()`.
601
602See this [recipe](http://code.google.com/p/googlemock/wiki/CookBook#Mocking_Side_Effects) for more details and an example.
603
604
605## My question is not in your FAQ! ##
606
607If you cannot find the answer to your question in this FAQ, there are
608some other resources you can use:
609
610  1. read other [wiki pages](http://code.google.com/p/googlemock/w/list),
611  1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
612  1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).
613
614Please note that creating an issue in the
615[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_
616a good way to get your answer, as it is monitored infrequently by a
617very small number of people.
618
619When asking a question, it's helpful to provide as much of the
620following information as possible (people cannot help you if there's
621not enough information in your question):
622
623  * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
624  * your operating system,
625  * the name and version of your compiler,
626  * the complete command line flags you give to your compiler,
627  * the complete compiler error messages (if the question is about compilation),
628  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/KnownIssues.md
r0r249096
1As any non-trivial software system, Google Mock has some known limitations and problems.  We are working on improving it, and welcome your help!  The follow is a list of issues we know about.
2
3
4
5## README contains outdated information on Google Mock's compatibility with other testing frameworks ##
6
7The `README` file in release 1.1.0 still says that Google Mock only works with Google Test.  Actually, you can configure Google Mock to work with any testing framework you choose.
8
9## Tests failing on machines using Power PC CPUs (e.g. some Macs) ##
10
11`gmock_output_test` and `gmock-printers_test` are known to fail with Power PC CPUs.  This is due to portability issues with these tests, and is not an indication of problems in Google Mock itself.  You can safely ignore them.
12
13## Failed to resolve libgtest.so.0 in tests when built against installed Google Test ##
14
15This only applies if you manually built and installed Google Test, and then built a Google Mock against it (either explicitly, or because gtest-config was in your path post-install). In this situation, Libtool has a known issue with certain systems' ldconfig setup:
16
17http://article.gmane.org/gmane.comp.sysutils.automake.general/9025
18
19This requires a manual run of "sudo ldconfig" after the "sudo make install" for Google Test before any binaries which link against it can be executed. This isn't a bug in our install, but we should at least have documented it or hacked a work-around into our install. We should have one of these solutions in our next release.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_5/CheatSheet.md
r0r249096
1
2
3# Defining a Mock Class #
4
5## Mocking a Normal Class ##
6
7Given
8```
9class Foo {
10  ...
11  virtual ~Foo();
12  virtual int GetSize() const = 0;
13  virtual string Describe(const char* name) = 0;
14  virtual string Describe(int type) = 0;
15  virtual bool Process(Bar elem, int count) = 0;
16};
17```
18(note that `~Foo()` **must** be virtual) we can define its mock as
19```
20#include <gmock/gmock.h>
21
22class MockFoo : public Foo {
23  MOCK_CONST_METHOD0(GetSize, int());
24  MOCK_METHOD1(Describe, string(const char* name));
25  MOCK_METHOD1(Describe, string(int type));
26  MOCK_METHOD2(Process, bool(Bar elem, int count));
27};
28```
29
30To create a "nice" mock object which ignores all uninteresting calls,
31or a "strict" mock object, which treats them as failures:
32```
33NiceMock<MockFoo> nice_foo;     // The type is a subclass of MockFoo.
34StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
35```
36
37## Mocking a Class Template ##
38
39To mock
40```
41template <typename Elem>
42class StackInterface {
43 public:
44  ...
45  virtual ~StackInterface();
46  virtual int GetSize() const = 0;
47  virtual void Push(const Elem& x) = 0;
48};
49```
50(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros:
51```
52template <typename Elem>
53class MockStack : public StackInterface<Elem> {
54 public:
55  ...
56  MOCK_CONST_METHOD0_T(GetSize, int());
57  MOCK_METHOD1_T(Push, void(const Elem& x));
58};
59```
60
61## Specifying Calling Conventions for Mock Functions ##
62
63If your mock function doesn't use the default calling convention, you
64can specify it by appending `_WITH_CALLTYPE` to any of the macros
65described in the previous two sections and supplying the calling
66convention as the first argument to the macro. For example,
67```
68  MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n));
69  MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y));
70```
71where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
72
73# Using Mocks in Tests #
74
75The typical flow is:
76  1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted.
77  1. Create the mock objects.
78  1. Optionally, set the default actions of the mock objects.
79  1. Set your expectations on the mock objects (How will they be called? What wil they do?).
80  1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions.
81  1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied.
82
83Here is an example:
84```
85using ::testing::Return;                            // #1
86
87TEST(BarTest, DoesThis) {
88  MockFoo foo;                                    // #2
89
90  ON_CALL(foo, GetSize())                         // #3
91      .WillByDefault(Return(1));
92  // ... other default actions ...
93
94  EXPECT_CALL(foo, Describe(5))                   // #4
95      .Times(3)
96      .WillRepeatedly(Return("Category 5"));
97  // ... other expectations ...
98
99  EXPECT_EQ("good", MyProductionFunction(&foo));  // #5
100}                                                 // #6
101```
102
103# Setting Default Actions #
104
105Google Mock has a **built-in default action** for any function that
106returns `void`, `bool`, a numeric value, or a pointer.
107
108To customize the default action for functions with return type `T` globally:
109```
110using ::testing::DefaultValue;
111
112DefaultValue<T>::Set(value);  // Sets the default value to be returned.
113// ... use the mocks ...
114DefaultValue<T>::Clear();     // Resets the default value.
115```
116
117To customize the default action for a particular method, use `ON_CALL()`:
118```
119ON_CALL(mock_object, method(matchers))
120    .With(multi_argument_matcher)  ?
121    .WillByDefault(action);
122```
123
124# Setting Expectations #
125
126`EXPECT_CALL()` sets **expectations** on a mock method (How will it be
127called? What will it do?):
128```
129EXPECT_CALL(mock_object, method(matchers))
130    .With(multi_argument_matcher)  ?
131    .Times(cardinality)            ?
132    .InSequence(sequences)         *
133    .After(expectations)           *
134    .WillOnce(action)              *
135    .WillRepeatedly(action)        ?
136    .RetiresOnSaturation();        ?
137```
138
139If `Times()` is omitted, the cardinality is assumed to be:
140
141  * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
142  * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or
143  * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0.
144
145A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time.
146
147# Matchers #
148
149A **matcher** matches a _single_ argument.  You can use it inside
150`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value
151directly:
152
153| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. |
154|:------------------------------|:----------------------------------------|
155| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. |
156
157Built-in matchers (where `argument` is the function argument) are
158divided into several categories:
159
160## Wildcard ##
161|`_`|`argument` can be any value of the correct type.|
162|:--|:-----------------------------------------------|
163|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`.     |
164
165## Generic Comparison ##
166
167|`Eq(value)` or `value`|`argument == value`|
168|:---------------------|:------------------|
169|`Ge(value)`           |`argument >= value`|
170|`Gt(value)`           |`argument > value` |
171|`Le(value)`           |`argument <= value`|
172|`Lt(value)`           |`argument < value` |
173|`Ne(value)`           |`argument != value`|
174|`IsNull()`            |`argument` is a `NULL` pointer (raw or smart).|
175|`NotNull()`           |`argument` is a non-null pointer (raw or smart).|
176|`Ref(variable)`       |`argument` is a reference to `variable`.|
177|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|
178
179Except `Ref()`, these matchers make a _copy_ of `value` in case it's
180modified or destructed later. If the compiler complains that `value`
181doesn't have a public copy constructor, try wrap it in `ByRef()`,
182e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure
183`non_copyable_value` is not changed afterwards, or the meaning of your
184matcher will be changed.
185
186## Floating-Point Matchers ##
187
188|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
189|:-------------------|:----------------------------------------------------------------------------------------------|
190|`FloatEq(a_float)`  |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal.  |
191|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal.  |
192|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal.    |
193
194The above matchers use ULP-based comparison (the same as used in
195[Google Test](http://code.google.com/p/googletest/)). They
196automatically pick a reasonable error bound based on the absolute
197value of the expected value.  `DoubleEq()` and `FloatEq()` conform to
198the IEEE standard, which requires comparing two NaNs for equality to
199return false. The `NanSensitive*` version instead treats two NaNs as
200equal, which is often what a user wants.
201
202## String Matchers ##
203
204The `argument` can be either a C string or a C++ string object:
205
206|`ContainsRegex(string)`|`argument` matches the given regular expression.|
207|:----------------------|:-----------------------------------------------|
208|`EndsWith(suffix)`     |`argument` ends with string `suffix`.           |
209|`HasSubstr(string)`    |`argument` contains `string` as a sub-string.   |
210|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.|
211|`StartsWith(prefix)`   |`argument` starts with string `prefix`.         |
212|`StrCaseEq(string)`    |`argument` is equal to `string`, ignoring case. |
213|`StrCaseNe(string)`    |`argument` is not equal to `string`, ignoring case.|
214|`StrEq(string)`        |`argument` is equal to `string`.                |
215|`StrNe(string)`        |`argument` is not equal to `string`.            |
216
217`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
218strings as well.
219
220## Container Matchers ##
221
222Most STL-style containers support `==`, so you can use
223`Eq(expected_container)` or simply `expected_container` to match a
224container exactly.   If you want to write the elements in-line,
225match them more flexibly, or get more informative messages, you can use:
226
227| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |
228|:--------------|:-------------------------------------------------------------------------------------------|
229|`ElementsAre(e0, e1, ..., en)`|`argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed.|
230|`ElementsAreArray(array)` or `ElementsAreArray(array, count)`|The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array.|
231| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
232
233These matchers can also match:
234
235  1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and
236  1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)).
237
238where the array may be multi-dimensional (i.e. its elements can be arrays).
239
240## Member Matchers ##
241
242|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
243|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------|
244|`Key(e)`                 |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
245|`Pair(m1, m2)`           |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.                                                |
246|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
247
248## Matching the Result of a Function or Functor ##
249
250|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
251|:---------------|:---------------------------------------------------------------------|
252
253## Pointer Matchers ##
254
255|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.|
256|:-----------|:-----------------------------------------------------------------------------------------------|
257
258## Multiargument Matchers ##
259
260These are matchers on tuple types. They can be used in
261`.With()`. The following can be used on functions with <i>two<br>
262arguments</i> `x` and `y`:
263
264|`Eq()`|`x == y`|
265|:-----|:-------|
266|`Ge()`|`x >= y`|
267|`Gt()`|`x > y` |
268|`Le()`|`x <= y`|
269|`Lt()`|`x < y` |
270|`Ne()`|`x != y`|
271
272You can use the following selectors to pick a subset of the arguments
273(or reorder them) to participate in the matching:
274
275|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.|
276|:-----------|:-------------------------------------------------------------------|
277|`Args<N1, N2, ..., Nk>(m)`|The `k` selected (using 0-based indices) arguments match `m`, e.g. `Args<1, 2>(Contains(5))`.|
278
279## Composite Matchers ##
280
281You can make a matcher from one or more other matchers:
282
283|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.|
284|:-----------------------|:---------------------------------------------------|
285|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.|
286|`Not(m)`                |`argument` doesn't match matcher `m`.               |
287
288## Adapters for Matchers ##
289
290|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.|
291|:------------------|:--------------------------------------|
292|`SafeMatcherCast<T>(m)`| [safely casts](V1_5_CookBook#Casting_Matchers.md) matcher `m` to type `Matcher<T>`. |
293|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.|
294
295## Matchers as Predicates ##
296
297|`Matches(m)`|a unary functor that returns `true` if the argument matches `m`.|
298|:-----------|:---------------------------------------------------------------|
299|`ExplainMatchResult(m, value, result_listener)`|returns `true` if `value` matches `m`, explaining the result to `result_listener`.|
300|`Value(x, m)`|returns `true` if the value of `x` matches `m`.                 |
301
302## Defining Matchers ##
303
304| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
305|:-------------------------------------------------|:------------------------------------------------------|
306| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
307| `MATCHER_P2(IsBetween, a, b, "is between %(a)s and %(b)s") { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
308
309**Notes:**
310
311  1. The `MATCHER*` macros cannot be used inside a function or class.
312  1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters).
313  1. You can use `PrintToString(x)` to convert a value `x` of any type to a string.
314
315## Matchers as Test Assertions ##
316
317|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/GoogleTestPrimer#Assertions) if the value of `expression` doesn't match matcher `m`.|
318|:---------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------|
319|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.                                                                    |
320
321# Actions #
322
323**Actions** specify what a mock function should do when invoked.
324
325## Returning a Value ##
326
327|`Return()`|Return from a `void` mock function.|
328|:---------|:----------------------------------|
329|`Return(value)`|Return `value`.                    |
330|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
331|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
332|`ReturnNull()`|Return a null pointer.             |
333|`ReturnRef(variable)`|Return a reference to `variable`.  |
334
335## Side Effects ##
336
337|`Assign(&variable, value)`|Assign `value` to variable.|
338|:-------------------------|:--------------------------|
339| `DeleteArg<N>()`         | Delete the `N`-th (0-based) argument, which must be a pointer. |
340| `SaveArg<N>(pointer)`    | Save the `N`-th (0-based) argument to `*pointer`. |
341| `SetArgReferee<N>(value)` |   Assign value to the variable referenced by the `N`-th (0-based) argument. |
342|`SetArgumentPointee<N>(value)`|Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
343|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
344|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
345|`Throw(exception)`        |Throws the given exception, which can be any copyable value. Available since v1.1.0.|
346
347## Using a Function or a Functor as an Action ##
348
349|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
350|:----------|:-----------------------------------------------------------------------------------------------------------------|
351|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.                                  |
352|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.                       |
353|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.                                                        |
354|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|
355
356The return value of the invoked function is used as the return value
357of the action.
358
359When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
360```
361  double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
362  ...
363  EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
364```
365
366In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example,
367```
368  InvokeArgument<2>(5, string("Hi"), ByRef(foo))
369```
370calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference.
371
372## Default Action ##
373
374|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).|
375|:------------|:--------------------------------------------------------------------|
376
377**Note:** due to technical reasons, `DoDefault()` cannot be used inside  a composite action - trying to do so will result in a run-time error.
378
379## Composite Actions ##
380
381|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
382|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------|
383|`IgnoreResult(a)`       |Perform action `a` and ignore its result. `a` must not return void.                                                           |
384|`WithArg<N>(a)`         |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it.                                         |
385|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it.                                      |
386|`WithoutArgs(a)`        |Perform action `a` without any arguments.                                                                                     |
387
388## Defining Actions ##
389
390| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
391|:--------------------------------------|:---------------------------------------------------------------------------------------|
392| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
393| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`.   |
394
395The `ACTION*` macros cannot be used inside a function or class.
396
397# Cardinalities #
398
399These are used in `Times()` to specify how many times a mock function will be called:
400
401|`AnyNumber()`|The function can be called any number of times.|
402|:------------|:----------------------------------------------|
403|`AtLeast(n)` |The call is expected at least `n` times.       |
404|`AtMost(n)`  |The call is expected at most `n` times.        |
405|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.|
406|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.|
407
408# Expectation Order #
409
410By default, the expectations can be matched in _any_ order.  If some
411or all expectations must be matched in a given order, there are two
412ways to specify it.  They can be used either independently or
413together.
414
415## The After Clause ##
416
417```
418using ::testing::Expectation;
419...
420Expectation init_x = EXPECT_CALL(foo, InitX());
421Expectation init_y = EXPECT_CALL(foo, InitY());
422EXPECT_CALL(foo, Bar())
423    .After(init_x, init_y);
424```
425says that `Bar()` can be called only after both `InitX()` and
426`InitY()` have been called.
427
428If you don't know how many pre-requisites an expectation has when you
429write it, you can use an `ExpectationSet` to collect them:
430
431```
432using ::testing::ExpectationSet;
433...
434ExpectationSet all_inits;
435for (int i = 0; i < element_count; i++) {
436  all_inits += EXPECT_CALL(foo, InitElement(i));
437}
438EXPECT_CALL(foo, Bar())
439    .After(all_inits);
440```
441says that `Bar()` can be called only after all elements have been
442initialized (but we don't care about which elements get initialized
443before the others).
444
445Modifying an `ExpectationSet` after using it in an `.After()` doesn't
446affect the meaning of the `.After()`.
447
448## Sequences ##
449
450When you have a long chain of sequential expectations, it's easier to
451specify the order using **sequences**, which don't require you to given
452each expectation in the chain a different name.  <i>All expected<br>
453calls</i> in the same sequence must occur in the order they are
454specified.
455
456```
457using ::testing::Sequence;
458Sequence s1, s2;
459...
460EXPECT_CALL(foo, Reset())
461    .InSequence(s1, s2)
462    .WillOnce(Return(true));
463EXPECT_CALL(foo, GetSize())
464    .InSequence(s1)
465    .WillOnce(Return(1));
466EXPECT_CALL(foo, Describe(A<const char*>()))
467    .InSequence(s2)
468    .WillOnce(Return("dummy"));
469```
470says that `Reset()` must be called before _both_ `GetSize()` _and_
471`Describe()`, and the latter two can occur in any order.
472
473To put many expectations in a sequence conveniently:
474```
475using ::testing::InSequence;
476{
477  InSequence dummy;
478
479  EXPECT_CALL(...)...;
480  EXPECT_CALL(...)...;
481  ...
482  EXPECT_CALL(...)...;
483}
484```
485says that all expected calls in the scope of `dummy` must occur in
486strict order. The name `dummy` is irrelevant.)
487
488# Verifying and Resetting a Mock #
489
490Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier:
491```
492using ::testing::Mock;
493...
494// Verifies and removes the expectations on mock_obj;
495// returns true iff successful.
496Mock::VerifyAndClearExpectations(&mock_obj);
497...
498// Verifies and removes the expectations on mock_obj;
499// also removes the default actions set by ON_CALL();
500// returns true iff successful.
501Mock::VerifyAndClear(&mock_obj);
502```
503
504You can also tell Google Mock that a mock object can be leaked and doesn't
505need to be verified:
506```
507Mock::AllowLeak(&mock_obj);
508```
509
510# Mock Classes #
511
512Google Mock defines a convenient mock class template
513```
514class MockFunction<R(A1, ..., An)> {
515 public:
516  MOCK_METHODn(Call, R(A1, ..., An));
517};
518```
519See this [recipe](V1_5_CookBook#Using_Check_Points.md) for one application of it.
520
521# Flags #
522
523| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
524|:-------------------------------|:----------------------------------------------|
525| `--gmock_verbose=LEVEL`        | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_5/CookBook.md
r0r249096
1
2
3You can find recipes for using Google Mock here. If you haven't yet,
4please read the [ForDummies](V1_5_ForDummies.md) document first to make sure you understand
5the basics.
6
7**Note:** Google Mock lives in the `testing` name space. For
8readability, it is recommended to write `using ::testing::Foo;` once in
9your file before using the name `Foo` defined by Google Mock. We omit
10such `using` statements in this page for brevity, but you should do it
11in your own code.
12
13# Creating Mock Classes #
14
15## Mocking Private or Protected Methods ##
16
17You must always put a mock method definition (`MOCK_METHOD*`) in a
18`public:` section of the mock class, regardless of the method being
19mocked being `public`, `protected`, or `private` in the base class.
20This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function
21from outside of the mock class.  (Yes, C++ allows a subclass to change
22the access level of a virtual function in the base class.)  Example:
23
24```
25class Foo {
26 public:
27  ...
28  virtual bool Transform(Gadget* g) = 0;
29
30 protected:
31  virtual void Resume();
32
33 private:
34  virtual int GetTimeOut();
35};
36
37class MockFoo : public Foo {
38 public:
39  ...
40  MOCK_METHOD1(Transform, bool(Gadget* g));
41
42  // The following must be in the public section, even though the
43  // methods are protected or private in the base class.
44  MOCK_METHOD0(Resume, void());
45  MOCK_METHOD0(GetTimeOut, int());
46};
47```
48
49## Mocking Overloaded Methods ##
50
51You can mock overloaded functions as usual. No special attention is required:
52
53```
54class Foo {
55  ...
56
57  // Must be virtual as we'll inherit from Foo.
58  virtual ~Foo();
59
60  // Overloaded on the types and/or numbers of arguments.
61  virtual int Add(Element x);
62  virtual int Add(int times, Element x);
63
64  // Overloaded on the const-ness of this object.
65  virtual Bar& GetBar();
66  virtual const Bar& GetBar() const;
67};
68
69class MockFoo : public Foo {
70  ...
71  MOCK_METHOD1(Add, int(Element x));
72  MOCK_METHOD2(Add, int(int times, Element x);
73
74  MOCK_METHOD0(GetBar, Bar&());
75  MOCK_CONST_METHOD0(GetBar, const Bar&());
76};
77```
78
79**Note:** if you don't mock all versions of the overloaded method, the
80compiler will give you a warning about some methods in the base class
81being hidden. To fix that, use `using` to bring them in scope:
82
83```
84class MockFoo : public Foo {
85  ...
86  using Foo::Add;
87  MOCK_METHOD1(Add, int(Element x));
88  // We don't want to mock int Add(int times, Element x);
89  ...
90};
91```
92
93## Mocking Class Templates ##
94
95To mock a class template, append `_T` to the `MOCK_*` macros:
96
97```
98template <typename Elem>
99class StackInterface {
100  ...
101  // Must be virtual as we'll inherit from StackInterface.
102  virtual ~StackInterface();
103
104  virtual int GetSize() const = 0;
105  virtual void Push(const Elem& x) = 0;
106};
107
108template <typename Elem>
109class MockStack : public StackInterface<Elem> {
110  ...
111  MOCK_CONST_METHOD0_T(GetSize, int());
112  MOCK_METHOD1_T(Push, void(const Elem& x));
113};
114```
115
116## Mocking Nonvirtual Methods ##
117
118Google Mock can mock non-virtual functions to be used in what we call _hi-perf
119dependency injection_.
120
121In this case, instead of sharing a common base class with the real
122class, your mock class will be _unrelated_ to the real class, but
123contain methods with the same signatures.  The syntax for mocking
124non-virtual methods is the _same_ as mocking virtual methods:
125
126```
127// A simple packet stream class.  None of its members is virtual.
128class ConcretePacketStream {
129 public:
130  void AppendPacket(Packet* new_packet);
131  const Packet* GetPacket(size_t packet_number) const;
132  size_t NumberOfPackets() const;
133  ...
134};
135
136// A mock packet stream class.  It inherits from no other, but defines
137// GetPacket() and NumberOfPackets().
138class MockPacketStream {
139 public:
140  MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
141  MOCK_CONST_METHOD0(NumberOfPackets, size_t());
142  ...
143};
144```
145
146Note that the mock class doesn't define `AppendPacket()`, unlike the
147real class. That's fine as long as the test doesn't need to call it.
148
149Next, you need a way to say that you want to use
150`ConcretePacketStream` in production code, and use `MockPacketStream`
151in tests.  Since the functions are not virtual and the two classes are
152unrelated, you must specify your choice at _compile time_ (as opposed
153to run time).
154
155One way to do it is to templatize your code that needs to use a packet
156stream.  More specifically, you will give your code a template type
157argument for the type of the packet stream.  In production, you will
158instantiate your template with `ConcretePacketStream` as the type
159argument.  In tests, you will instantiate the same template with
160`MockPacketStream`.  For example, you may write:
161
162```
163template <class PacketStream>
164void CreateConnection(PacketStream* stream) { ... }
165
166template <class PacketStream>
167class PacketReader {
168 public:
169  void ReadPackets(PacketStream* stream, size_t packet_num);
170};
171```
172
173Then you can use `CreateConnection<ConcretePacketStream>()` and
174`PacketReader<ConcretePacketStream>` in production code, and use
175`CreateConnection<MockPacketStream>()` and
176`PacketReader<MockPacketStream>` in tests.
177
178```
179  MockPacketStream mock_stream;
180  EXPECT_CALL(mock_stream, ...)...;
181  .. set more expectations on mock_stream ...
182  PacketReader<MockPacketStream> reader(&mock_stream);
183  ... exercise reader ...
184```
185
186## Mocking Free Functions ##
187
188It's possible to use Google Mock to mock a free function (i.e. a
189C-style function or a static method).  You just need to rewrite your
190code to use an interface (abstract class).
191
192Instead of calling a free function (say, `OpenFile`) directly,
193introduce an interface for it and have a concrete subclass that calls
194the free function:
195
196```
197class FileInterface {
198 public:
199  ...
200  virtual bool Open(const char* path, const char* mode) = 0;
201};
202
203class File : public FileInterface {
204 public:
205  ...
206  virtual bool Open(const char* path, const char* mode) {
207    return OpenFile(path, mode);
208  }
209};
210```
211
212Your code should talk to `FileInterface` to open a file.  Now it's
213easy to mock out the function.
214
215This may seem much hassle, but in practice you often have multiple
216related functions that you can put in the same interface, so the
217per-function syntactic overhead will be much lower.
218
219If you are concerned about the performance overhead incurred by
220virtual functions, and profiling confirms your concern, you can
221combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md).
222
223## Nice Mocks and Strict Mocks ##
224
225If a mock method has no `EXPECT_CALL` spec but is called, Google Mock
226will print a warning about the "uninteresting call". The rationale is:
227
228  * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called.
229  * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning.
230
231However, sometimes you may want to suppress all "uninteresting call"
232warnings, while sometimes you may want the opposite, i.e. to treat all
233of them as errors. Google Mock lets you make the decision on a
234per-mock-object basis.
235
236Suppose your test uses a mock class `MockFoo`:
237
238```
239TEST(...) {
240  MockFoo mock_foo;
241  EXPECT_CALL(mock_foo, DoThis());
242  ... code that uses mock_foo ...
243}
244```
245
246If a method of `mock_foo` other than `DoThis()` is called, it will be
247reported by Google Mock as a warning. However, if you rewrite your
248test to use `NiceMock<MockFoo>` instead, the warning will be gone,
249resulting in a cleaner test output:
250
251```
252using ::testing::NiceMock;
253
254TEST(...) {
255  NiceMock<MockFoo> mock_foo;
256  EXPECT_CALL(mock_foo, DoThis());
257  ... code that uses mock_foo ...
258}
259```
260
261`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used
262wherever `MockFoo` is accepted.
263
264It also works if `MockFoo`'s constructor takes some arguments, as
265`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:
266
267```
268using ::testing::NiceMock;
269
270TEST(...) {
271  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
272  EXPECT_CALL(mock_foo, DoThis());
273  ... code that uses mock_foo ...
274}
275```
276
277The usage of `StrictMock` is similar, except that it makes all
278uninteresting calls failures:
279
280```
281using ::testing::StrictMock;
282
283TEST(...) {
284  StrictMock<MockFoo> mock_foo;
285  EXPECT_CALL(mock_foo, DoThis());
286  ... code that uses mock_foo ...
287
288  // The test will fail if a method of mock_foo other than DoThis()
289  // is called.
290}
291```
292
293There are some caveats though (I don't like them just as much as the
294next guy, but sadly they are side effects of C++'s limitations):
295
296  1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported.
297  1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
298  1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict.  This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual.  In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class.  This rule is required for safety.  Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.)
299
300Finally, you should be **very cautious** when using this feature, as the
301decision you make applies to **all** future changes to the mock
302class. If an important change is made in the interface you are mocking
303(and thus in the mock class), it could break your tests (if you use
304`StrictMock`) or let bugs pass through without a warning (if you use
305`NiceMock`). Therefore, try to specify the mock's behavior using
306explicit `EXPECT_CALL` first, and only turn to `NiceMock` or
307`StrictMock` as the last resort.
308
309## Simplifying the Interface without Breaking Existing Code ##
310
311Sometimes a method has a long list of arguments that is mostly
312uninteresting. For example,
313
314```
315class LogSink {
316 public:
317  ...
318  virtual void send(LogSeverity severity, const char* full_filename,
319                    const char* base_filename, int line,
320                    const struct tm* tm_time,
321                    const char* message, size_t message_len) = 0;
322};
323```
324
325This method's argument list is lengthy and hard to work with (let's
326say that the `message` argument is not even 0-terminated). If we mock
327it as is, using the mock will be awkward. If, however, we try to
328simplify this interface, we'll need to fix all clients depending on
329it, which is often infeasible.
330
331The trick is to re-dispatch the method in the mock class:
332
333```
334class ScopedMockLog : public LogSink {
335 public:
336  ...
337  virtual void send(LogSeverity severity, const char* full_filename,
338                    const char* base_filename, int line, const tm* tm_time,
339                    const char* message, size_t message_len) {
340    // We are only interested in the log severity, full file name, and
341    // log message.
342    Log(severity, full_filename, std::string(message, message_len));
343  }
344
345  // Implements the mock method:
346  //
347  //   void Log(LogSeverity severity,
348  //            const string& file_path,
349  //            const string& message);
350  MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
351                         const string& message));
352};
353```
354
355By defining a new mock method with a trimmed argument list, we make
356the mock class much more user-friendly.
357
358## Alternative to Mocking Concrete Classes ##
359
360Often you may find yourself using classes that don't implement
361interfaces. In order to test your code that uses such a class (let's
362call it `Concrete`), you may be tempted to make the methods of
363`Concrete` virtual and then mock it.
364
365Try not to do that.
366
367Making a non-virtual function virtual is a big decision. It creates an
368extension point where subclasses can tweak your class' behavior. This
369weakens your control on the class because now it's harder to maintain
370the class' invariants. You should make a function virtual only when
371there is a valid reason for a subclass to override it.
372
373Mocking concrete classes directly is problematic as it creates a tight
374coupling between the class and the tests - any small change in the
375class may invalidate your tests and make test maintenance a pain.
376
377To avoid such problems, many programmers have been practicing "coding
378to interfaces": instead of talking to the `Concrete` class, your code
379would define an interface and talk to it. Then you implement that
380interface as an adaptor on top of `Concrete`. In tests, you can easily
381mock that interface to observe how your code is doing.
382
383This technique incurs some overhead:
384
385  * You pay the cost of virtual function calls (usually not a problem).
386  * There is more abstraction for the programmers to learn.
387
388However, it can also bring significant benefits in addition to better
389testability:
390
391  * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive.
392  * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change.
393
394Some people worry that if everyone is practicing this technique, they
395will end up writing lots of redundant code. This concern is totally
396understandable. However, there are two reasons why it may not be the
397case:
398
399  * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code.
400  * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it.
401
402You need to weigh the pros and cons carefully for your particular
403problem, but I'd like to assure you that the Java community has been
404practicing this for a long time and it's a proven effective technique
405applicable in a wide variety of situations. :-)
406
407## Delegating Calls to a Fake ##
408
409Some times you have a non-trivial fake implementation of an
410interface. For example:
411
412```
413class Foo {
414 public:
415  virtual ~Foo() {}
416  virtual char DoThis(int n) = 0;
417  virtual void DoThat(const char* s, int* p) = 0;
418};
419
420class FakeFoo : public Foo {
421 public:
422  virtual char DoThis(int n) {
423    return (n > 0) ? '+' :
424        (n < 0) ? '-' : '0';
425  }
426
427  virtual void DoThat(const char* s, int* p) {
428    *p = strlen(s);
429  }
430};
431```
432
433Now you want to mock this interface such that you can set expectations
434on it. However, you also want to use `FakeFoo` for the default
435behavior, as duplicating it in the mock object is, well, a lot of
436work.
437
438When you define the mock class using Google Mock, you can have it
439delegate its default action to a fake class you already have, using
440this pattern:
441
442```
443using ::testing::_;
444using ::testing::Invoke;
445
446class MockFoo : public Foo {
447 public:
448  // Normal mock method definitions using Google Mock.
449  MOCK_METHOD1(DoThis, char(int n));
450  MOCK_METHOD2(DoThat, void(const char* s, int* p));
451
452  // Delegates the default actions of the methods to a FakeFoo object.
453  // This must be called *before* the custom ON_CALL() statements.
454  void DelegateToFake() {
455    ON_CALL(*this, DoThis(_))
456        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
457    ON_CALL(*this, DoThat(_, _))
458        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
459  }
460 private:
461  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
462};
463```
464
465With that, you can use `MockFoo` in your tests as usual. Just remember
466that if you don't explicitly set an action in an `ON_CALL()` or
467`EXPECT_CALL()`, the fake will be called upon to do it:
468
469```
470using ::testing::_;
471
472TEST(AbcTest, Xyz) {
473  MockFoo foo;
474  foo.DelegateToFake(); // Enables the fake for delegation.
475
476  // Put your ON_CALL(foo, ...)s here, if any.
477
478  // No action specified, meaning to use the default action.
479  EXPECT_CALL(foo, DoThis(5));
480  EXPECT_CALL(foo, DoThat(_, _));
481
482  int n = 0;
483  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
484  foo.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
485  EXPECT_EQ(2, n);
486}
487```
488
489**Some tips:**
490
491  * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
492  * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use.
493  * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type.
494  * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code.
495
496Regarding the tip on mixing a mock and a fake, here's an example on
497why it may be a bad sign: Suppose you have a class `System` for
498low-level system operations. In particular, it does file and I/O
499operations. And suppose you want to test how your code uses `System`
500to do I/O, and you just want the file operations to work normally. If
501you mock out the entire `System` class, you'll have to provide a fake
502implementation for the file operation part, which suggests that
503`System` is taking on too many roles.
504
505Instead, you can define a `FileOps` interface and an `IOOps` interface
506and split `System`'s functionalities into the two. Then you can mock
507`IOOps` without mocking `FileOps`.
508
509## Delegating Calls to a Real Object ##
510
511When using testing doubles (mocks, fakes, stubs, and etc), sometimes
512their behaviors will differ from those of the real objects. This
513difference could be either intentional (as in simulating an error such
514that you can test the error handling code) or unintentional. If your
515mocks have different behaviors than the real objects by mistake, you
516could end up with code that passes the tests but fails in production.
517
518You can use the _delegating-to-real_ technique to ensure that your
519mock has the same behavior as the real object while retaining the
520ability to validate calls. This technique is very similar to the
521delegating-to-fake technique, the difference being that we use a real
522object instead of a fake. Here's an example:
523
524```
525using ::testing::_;
526using ::testing::AtLeast;
527using ::testing::Invoke;
528
529class MockFoo : public Foo {
530 public:
531  MockFoo() {
532    // By default, all calls are delegated to the real object.
533    ON_CALL(*this, DoThis())
534        .WillByDefault(Invoke(&real_, &Foo::DoThis));
535    ON_CALL(*this, DoThat(_))
536        .WillByDefault(Invoke(&real_, &Foo::DoThat));
537    ...
538  }
539  MOCK_METHOD0(DoThis, ...);
540  MOCK_METHOD1(DoThat, ...);
541  ...
542 private:
543  Foo real_;
544};
545...
546
547  MockFoo mock;
548
549  EXPECT_CALL(mock, DoThis())
550      .Times(3);
551  EXPECT_CALL(mock, DoThat("Hi"))
552      .Times(AtLeast(1));
553  ... use mock in test ...
554```
555
556With this, Google Mock will verify that your code made the right calls
557(with the right arguments, in the right order, called the right number
558of times, etc), and a real object will answer the calls (so the
559behavior will be the same as in production). This gives you the best
560of both worlds.
561
562## Delegating Calls to a Parent Class ##
563
564Ideally, you should code to interfaces, whose methods are all pure
565virtual. In reality, sometimes you do need to mock a virtual method
566that is not pure (i.e, it already has an implementation). For example:
567
568```
569class Foo {
570 public:
571  virtual ~Foo();
572
573  virtual void Pure(int n) = 0;
574  virtual int Concrete(const char* str) { ... }
575};
576
577class MockFoo : public Foo {
578 public:
579  // Mocking a pure method.
580  MOCK_METHOD1(Pure, void(int n));
581  // Mocking a concrete method.  Foo::Concrete() is shadowed.
582  MOCK_METHOD1(Concrete, int(const char* str));
583};
584```
585
586Sometimes you may want to call `Foo::Concrete()` instead of
587`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub
588action, or perhaps your test doesn't need to mock `Concrete()` at all
589(but it would be oh-so painful to have to define a new mock class
590whenever you don't need to mock one of its methods).
591
592The trick is to leave a back door in your mock class for accessing the
593real methods in the base class:
594
595```
596class MockFoo : public Foo {
597 public:
598  // Mocking a pure method.
599  MOCK_METHOD1(Pure, void(int n));
600  // Mocking a concrete method.  Foo::Concrete() is shadowed.
601  MOCK_METHOD1(Concrete, int(const char* str));
602
603  // Use this to call Concrete() defined in Foo.
604  int FooConcrete(const char* str) { return Foo::Concrete(str); }
605};
606```
607
608Now, you can call `Foo::Concrete()` inside an action by:
609
610```
611using ::testing::_;
612using ::testing::Invoke;
613...
614  EXPECT_CALL(foo, Concrete(_))
615      .WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
616```
617
618or tell the mock object that you don't want to mock `Concrete()`:
619
620```
621using ::testing::Invoke;
622...
623  ON_CALL(foo, Concrete(_))
624      .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
625```
626
627(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do
628that, `MockFoo::Concrete()` will be called (and cause an infinite
629recursion) since `Foo::Concrete()` is virtual. That's just how C++
630works.)
631
632# Using Matchers #
633
634## Matching Argument Values Exactly ##
635
636You can specify exactly which arguments a mock method is expecting:
637
638```
639using ::testing::Return;
640...
641  EXPECT_CALL(foo, DoThis(5))
642      .WillOnce(Return('a'));
643  EXPECT_CALL(foo, DoThat("Hello", bar));
644```
645
646## Using Simple Matchers ##
647
648You can use matchers to match arguments that have a certain property:
649
650```
651using ::testing::Ge;
652using ::testing::NotNull;
653using ::testing::Return;
654...
655  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
656      .WillOnce(Return('a'));
657  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
658  // The second argument must not be NULL.
659```
660
661A frequently used matcher is `_`, which matches anything:
662
663```
664using ::testing::_;
665using ::testing::NotNull;
666...
667  EXPECT_CALL(foo, DoThat(_, NotNull()));
668```
669
670## Combining Matchers ##
671
672You can build complex matchers from existing ones using `AllOf()`,
673`AnyOf()`, and `Not()`:
674
675```
676using ::testing::AllOf;
677using ::testing::Gt;
678using ::testing::HasSubstr;
679using ::testing::Ne;
680using ::testing::Not;
681...
682  // The argument must be > 5 and != 10.
683  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
684                                Ne(10))));
685
686  // The first argument must not contain sub-string "blah".
687  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
688                          NULL));
689```
690
691## Casting Matchers ##
692
693Google Mock matchers are statically typed, meaning that the compiler
694can catch your mistake if you use a matcher of the wrong type (for
695example, if you use `Eq(5)` to match a `string` argument). Good for
696you!
697
698Sometimes, however, you know what you're doing and want the compiler
699to give you some slack. One example is that you have a matcher for
700`long` and the argument you want to match is `int`. While the two
701types aren't exactly the same, there is nothing really wrong with
702using a `Matcher<long>` to match an `int` - after all, we can first
703convert the `int` argument to a `long` before giving it to the
704matcher.
705
706To support this need, Google Mock gives you the
707`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type
708`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the
709type `m` accepts):
710
711  1. Type `T` can be implicitly cast to type `U`;
712  1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and
713  1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value).
714
715The code won't compile if any of these conditions isn't met.
716
717Here's one example:
718
719```
720using ::testing::SafeMatcherCast;
721
722// A base class and a child class.
723class Base { ... };
724class Derived : public Base { ... };
725
726class MockFoo : public Foo {
727 public:
728  MOCK_METHOD1(DoThis, void(Derived* derived));
729};
730...
731
732  MockFoo foo;
733  // m is a Matcher<Base*> we got from somewhere.
734  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
735```
736
737If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar
738function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works
739as long as you can `static_cast` type `T` to type `U`.
740
741`MatcherCast` essentially lets you bypass C++'s type system
742(`static_cast` isn't always safe as it could throw away information,
743for example), so be careful not to misuse/abuse it.
744
745## Selecting Between Overloaded Functions ##
746
747If you expect an overloaded function to be called, the compiler may
748need some help on which overloaded version it is.
749
750To disambiguate functions overloaded on the const-ness of this object,
751use the `Const()` argument wrapper.
752
753```
754using ::testing::ReturnRef;
755
756class MockFoo : public Foo {
757  ...
758  MOCK_METHOD0(GetBar, Bar&());
759  MOCK_CONST_METHOD0(GetBar, const Bar&());
760};
761...
762
763  MockFoo foo;
764  Bar bar1, bar2;
765  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
766      .WillOnce(ReturnRef(bar1));
767  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
768      .WillOnce(ReturnRef(bar2));
769```
770
771(`Const()` is defined by Google Mock and returns a `const` reference
772to its argument.)
773
774To disambiguate overloaded functions with the same number of arguments
775but different argument types, you may need to specify the exact type
776of a matcher, either by wrapping your matcher in `Matcher<type>()`, or
777using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`,
778etc):
779
780```
781using ::testing::An;
782using ::testing::Lt;
783using ::testing::Matcher;
784using ::testing::TypedEq;
785
786class MockPrinter : public Printer {
787 public:
788  MOCK_METHOD1(Print, void(int n));
789  MOCK_METHOD1(Print, void(char c));
790};
791
792TEST(PrinterTest, Print) {
793  MockPrinter printer;
794
795  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
796  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
797  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);
798
799  printer.Print(3);
800  printer.Print(6);
801  printer.Print('a');
802}
803```
804
805## Performing Different Actions Based on the Arguments ##
806
807When a mock method is called, the _last_ matching expectation that's
808still active will be selected (think "newer overrides older"). So, you
809can make a method do different things depending on its argument values
810like this:
811
812```
813using ::testing::_;
814using ::testing::Lt;
815using ::testing::Return;
816...
817  // The default case.
818  EXPECT_CALL(foo, DoThis(_))
819      .WillRepeatedly(Return('b'));
820
821  // The more specific case.
822  EXPECT_CALL(foo, DoThis(Lt(5)))
823      .WillRepeatedly(Return('a'));
824```
825
826Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will
827be returned; otherwise `'b'` will be returned.
828
829## Matching Multiple Arguments as a Whole ##
830
831Sometimes it's not enough to match the arguments individually. For
832example, we may want to say that the first argument must be less than
833the second argument. The `With()` clause allows us to match
834all arguments of a mock function as a whole. For example,
835
836```
837using ::testing::_;
838using ::testing::Lt;
839using ::testing::Ne;
840...
841  EXPECT_CALL(foo, InRange(Ne(0), _))
842      .With(Lt());
843```
844
845says that the first argument of `InRange()` must not be 0, and must be
846less than the second argument.
847
848The expression inside `With()` must be a matcher of type
849`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the
850types of the function arguments.
851
852You can also write `AllArgs(m)` instead of `m` inside `.With()`. The
853two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable
854than `.With(Lt())`.
855
856You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments
857against `m`. For example,
858
859```
860using ::testing::_;
861using ::testing::AllOf;
862using ::testing::Args;
863using ::testing::Lt;
864...
865  EXPECT_CALL(foo, Blah(_, _, _))
866      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
867```
868
869says that `Blah()` will be called with arguments `x`, `y`, and `z` where
870`x < y < z`.
871
872As a convenience and example, Google Mock provides some matchers for
8732-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_5_CheatSheet.md) for
874the complete list.
875
876## Using Matchers as Predicates ##
877
878Have you noticed that a matcher is just a fancy predicate that also
879knows how to describe itself? Many existing algorithms take predicates
880as arguments (e.g. those defined in STL's `<algorithm>` header), and
881it would be a shame if Google Mock matchers are not allowed to
882participate.
883
884Luckily, you can use a matcher where a unary predicate functor is
885expected by wrapping it inside the `Matches()` function. For example,
886
887```
888#include <algorithm>
889#include <vector>
890
891std::vector<int> v;
892...
893// How many elements in v are >= 10?
894const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
895```
896
897Since you can build complex matchers from simpler ones easily using
898Google Mock, this gives you a way to conveniently construct composite
899predicates (doing the same using STL's `<functional>` header is just
900painful). For example, here's a predicate that's satisfied by any
901number that is >= 0, <= 100, and != 50:
902
903```
904Matches(AllOf(Ge(0), Le(100), Ne(50)))
905```
906
907## Using Matchers in Google Test Assertions ##
908
909Since matchers are basically predicates that also know how to describe
910themselves, there is a way to take advantage of them in
911[Google Test](http://code.google.com/p/googletest/) assertions. It's
912called `ASSERT_THAT` and `EXPECT_THAT`:
913
914```
915  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
916  EXPECT_THAT(value, matcher);  // The non-fatal version.
917```
918
919For example, in a Google Test test you can write:
920
921```
922#include <gmock/gmock.h>
923
924using ::testing::AllOf;
925using ::testing::Ge;
926using ::testing::Le;
927using ::testing::MatchesRegex;
928using ::testing::StartsWith;
929...
930
931  EXPECT_THAT(Foo(), StartsWith("Hello"));
932  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
933  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
934```
935
936which (as you can probably guess) executes `Foo()`, `Bar()`, and
937`Baz()`, and verifies that:
938
939  * `Foo()` returns a string that starts with `"Hello"`.
940  * `Bar()` returns a string that matches regular expression `"Line \\d+"`.
941  * `Baz()` returns a number in the range [5, 10].
942
943The nice thing about these macros is that _they read like
944English_. They generate informative messages too. For example, if the
945first `EXPECT_THAT()` above fails, the message will be something like:
946
947```
948Value of: Foo()
949  Actual: "Hi, world!"
950Expected: starts with "Hello"
951```
952
953**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the
954[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds
955`assertThat()` to JUnit.
956
957## Using Predicates as Matchers ##
958
959Google Mock provides a built-in set of matchers. In case you find them
960lacking, you can use an arbitray unary predicate function or functor
961as a matcher - as long as the predicate accepts a value of the type
962you want. You do this by wrapping the predicate inside the `Truly()`
963function, for example:
964
965```
966using ::testing::Truly;
967
968int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
969...
970
971  // Bar() must be called with an even number.
972  EXPECT_CALL(foo, Bar(Truly(IsEven)));
973```
974
975Note that the predicate function / functor doesn't have to return
976`bool`. It works as long as the return value can be used as the
977condition in statement `if (condition) ...`.
978
979## Matching Arguments that Are Not Copyable ##
980
981When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves
982away a copy of `bar`. When `Foo()` is called later, Google Mock
983compares the argument to `Foo()` with the saved copy of `bar`. This
984way, you don't need to worry about `bar` being modified or destroyed
985after the `EXPECT_CALL()` is executed. The same is true when you use
986matchers like `Eq(bar)`, `Le(bar)`, and so on.
987
988But what if `bar` cannot be copied (i.e. has no copy constructor)? You
989could define your own matcher function and use it with `Truly()`, as
990the previous couple of recipes have shown. Or, you may be able to get
991away from it if you can guarantee that `bar` won't be changed after
992the `EXPECT_CALL()` is executed. Just tell Google Mock that it should
993save a reference to `bar`, instead of a copy of it. Here's how:
994
995```
996using ::testing::Eq;
997using ::testing::ByRef;
998using ::testing::Lt;
999...
1000  // Expects that Foo()'s argument == bar.
1001  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
1002
1003  // Expects that Foo()'s argument < bar.
1004  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
1005```
1006
1007Remember: if you do this, don't change `bar` after the
1008`EXPECT_CALL()`, or the result is undefined.
1009
1010## Validating a Member of an Object ##
1011
1012Often a mock function takes a reference to object as an argument. When
1013matching the argument, you may not want to compare the entire object
1014against a fixed object, as that may be over-specification. Instead,
1015you may need to validate a certain member variable or the result of a
1016certain getter method of the object. You can do this with `Field()`
1017and `Property()`. More specifically,
1018
1019```
1020Field(&Foo::bar, m)
1021```
1022
1023is a matcher that matches a `Foo` object whose `bar` member variable
1024satisfies matcher `m`.
1025
1026```
1027Property(&Foo::baz, m)
1028```
1029
1030is a matcher that matches a `Foo` object whose `baz()` method returns
1031a value that satisfies matcher `m`.
1032
1033For example:
1034
1035> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
1036|:-----------------------------|:-----------------------------------|
1037> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
1038
1039Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no
1040argument and be declared as `const`.
1041
1042BTW, `Field()` and `Property()` can also match plain pointers to
1043objects. For instance,
1044
1045```
1046Field(&Foo::number, Ge(3))
1047```
1048
1049matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`,
1050the match will always fail regardless of the inner matcher.
1051
1052What if you want to validate more than one members at the same time?
1053Remember that there is `AllOf()`.
1054
1055## Validating the Value Pointed to by a Pointer Argument ##
1056
1057C++ functions often take pointers as arguments. You can use matchers
1058like `NULL`, `NotNull()`, and other comparison matchers to match a
1059pointer, but what if you want to make sure the value _pointed to_ by
1060the pointer, instead of the pointer itself, has a certain property?
1061Well, you can use the `Pointee(m)` matcher.
1062
1063`Pointee(m)` matches a pointer iff `m` matches the value the pointer
1064points to. For example:
1065
1066```
1067using ::testing::Ge;
1068using ::testing::Pointee;
1069...
1070  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
1071```
1072
1073expects `foo.Bar()` to be called with a pointer that points to a value
1074greater than or equal to 3.
1075
1076One nice thing about `Pointee()` is that it treats a `NULL` pointer as
1077a match failure, so you can write `Pointee(m)` instead of
1078
1079```
1080  AllOf(NotNull(), Pointee(m))
1081```
1082
1083without worrying that a `NULL` pointer will crash your test.
1084
1085Also, did we tell you that `Pointee()` works with both raw pointers
1086**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and
1087etc)?
1088
1089What if you have a pointer to pointer? You guessed it - you can use
1090nested `Pointee()` to probe deeper inside the value. For example,
1091`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer
1092that points to a number less than 3 (what a mouthful...).
1093
1094## Testing a Certain Property of an Object ##
1095
1096Sometimes you want to specify that an object argument has a certain
1097property, but there is no existing matcher that does this. If you want
1098good error messages, you should define a matcher. If you want to do it
1099quick and dirty, you could get away with writing an ordinary function.
1100
1101Let's say you have a mock function that takes an object of type `Foo`,
1102which has an `int bar()` method and an `int baz()` method, and you
1103want to constrain that the argument's `bar()` value plus its `baz()`
1104value is a given number. Here's how you can define a matcher to do it:
1105
1106```
1107using ::testing::MatcherInterface;
1108using ::testing::MatchResultListener;
1109
1110class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
1111 public:
1112  explicit BarPlusBazEqMatcher(int expected_sum)
1113      : expected_sum_(expected_sum) {}
1114
1115  virtual bool MatchAndExplain(const Foo& foo,
1116                               MatchResultListener* listener) const {
1117    return (foo.bar() + foo.baz()) == expected_sum_;
1118  }
1119
1120  virtual void DescribeTo(::std::ostream* os) const {
1121    *os << "bar() + baz() equals " << expected_sum_;
1122  }
1123
1124  virtual void DescribeNegationTo(::std::ostream* os) const {
1125    *os << "bar() + baz() does not equal " << expected_sum_;
1126  }
1127 private:
1128  const int expected_sum_;
1129};
1130
1131inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
1132  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
1133}
1134
1135...
1136
1137  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
1138```
1139
1140## Matching Containers ##
1141
1142Sometimes an STL container (e.g. list, vector, map, ...) is passed to
1143a mock function and you may want to validate it. Since most STL
1144containers support the `==` operator, you can write
1145`Eq(expected_container)` or simply `expected_container` to match a
1146container exactly.
1147
1148Sometimes, though, you may want to be more flexible (for example, the
1149first element must be an exact match, but the second element can be
1150any positive number, and so on). Also, containers used in tests often
1151have a small number of elements, and having to define the expected
1152container out-of-line is a bit of a hassle.
1153
1154You can use the `ElementsAre()` matcher in such cases:
1155
1156```
1157using ::testing::_;
1158using ::testing::ElementsAre;
1159using ::testing::Gt;
1160...
1161
1162  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
1163...
1164
1165  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
1166```
1167
1168The above matcher says that the container must have 4 elements, which
1169must be 1, greater than 0, anything, and 5 respectively.
1170
1171`ElementsAre()` is overloaded to take 0 to 10 arguments. If more are
1172needed, you can place them in a C-style array and use
1173`ElementsAreArray()` instead:
1174
1175```
1176using ::testing::ElementsAreArray;
1177...
1178
1179  // ElementsAreArray accepts an array of element values.
1180  const int expected_vector1[] = { 1, 5, 2, 4, ... };
1181  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));
1182
1183  // Or, an array of element matchers.
1184  Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
1185  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
1186```
1187
1188In case the array needs to be dynamically created (and therefore the
1189array size cannot be inferred by the compiler), you can give
1190`ElementsAreArray()` an additional argument to specify the array size:
1191
1192```
1193using ::testing::ElementsAreArray;
1194...
1195  int* const expected_vector3 = new int[count];
1196  ... fill expected_vector3 with values ...
1197  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
1198```
1199
1200**Tips:**
1201
1202  * `ElementAre*()` works with _any_ container that implements the STL iterator concept (i.e. it has a `const_iterator` type and supports `begin()/end()`) and supports `size()`, not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern.
1203  * You can use nested `ElementAre*()` to match nested (multi-dimensional) containers.
1204  * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`.
1205  * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`).
1206
1207## Sharing Matchers ##
1208
1209Under the hood, a Google Mock matcher object consists of a pointer to
1210a ref-counted implementation object. Copying matchers is allowed and
1211very efficient, as only the pointer is copied. When the last matcher
1212that references the implementation object dies, the implementation
1213object will be deleted.
1214
1215Therefore, if you have some complex matcher that you want to use again
1216and again, there is no need to build it everytime. Just assign it to a
1217matcher variable and use that variable repeatedly! For example,
1218
1219```
1220  Matcher<int> in_range = AllOf(Gt(5), Le(10));
1221  ... use in_range as a matcher in multiple EXPECT_CALLs ...
1222```
1223
1224# Setting Expectations #
1225
1226## Ignoring Uninteresting Calls ##
1227
1228If you are not interested in how a mock method is called, just don't
1229say anything about it. In this case, if the method is ever called,
1230Google Mock will perform its default action to allow the test program
1231to continue. If you are not happy with the default action taken by
1232Google Mock, you can override it using `DefaultValue<T>::Set()`
1233(described later in this document) or `ON_CALL()`.
1234
1235Please note that once you expressed interest in a particular mock
1236method (via `EXPECT_CALL()`), all invocations to it must match some
1237expectation. If this function is called but the arguments don't match
1238any `EXPECT_CALL()` statement, it will be an error.
1239
1240## Disallowing Unexpected Calls ##
1241
1242If a mock method shouldn't be called at all, explicitly say so:
1243
1244```
1245using ::testing::_;
1246...
1247  EXPECT_CALL(foo, Bar(_))
1248      .Times(0);
1249```
1250
1251If some calls to the method are allowed, but the rest are not, just
1252list all the expected calls:
1253
1254```
1255using ::testing::AnyNumber;
1256using ::testing::Gt;
1257...
1258  EXPECT_CALL(foo, Bar(5));
1259  EXPECT_CALL(foo, Bar(Gt(10)))
1260      .Times(AnyNumber());
1261```
1262
1263A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()`
1264statements will be an error.
1265
1266## Expecting Ordered Calls ##
1267
1268Although an `EXPECT_CALL()` statement defined earlier takes precedence
1269when Google Mock tries to match a function call with an expectation,
1270by default calls don't have to happen in the order `EXPECT_CALL()`
1271statements are written. For example, if the arguments match the
1272matchers in the third `EXPECT_CALL()`, but not those in the first two,
1273then the third expectation will be used.
1274
1275If you would rather have all calls occur in the order of the
1276expectations, put the `EXPECT_CALL()` statements in a block where you
1277define a variable of type `InSequence`:
1278
1279```
1280  using ::testing::_;
1281  using ::testing::InSequence;
1282
1283  {
1284    InSequence s;
1285
1286    EXPECT_CALL(foo, DoThis(5));
1287    EXPECT_CALL(bar, DoThat(_))
1288        .Times(2);
1289    EXPECT_CALL(foo, DoThis(6));
1290  }
1291```
1292
1293In this example, we expect a call to `foo.DoThis(5)`, followed by two
1294calls to `bar.DoThat()` where the argument can be anything, which are
1295in turn followed by a call to `foo.DoThis(6)`. If a call occurred
1296out-of-order, Google Mock will report an error.
1297
1298## Expecting Partially Ordered Calls ##
1299
1300Sometimes requiring everything to occur in a predetermined order can
1301lead to brittle tests. For example, we may care about `A` occurring
1302before both `B` and `C`, but aren't interested in the relative order
1303of `B` and `C`. In this case, the test should reflect our real intent,
1304instead of being overly constraining.
1305
1306Google Mock allows you to impose an arbitrary DAG (directed acyclic
1307graph) on the calls. One way to express the DAG is to use the
1308[After](V1_5_CheatSheet#The_After_Clause.md) clause of `EXPECT_CALL`.
1309
1310Another way is via the `InSequence()` clause (not the same as the
1311`InSequence` class), which we borrowed from jMock 2. It's less
1312flexible than `After()`, but more convenient when you have long chains
1313of sequential calls, as it doesn't require you to come up with
1314different names for the expectations in the chains.  Here's how it
1315works:
1316
1317If we view `EXPECT_CALL()` statements as nodes in a graph, and add an
1318edge from node A to node B wherever A must occur before B, we can get
1319a DAG. We use the term "sequence" to mean a directed path in this
1320DAG. Now, if we decompose the DAG into sequences, we just need to know
1321which sequences each `EXPECT_CALL()` belongs to in order to be able to
1322reconstruct the orginal DAG.
1323
1324So, to specify the partial order on the expectations we need to do two
1325things: first to define some `Sequence` objects, and then for each
1326`EXPECT_CALL()` say which `Sequence` objects it is part
1327of. Expectations in the same sequence must occur in the order they are
1328written. For example,
1329
1330```
1331  using ::testing::Sequence;
1332
1333  Sequence s1, s2;
1334
1335  EXPECT_CALL(foo, A())
1336      .InSequence(s1, s2);
1337  EXPECT_CALL(bar, B())
1338      .InSequence(s1);
1339  EXPECT_CALL(bar, C())
1340      .InSequence(s2);
1341  EXPECT_CALL(foo, D())
1342      .InSequence(s2);
1343```
1344
1345specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A ->
1346C -> D`):
1347
1348```
1349       +---> B
1350       |
1351  A ---|
1352       |
1353       +---> C ---> D
1354```
1355
1356This means that A must occur before B and C, and C must occur before
1357D. There's no restriction about the order other than these.
1358
1359## Controlling When an Expectation Retires ##
1360
1361When a mock method is called, Google Mock only consider expectations
1362that are still active. An expectation is active when created, and
1363becomes inactive (aka _retires_) when a call that has to occur later
1364has occurred. For example, in
1365
1366```
1367  using ::testing::_;
1368  using ::testing::Sequence;
1369
1370  Sequence s1, s2;
1371
1372  EXPECT_CALL(log, Log(WARNING, _, "File too large."))     // #1
1373      .Times(AnyNumber())
1374      .InSequence(s1, s2);
1375  EXPECT_CALL(log, Log(WARNING, _, "Data set is empty."))  // #2
1376      .InSequence(s1);
1377  EXPECT_CALL(log, Log(WARNING, _, "User not found."))     // #3
1378      .InSequence(s2);
1379```
1380
1381as soon as either #2 or #3 is matched, #1 will retire. If a warning
1382`"File too large."` is logged after this, it will be an error.
1383
1384Note that an expectation doesn't retire automatically when it's
1385saturated. For example,
1386
1387```
1388using ::testing::_;
1389...
1390  EXPECT_CALL(log, Log(WARNING, _, _));                  // #1
1391  EXPECT_CALL(log, Log(WARNING, _, "File too large."));  // #2
1392```
1393
1394says that there will be exactly one warning with the message `"File
1395too large."`. If the second warning contains this message too, #2 will
1396match again and result in an upper-bound-violated error.
1397
1398If this is not what you want, you can ask an expectation to retire as
1399soon as it becomes saturated:
1400
1401```
1402using ::testing::_;
1403...
1404  EXPECT_CALL(log, Log(WARNING, _, _));                 // #1
1405  EXPECT_CALL(log, Log(WARNING, _, "File too large."))  // #2
1406      .RetiresOnSaturation();
1407```
1408
1409Here #2 can be used only once, so if you have two warnings with the
1410message `"File too large."`, the first will match #2 and the second
1411will match #1 - there will be no error.
1412
1413# Using Actions #
1414
1415## Returning References from Mock Methods ##
1416
1417If a mock function's return type is a reference, you need to use
1418`ReturnRef()` instead of `Return()` to return a result:
1419
1420```
1421using ::testing::ReturnRef;
1422
1423class MockFoo : public Foo {
1424 public:
1425  MOCK_METHOD0(GetBar, Bar&());
1426};
1427...
1428
1429  MockFoo foo;
1430  Bar bar;
1431  EXPECT_CALL(foo, GetBar())
1432      .WillOnce(ReturnRef(bar));
1433```
1434
1435## Combining Actions ##
1436
1437Want to do more than one thing when a function is called? That's
1438fine. `DoAll()` allow you to do sequence of actions every time. Only
1439the return value of the last action in the sequence will be used.
1440
1441```
1442using ::testing::DoAll;
1443
1444class MockFoo : public Foo {
1445 public:
1446  MOCK_METHOD1(Bar, bool(int n));
1447};
1448...
1449
1450  EXPECT_CALL(foo, Bar(_))
1451      .WillOnce(DoAll(action_1,
1452                      action_2,
1453                      ...
1454                      action_n));
1455```
1456
1457## Mocking Side Effects ##
1458
1459Sometimes a method exhibits its effect not via returning a value but
1460via side effects. For example, it may change some global state or
1461modify an output argument. To mock side effects, in general you can
1462define your own action by implementing `::testing::ActionInterface`.
1463
1464If all you need to do is to change an output argument, the built-in
1465`SetArgumentPointee()` action is convenient:
1466
1467```
1468using ::testing::SetArgumentPointee;
1469
1470class MockMutator : public Mutator {
1471 public:
1472  MOCK_METHOD2(Mutate, void(bool mutate, int* value));
1473  ...
1474};
1475...
1476
1477  MockMutator mutator;
1478  EXPECT_CALL(mutator, Mutate(true, _))
1479      .WillOnce(SetArgumentPointee<1>(5));
1480```
1481
1482In this example, when `mutator.Mutate()` is called, we will assign 5
1483to the `int` variable pointed to by argument #1
1484(0-based).
1485
1486`SetArgumentPointee()` conveniently makes an internal copy of the
1487value you pass to it, removing the need to keep the value in scope and
1488alive. The implication however is that the value must have a copy
1489constructor and assignment operator.
1490
1491If the mock method also needs to return a value as well, you can chain
1492`SetArgumentPointee()` with `Return()` using `DoAll()`:
1493
1494```
1495using ::testing::_;
1496using ::testing::Return;
1497using ::testing::SetArgumentPointee;
1498
1499class MockMutator : public Mutator {
1500 public:
1501  ...
1502  MOCK_METHOD1(MutateInt, bool(int* value));
1503};
1504...
1505
1506  MockMutator mutator;
1507  EXPECT_CALL(mutator, MutateInt(_))
1508      .WillOnce(DoAll(SetArgumentPointee<0>(5),
1509                      Return(true)));
1510```
1511
1512If the output argument is an array, use the
1513`SetArrayArgument<N>(first, last)` action instead. It copies the
1514elements in source range `[first, last)` to the array pointed to by
1515the `N`-th (0-based) argument:
1516
1517```
1518using ::testing::NotNull;
1519using ::testing::SetArrayArgument;
1520
1521class MockArrayMutator : public ArrayMutator {
1522 public:
1523  MOCK_METHOD2(Mutate, void(int* values, int num_values));
1524  ...
1525};
1526...
1527
1528  MockArrayMutator mutator;
1529  int values[5] = { 1, 2, 3, 4, 5 };
1530  EXPECT_CALL(mutator, Mutate(NotNull(), 5))
1531      .WillOnce(SetArrayArgument<0>(values, values + 5));
1532```
1533
1534This also works when the argument is an output iterator:
1535
1536```
1537using ::testing::_;
1538using ::testing::SeArrayArgument;
1539
1540class MockRolodex : public Rolodex {
1541 public:
1542  MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
1543  ...
1544};
1545...
1546
1547  MockRolodex rolodex;
1548  vector<string> names;
1549  names.push_back("George");
1550  names.push_back("John");
1551  names.push_back("Thomas");
1552  EXPECT_CALL(rolodex, GetNames(_))
1553      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
1554```
1555
1556## Changing a Mock Object's Behavior Based on the State ##
1557
1558If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:
1559
1560```
1561using ::testing::InSequence;
1562using ::testing::Return;
1563
1564...
1565  {
1566    InSequence seq;
1567    EXPECT_CALL(my_mock, IsDirty())
1568        .WillRepeatedly(Return(true));
1569    EXPECT_CALL(my_mock, Flush());
1570    EXPECT_CALL(my_mock, IsDirty())
1571        .WillRepeatedly(Return(false));
1572  }
1573  my_mock.FlushIfDirty();
1574```
1575
1576This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards.
1577
1578If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
1579
1580```
1581using ::testing::_;
1582using ::testing::SaveArg;
1583using ::testing::Return;
1584
1585ACTION_P(ReturnPointee, p) { return *p; }
1586...
1587  int previous_value = 0;
1588  EXPECT_CALL(my_mock, GetPrevValue())
1589      .WillRepeatedly(ReturnPointee(&previous_value));
1590  EXPECT_CALL(my_mock, UpdateValue(_))
1591      .WillRepeatedly(SaveArg<0>(&previous_value));
1592  my_mock.DoSomethingToUpdateValue();
1593```
1594
1595Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call.
1596
1597## Setting the Default Value for a Return Type ##
1598
1599If a mock method's return type is a built-in C++ type or pointer, by
1600default it will return 0 when invoked. You only need to specify an
1601action if this default value doesn't work for you.
1602
1603Sometimes, you may want to change this default value, or you may want
1604to specify a default value for types Google Mock doesn't know
1605about. You can do this using the `::testing::DefaultValue` class
1606template:
1607
1608```
1609class MockFoo : public Foo {
1610 public:
1611  MOCK_METHOD0(CalculateBar, Bar());
1612};
1613...
1614
1615  Bar default_bar;
1616  // Sets the default return value for type Bar.
1617  DefaultValue<Bar>::Set(default_bar);
1618
1619  MockFoo foo;
1620
1621  // We don't need to specify an action here, as the default
1622  // return value works for us.
1623  EXPECT_CALL(foo, CalculateBar());
1624
1625  foo.CalculateBar();  // This should return default_bar.
1626
1627  // Unsets the default return value.
1628  DefaultValue<Bar>::Clear();
1629```
1630
1631Please note that changing the default value for a type can make you
1632tests hard to understand. We recommend you to use this feature
1633judiciously. For example, you may want to make sure the `Set()` and
1634`Clear()` calls are right next to the code that uses your mock.
1635
1636## Setting the Default Actions for a Mock Method ##
1637
1638You've learned how to change the default value of a given
1639type. However, this may be too coarse for your purpose: perhaps you
1640have two mock methods with the same return type and you want them to
1641have different behaviors. The `ON_CALL()` macro allows you to
1642customize your mock's behavior at the method level:
1643
1644```
1645using ::testing::_;
1646using ::testing::AnyNumber;
1647using ::testing::Gt;
1648using ::testing::Return;
1649...
1650  ON_CALL(foo, Sign(_))
1651      .WillByDefault(Return(-1));
1652  ON_CALL(foo, Sign(0))
1653      .WillByDefault(Return(0));
1654  ON_CALL(foo, Sign(Gt(0)))
1655      .WillByDefault(Return(1));
1656
1657  EXPECT_CALL(foo, Sign(_))
1658      .Times(AnyNumber());
1659
1660  foo.Sign(5);   // This should return 1.
1661  foo.Sign(-9);  // This should return -1.
1662  foo.Sign(0);   // This should return 0.
1663```
1664
1665As you may have guessed, when there are more than one `ON_CALL()`
1666statements, the news order take precedence over the older ones. In
1667other words, the **last** one that matches the function arguments will
1668be used. This matching order allows you to set up the common behavior
1669in a mock object's constructor or the test fixture's set-up phase and
1670specialize the mock's behavior later.
1671
1672## Using Functions/Methods/Functors as Actions ##
1673
1674If the built-in actions don't suit you, you can easily use an existing
1675function, method, or functor as an action:
1676
1677```
1678using ::testing::_;
1679using ::testing::Invoke;
1680
1681class MockFoo : public Foo {
1682 public:
1683  MOCK_METHOD2(Sum, int(int x, int y));
1684  MOCK_METHOD1(ComplexJob, bool(int x));
1685};
1686
1687int CalculateSum(int x, int y) { return x + y; }
1688
1689class Helper {
1690 public:
1691  bool ComplexJob(int x);
1692};
1693...
1694
1695  MockFoo foo;
1696  Helper helper;
1697  EXPECT_CALL(foo, Sum(_, _))
1698      .WillOnce(Invoke(CalculateSum));
1699  EXPECT_CALL(foo, ComplexJob(_))
1700      .WillOnce(Invoke(&helper, &Helper::ComplexJob));
1701
1702  foo.Sum(5, 6);       // Invokes CalculateSum(5, 6).
1703  foo.ComplexJob(10);  // Invokes helper.ComplexJob(10);
1704```
1705
1706The only requirement is that the type of the function, etc must be
1707_compatible_ with the signature of the mock function, meaning that the
1708latter's arguments can be implicitly converted to the corresponding
1709arguments of the former, and the former's return type can be
1710implicitly converted to that of the latter. So, you can invoke
1711something whose type is _not_ exactly the same as the mock function,
1712as long as it's safe to do so - nice, huh?
1713
1714## Invoking a Function/Method/Functor Without Arguments ##
1715
1716`Invoke()` is very useful for doing actions that are more complex. It
1717passes the mock function's arguments to the function or functor being
1718invoked such that the callee has the full context of the call to work
1719with. If the invoked function is not interested in some or all of the
1720arguments, it can simply ignore them.
1721
1722Yet, a common pattern is that a test author wants to invoke a function
1723without the arguments of the mock function. `Invoke()` allows her to
1724do that using a wrapper function that throws away the arguments before
1725invoking an underlining nullary function. Needless to say, this can be
1726tedious and obscures the intent of the test.
1727
1728`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except
1729that it doesn't pass the mock function's arguments to the
1730callee. Here's an example:
1731
1732```
1733using ::testing::_;
1734using ::testing::InvokeWithoutArgs;
1735
1736class MockFoo : public Foo {
1737 public:
1738  MOCK_METHOD1(ComplexJob, bool(int n));
1739};
1740
1741bool Job1() { ... }
1742...
1743
1744  MockFoo foo;
1745  EXPECT_CALL(foo, ComplexJob(_))
1746      .WillOnce(InvokeWithoutArgs(Job1));
1747
1748  foo.ComplexJob(10);  // Invokes Job1().
1749```
1750
1751## Invoking an Argument of the Mock Function ##
1752
1753Sometimes a mock function will receive a function pointer or a functor
1754(in other words, a "callable") as an argument, e.g.
1755
1756```
1757class MockFoo : public Foo {
1758 public:
1759  MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
1760};
1761```
1762
1763and you may want to invoke this callable argument:
1764
1765```
1766using ::testing::_;
1767...
1768  MockFoo foo;
1769  EXPECT_CALL(foo, DoThis(_, _))
1770      .WillOnce(...);
1771  // Will execute (*fp)(5), where fp is the
1772  // second argument DoThis() receives.
1773```
1774
1775Arghh, you need to refer to a mock function argument but C++ has no
1776lambda (yet), so you have to define your own action. :-( Or do you
1777really?
1778
1779Well, Google Mock has an action to solve _exactly_ this problem:
1780
1781```
1782  InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
1783```
1784
1785will invoke the `N`-th (0-based) argument the mock function receives,
1786with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is
1787a function pointer or a functor, Google Mock handles them both.
1788
1789With that, you could write:
1790
1791```
1792using ::testing::_;
1793using ::testing::InvokeArgument;
1794...
1795  EXPECT_CALL(foo, DoThis(_, _))
1796      .WillOnce(InvokeArgument<1>(5));
1797  // Will execute (*fp)(5), where fp is the
1798  // second argument DoThis() receives.
1799```
1800
1801What if the callable takes an argument by reference? No problem - just
1802wrap it inside `ByRef()`:
1803
1804```
1805...
1806  MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
1807...
1808using ::testing::_;
1809using ::testing::ByRef;
1810using ::testing::InvokeArgument;
1811...
1812
1813  MockFoo foo;
1814  Helper helper;
1815  ...
1816  EXPECT_CALL(foo, Bar(_))
1817      .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
1818  // ByRef(helper) guarantees that a reference to helper, not a copy of it,
1819  // will be passed to the callable.
1820```
1821
1822What if the callable takes an argument by reference and we do **not**
1823wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a
1824copy_ of the argument, and pass a _reference to the copy_, instead of
1825a reference to the original value, to the callable. This is especially
1826handy when the argument is a temporary value:
1827
1828```
1829...
1830  MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
1831...
1832using ::testing::_;
1833using ::testing::InvokeArgument;
1834...
1835
1836  MockFoo foo;
1837  ...
1838  EXPECT_CALL(foo, DoThat(_))
1839      .WillOnce(InvokeArgument<0>(5.0, string("Hi")));
1840  // Will execute (*f)(5.0, string("Hi")), where f is the function pointer
1841  // DoThat() receives.  Note that the values 5.0 and string("Hi") are
1842  // temporary and dead once the EXPECT_CALL() statement finishes.  Yet
1843  // it's fine to perform this action later, since a copy of the values
1844  // are kept inside the InvokeArgument action.
1845```
1846
1847## Ignoring an Action's Result ##
1848
1849Sometimes you have an action that returns _something_, but you need an
1850action that returns `void` (perhaps you want to use it in a mock
1851function that returns `void`, or perhaps it needs to be used in
1852`DoAll()` and it's not the last in the list). `IgnoreResult()` lets
1853you do that. For example:
1854
1855```
1856using ::testing::_;
1857using ::testing::Invoke;
1858using ::testing::Return;
1859
1860int Process(const MyData& data);
1861string DoSomething();
1862
1863class MockFoo : public Foo {
1864 public:
1865  MOCK_METHOD1(Abc, void(const MyData& data));
1866  MOCK_METHOD0(Xyz, bool());
1867};
1868...
1869
1870  MockFoo foo;
1871  EXPECT_CALL(foo, Abc(_))
1872  // .WillOnce(Invoke(Process));
1873  // The above line won't compile as Process() returns int but Abc() needs
1874  // to return void.
1875      .WillOnce(IgnoreResult(Invoke(Process)));
1876
1877  EXPECT_CALL(foo, Xyz())
1878      .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
1879      // Ignores the string DoSomething() returns.
1880                      Return(true)));
1881```
1882
1883Note that you **cannot** use `IgnoreResult()` on an action that already
1884returns `void`. Doing so will lead to ugly compiler errors.
1885
1886## Selecting an Action's Arguments ##
1887
1888Say you have a mock function `Foo()` that takes seven arguments, and
1889you have a custom action that you want to invoke when `Foo()` is
1890called. Trouble is, the custom action only wants three arguments:
1891
1892```
1893using ::testing::_;
1894using ::testing::Invoke;
1895...
1896  MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
1897                         const map<pair<int, int>, double>& weight,
1898                         double min_weight, double max_wight));
1899...
1900
1901bool IsVisibleInQuadrant1(bool visible, int x, int y) {
1902  return visible && x >= 0 && y >= 0;
1903}
1904...
1905
1906  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1907      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(
1908```
1909
1910To please the compiler God, you can to define an "adaptor" that has
1911the same signature as `Foo()` and calls the custom action with the
1912right arguments:
1913
1914```
1915using ::testing::_;
1916using ::testing::Invoke;
1917
1918bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
1919                            const map<pair<int, int>, double>& weight,
1920                            double min_weight, double max_wight) {
1921  return IsVisibleInQuadrant1(visible, x, y);
1922}
1923...
1924
1925  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1926      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.
1927```
1928
1929But isn't this awkward?
1930
1931Google Mock provides a generic _action adaptor_, so you can spend your
1932time minding more important business than writing your own
1933adaptors. Here's the syntax:
1934
1935```
1936  WithArgs<N1, N2, ..., Nk>(action)
1937```
1938
1939creates an action that passes the arguments of the mock function at
1940the given indices (0-based) to the inner `action` and performs
1941it. Using `WithArgs`, our original example can be written as:
1942
1943```
1944using ::testing::_;
1945using ::testing::Invoke;
1946using ::testing::WithArgs;
1947...
1948  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1949      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
1950      // No need to define your own adaptor.
1951```
1952
1953For better readability, Google Mock also gives you:
1954
1955  * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and
1956  * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument.
1957
1958As you may have realized, `InvokeWithoutArgs(...)` is just syntactic
1959sugar for `WithoutArgs(Inovke(...))`.
1960
1961Here are more tips:
1962
1963  * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything.
1964  * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`.
1965  * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.
1966  * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work.
1967
1968## Ignoring Arguments in Action Functions ##
1969
1970The selecting-an-action's-arguments recipe showed us one way to make a
1971mock function and an action with incompatible argument lists fit
1972together. The downside is that wrapping the action in
1973`WithArgs<...>()` can get tedious for people writing the tests.
1974
1975If you are defining a function, method, or functor to be used with
1976`Invoke*()`, and you are not interested in some of its arguments, an
1977alternative to `WithArgs` is to declare the uninteresting arguments as
1978`Unused`. This makes the definition less cluttered and less fragile in
1979case the types of the uninteresting arguments change. It could also
1980increase the chance the action function can be reused. For example,
1981given
1982
1983```
1984  MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1985  MOCK_METHOD3(Bar, double(int index, double x, double y));
1986```
1987
1988instead of
1989
1990```
1991using ::testing::_;
1992using ::testing::Invoke;
1993
1994double DistanceToOriginWithLabel(const string& label, double x, double y) {
1995  return sqrt(x*x + y*y);
1996}
1997
1998double DistanceToOriginWithIndex(int index, double x, double y) {
1999  return sqrt(x*x + y*y);
2000}
2001...
2002
2003  EXEPCT_CALL(mock, Foo("abc", _, _))
2004      .WillOnce(Invoke(DistanceToOriginWithLabel));
2005  EXEPCT_CALL(mock, Bar(5, _, _))
2006      .WillOnce(Invoke(DistanceToOriginWithIndex));
2007```
2008
2009you could write
2010
2011```
2012using ::testing::_;
2013using ::testing::Invoke;
2014using ::testing::Unused;
2015
2016double DistanceToOrigin(Unused, double x, double y) {
2017  return sqrt(x*x + y*y);
2018}
2019...
2020
2021  EXEPCT_CALL(mock, Foo("abc", _, _))
2022      .WillOnce(Invoke(DistanceToOrigin));
2023  EXEPCT_CALL(mock, Bar(5, _, _))
2024      .WillOnce(Invoke(DistanceToOrigin));
2025```
2026
2027## Sharing Actions ##
2028
2029Just like matchers, a Google Mock action object consists of a pointer
2030to a ref-counted implementation object. Therefore copying actions is
2031also allowed and very efficient. When the last action that references
2032the implementation object dies, the implementation object will be
2033deleted.
2034
2035If you have some complex action that you want to use again and again,
2036you may not have to build it from scratch everytime. If the action
2037doesn't have an internal state (i.e. if it always does the same thing
2038no matter how many times it has been called), you can assign it to an
2039action variable and use that variable repeatedly. For example:
2040
2041```
2042  Action<bool(int*)> set_flag = DoAll(SetArgumentPointee<0>(5),
2043                                      Return(true));
2044  ... use set_flag in .WillOnce() and .WillRepeatedly() ...
2045```
2046
2047However, if the action has its own state, you may be surprised if you
2048share the action object. Suppose you have an action factory
2049`IncrementCounter(init)` which creates an action that increments and
2050returns a counter whose initial value is `init`, using two actions
2051created from the same expression and using a shared action will
2052exihibit different behaviors. Example:
2053
2054```
2055  EXPECT_CALL(foo, DoThis())
2056      .WillRepeatedly(IncrementCounter(0));
2057  EXPECT_CALL(foo, DoThat())
2058      .WillRepeatedly(IncrementCounter(0));
2059  foo.DoThis();  // Returns 1.
2060  foo.DoThis();  // Returns 2.
2061  foo.DoThat();  // Returns 1 - Blah() uses a different
2062                 // counter than Bar()'s.
2063```
2064
2065versus
2066
2067```
2068  Action<int()> increment = IncrementCounter(0);
2069
2070  EXPECT_CALL(foo, DoThis())
2071      .WillRepeatedly(increment);
2072  EXPECT_CALL(foo, DoThat())
2073      .WillRepeatedly(increment);
2074  foo.DoThis();  // Returns 1.
2075  foo.DoThis();  // Returns 2.
2076  foo.DoThat();  // Returns 3 - the counter is shared.
2077```
2078
2079# Misc Recipes on Using Google Mock #
2080
2081## Forcing a Verification ##
2082
2083When it's being destoyed, your friendly mock object will automatically
2084verify that all expectations on it have been satisfied, and will
2085generate [Google Test](http://code.google.com/p/googletest/) failures
2086if not. This is convenient as it leaves you with one less thing to
2087worry about. That is, unless you are not sure if your mock object will
2088be destoyed.
2089
2090How could it be that your mock object won't eventually be destroyed?
2091Well, it might be created on the heap and owned by the code you are
2092testing. Suppose there's a bug in that code and it doesn't delete the
2093mock object properly - you could end up with a passing test when
2094there's actually a bug.
2095
2096Using a heap checker is a good idea and can alleviate the concern, but
2097its implementation may not be 100% reliable. So, sometimes you do want
2098to _force_ Google Mock to verify a mock object before it is
2099(hopefully) destructed. You can do this with
2100`Mock::VerifyAndClearExpectations(&mock_object)`:
2101
2102```
2103TEST(MyServerTest, ProcessesRequest) {
2104  using ::testing::Mock;
2105
2106  MockFoo* const foo = new MockFoo;
2107  EXPECT_CALL(*foo, ...)...;
2108  // ... other expectations ...
2109
2110  // server now owns foo.
2111  MyServer server(foo);
2112  server.ProcessRequest(...);
2113
2114  // In case that server's destructor will forget to delete foo,
2115  // this will verify the expectations anyway.
2116  Mock::VerifyAndClearExpectations(foo);
2117}  // server is destroyed when it goes out of scope here.
2118```
2119
2120**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a
2121`bool` to indicate whether the verification was successful (`true` for
2122yes), so you can wrap that function call inside a `ASSERT_TRUE()` if
2123there is no point going further when the verification has failed.
2124
2125## Using Check Points ##
2126
2127Sometimes you may want to "reset" a mock object at various check
2128points in your test: at each check point, you verify that all existing
2129expectations on the mock object have been satisfied, and then you set
2130some new expectations on it as if it's newly created. This allows you
2131to work with a mock object in "phases" whose sizes are each
2132manageable.
2133
2134One such scenario is that in your test's `SetUp()` function, you may
2135want to put the object you are testing into a certain state, with the
2136help from a mock object. Once in the desired state, you want to clear
2137all expectations on the mock, such that in the `TEST_F` body you can
2138set fresh expectations on it.
2139
2140As you may have figured out, the `Mock::VerifyAndClearExpectations()`
2141function we saw in the previous recipe can help you here. Or, if you
2142are using `ON_CALL()` to set default actions on the mock object and
2143want to clear the default actions as well, use
2144`Mock::VerifyAndClear(&mock_object)` instead. This function does what
2145`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the
2146same `bool`, **plus** it clears the `ON_CALL()` statements on
2147`mock_object` too.
2148
2149Another trick you can use to achieve the same effect is to put the
2150expectations in sequences and insert calls to a dummy "check-point"
2151function at specific places. Then you can verify that the mock
2152function calls do happen at the right time. For example, if you are
2153exercising code:
2154
2155```
2156Foo(1);
2157Foo(2);
2158Foo(3);
2159```
2160
2161and want to verify that `Foo(1)` and `Foo(3)` both invoke
2162`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write:
2163
2164```
2165using ::testing::MockFunction;
2166
2167TEST(FooTest, InvokesBarCorrectly) {
2168  MyMock mock;
2169  // Class MockFunction<F> has exactly one mock method.  It is named
2170  // Call() and has type F.
2171  MockFunction<void(string check_point_name)> check;
2172  {
2173    InSequence s;
2174
2175    EXPECT_CALL(mock, Bar("a"));
2176    EXPECT_CALL(check, Call("1"));
2177    EXPECT_CALL(check, Call("2"));
2178    EXPECT_CALL(mock, Bar("a"));
2179  }
2180  Foo(1);
2181  check.Call("1");
2182  Foo(2);
2183  check.Call("2");
2184  Foo(3);
2185}
2186```
2187
2188The expectation spec says that the first `Bar("a")` must happen before
2189check point "1", the second `Bar("a")` must happen after check point "2",
2190and nothing should happen between the two check points. The explicit
2191check points make it easy to tell which `Bar("a")` is called by which
2192call to `Foo()`.
2193
2194## Mocking Destructors ##
2195
2196Sometimes you want to make sure a mock object is destructed at the
2197right time, e.g. after `bar->A()` is called but before `bar->B()` is
2198called. We already know that you can specify constraints on the order
2199of mock function calls, so all we need to do is to mock the destructor
2200of the mock function.
2201
2202This sounds simple, except for one problem: a destructor is a special
2203function with special syntax and special semantics, and the
2204`MOCK_METHOD0` macro doesn't work for it:
2205
2206```
2207  MOCK_METHOD0(~MockFoo, void());  // Won't compile!
2208```
2209
2210The good news is that you can use a simple pattern to achieve the same
2211effect. First, add a mock function `Die()` to your mock class and call
2212it in the destructor, like this:
2213
2214```
2215class MockFoo : public Foo {
2216  ...
2217  // Add the following two lines to the mock class.
2218  MOCK_METHOD0(Die, void());
2219  virtual ~MockFoo() { Die(); }
2220};
2221```
2222
2223(If the name `Die()` clashes with an existing symbol, choose another
2224name.) Now, we have translated the problem of testing when a `MockFoo`
2225object dies to testing when its `Die()` method is called:
2226
2227```
2228  MockFoo* foo = new MockFoo;
2229  MockBar* bar = new MockBar;
2230  ...
2231  {
2232    InSequence s;
2233
2234    // Expects *foo to die after bar->A() and before bar->B().
2235    EXPECT_CALL(*bar, A());
2236    EXPECT_CALL(*foo, Die());
2237    EXPECT_CALL(*bar, B());
2238  }
2239```
2240
2241And that's that.
2242
2243## Using Google Mock and Threads ##
2244
2245**IMPORTANT NOTE:** What we describe in this recipe is **NOT** true yet,
2246as Google Mock is not currently thread-safe.  However, all we need to
2247make it thread-safe is to implement some synchronization operations in
2248`<gtest/internal/gtest-port.h>` - and then the information below will
2249become true.
2250
2251In a **unit** test, it's best if you could isolate and test a piece of
2252code in a single-threaded context. That avoids race conditions and
2253dead locks, and makes debugging your test much easier.
2254
2255Yet many programs are multi-threaded, and sometimes to test something
2256we need to pound on it from more than one thread. Google Mock works
2257for this purpose too.
2258
2259Remember the steps for using a mock:
2260
2261  1. Create a mock object `foo`.
2262  1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`.
2263  1. The code under test calls methods of `foo`.
2264  1. Optionally, verify and reset the mock.
2265  1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.
2266
2267If you follow the following simple rules, your mocks and threads can
2268live happily togeter:
2269
2270  * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow.
2271  * Obviously, you can do step #1 without locking.
2272  * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh?
2273  * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic.
2274
2275If you violate the rules (for example, if you set expectations on a
2276mock while another thread is calling its methods), you get undefined
2277behavior. That's not fun, so don't do it.
2278
2279Google Mock guarantees that the action for a mock function is done in
2280the same thread that called the mock function. For example, in
2281
2282```
2283  EXPECT_CALL(mock, Foo(1))
2284      .WillOnce(action1);
2285  EXPECT_CALL(mock, Foo(2))
2286      .WillOnce(action2);
2287```
2288
2289if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2,
2290Google Mock will execute `action1` in thread 1 and `action2` in thread
22912.
2292
2293Google Mock does _not_ impose a sequence on actions performed in
2294different threads (doing so may create deadlocks as the actions may
2295need to cooperate). This means that the execution of `action1` and
2296`action2` in the above example _may_ interleave. If this is a problem,
2297you should add proper synchronization logic to `action1` and `action2`
2298to make the test thread-safe.
2299
2300
2301Also, remember that `DefaultValue<T>` is a global resource that
2302potentially affects _all_ living mock objects in your
2303program. Naturally, you won't want to mess with it from multiple
2304threads or when there still are mocks in action.
2305
2306## Controlling How Much Information Google Mock Prints ##
2307
2308When Google Mock sees something that has the potential of being an
2309error (e.g. a mock function with no expectation is called, a.k.a. an
2310uninteresting call, which is allowed but perhaps you forgot to
2311explicitly ban the call), it prints some warning messages, including
2312the arguments of the function and the return value. Hopefully this
2313will remind you to take a look and see if there is indeed a problem.
2314
2315Sometimes you are confident that your tests are correct and may not
2316appreciate such friendly messages. Some other times, you are debugging
2317your tests or learning about the behavior of the code you are testing,
2318and wish you could observe every mock call that happens (including
2319argument values and the return value). Clearly, one size doesn't fit
2320all.
2321
2322You can control how much Google Mock tells you using the
2323`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string
2324with three possible values:
2325
2326  * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros.
2327  * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default.
2328  * `error`: Google Mock will print errors only (least verbose).
2329
2330Alternatively, you can adjust the value of that flag from within your
2331tests like so:
2332
2333```
2334  ::testing::FLAGS_gmock_verbose = "error";
2335```
2336
2337Now, judiciously use the right flag to enable Google Mock serve you better!
2338
2339## Running Tests in Emacs ##
2340
2341If you build and run your tests in Emacs, the source file locations of
2342Google Mock and [Google Test](http://code.google.com/p/googletest/)
2343errors will be highlighted. Just press `<Enter>` on one of them and
2344you'll be taken to the offending line. Or, you can just type `C-x ``
2345to jump to the next error.
2346
2347To make it even easier, you can add the following lines to your
2348`~/.emacs` file:
2349
2350```
2351(global-set-key "\M-m"   'compile)  ; m is for make
2352(global-set-key [M-down] 'next-error)
2353(global-set-key [M-up]   '(lambda () (interactive) (next-error -1)))
2354```
2355
2356Then you can type `M-m` to start a build, or `M-up`/`M-down` to move
2357back and forth between errors.
2358
2359## Fusing Google Mock Source Files ##
2360
2361Google Mock's implementation consists of dozens of files (excluding
2362its own tests).  Sometimes you may want them to be packaged up in
2363fewer files instead, such that you can easily copy them to a new
2364machine and start hacking there.  For this we provide an experimental
2365Python script `fuse_gmock_files.py` in the `scripts/` directory
2366(starting with release 1.2.0).  Assuming you have Python 2.4 or above
2367installed on your machine, just go to that directory and run
2368```
2369python fuse_gmock_files.py OUTPUT_DIR
2370```
2371
2372and you should see an `OUTPUT_DIR` directory being created with files
2373`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it.
2374These three files contain everything you need to use Google Mock (and
2375Google Test).  Just copy them to anywhere you want and you are ready
2376to write tests and use mocks.  You can use the
2377[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests
2378against them.
2379
2380# Extending Google Mock #
2381
2382## Writing New Matchers Quickly ##
2383
2384The `MATCHER*` family of macros can be used to define custom matchers
2385easily.  The syntax:
2386
2387```
2388MATCHER(name, "description string") { statements; }
2389```
2390
2391will define a matcher with the given name that executes the
2392statements, which must return a `bool` to indicate if the match
2393succeeds.  Inside the statements, you can refer to the value being
2394matched by `arg`, and refer to its type by `arg_type`.
2395
2396The description string documents what the matcher does, and is used to
2397generate the failure message when the match fails.  Since a
2398`MATCHER()` is usually defined in a header file shared by multiple C++
2399source files, we require the description to be a C-string _literal_ to
2400avoid possible side effects.  It can be empty (`""`), in which case
2401Google Mock will use the sequence of words in the matcher name as the
2402description.
2403
2404For example:
2405```
2406MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
2407```
2408allows you to write
2409```
2410  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.
2411  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
2412```
2413or,
2414```
2415  // Verifies that the value of some_expression is divisible by 7.
2416  EXPECT_THAT(some_expression, IsDivisibleBy7());
2417```
2418If the above assertion fails, it will print something like:
2419```
2420  Value of: some_expression
2421  Expected: is divisible by 7
2422    Actual: 27
2423```
2424where the description `"is divisible by 7"` is automatically calculated from the
2425matcher name `IsDivisibleBy7`.
2426
2427Optionally, you can stream additional information to a hidden argument
2428named `result_listener` to explain the match result. For example, a
2429better definition of `IsDivisibleBy7` is:
2430```
2431MATCHER(IsDivisibleBy7, "") {
2432  if ((arg % 7) == 0)
2433    return true;
2434
2435  *result_listener << "the remainder is " << (arg % 7);
2436  return false;
2437}
2438```
2439
2440With this definition, the above assertion will give a better message:
2441```
2442  Value of: some_expression
2443  Expected: is divisible by 7
2444    Actual: 27 (the remainder is 6)
2445```
2446
2447You should let `MatchAndExplain()` print _any additional information_
2448that can help a user understand the match result. Note that it should
2449explain why the match succeeds in case of a success (unless it's
2450obvious) - this is useful when the matcher is used inside
2451`Not()`. There is no need to print the argument value itself, as
2452Google Mock already prints it for you.
2453
2454**Notes:**
2455
2456  1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you).  This allows the matcher to be polymorphic.  For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`.  In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on.
2457  1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock.
2458
2459## Writing New Parameterized Matchers Quickly ##
2460
2461Sometimes you'll want to define a matcher that has parameters.  For that you
2462can use the macro:
2463```
2464MATCHER_P(name, param_name, "description string") { statements; }
2465```
2466
2467For example:
2468```
2469MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2470```
2471will allow you to write:
2472```
2473  EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2474```
2475which may lead to this message (assuming `n` is 10):
2476```
2477  Value of: Blah("a")
2478  Expected: has absolute value 10
2479    Actual: -9
2480```
2481
2482Note that both the matcher description and its parameter are
2483printed, making the message human-friendly.
2484
2485In the matcher definition body, you can write `foo_type` to
2486reference the type of a parameter named `foo`.  For example, in the
2487body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write
2488`value_type` to refer to the type of `value`.
2489
2490Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to
2491`MATCHER_P10` to support multi-parameter matchers:
2492```
2493MATCHER_Pk(name, param_1, ..., param_k, "description string") { statements; }
2494```
2495
2496Please note that the custom description string is for a particular
2497**instance** of the matcher, where the parameters have been bound to
2498actual values.  Therefore usually you'll want the parameter values to
2499be part of the description.  Google Mock lets you do that using
2500Python-style interpolations.  The following syntaxes are supported
2501currently:
2502
2503| `%%` | a single `%` character |
2504|:-----|:-----------------------|
2505| `%(*)s` | all parameters of the matcher printed as a tuple |
2506| `%(foo)s` | value of the matcher parameter named `foo` |
2507
2508For example,
2509```
2510  MATCHER_P2(InClosedRange, low, hi, "is in range [%(low)s, %(hi)s]") {
2511    return low <= arg && arg <= hi;
2512  }
2513  ...
2514  EXPECT_THAT(3, InClosedRange(4, 6));
2515```
2516would generate a failure that contains the message:
2517```
2518  Expected: is in range [4, 6]
2519```
2520
2521If you specify `""` as the description, the failure message will
2522contain the sequence of words in the matcher name followed by the
2523parameter values printed as a tuple.  For example,
2524```
2525  MATCHER_P2(InClosedRange, low, hi, "") { ... }
2526  ...
2527  EXPECT_THAT(3, InClosedRange(4, 6));
2528```
2529would generate a failure that contains the text:
2530```
2531  Expected: in closed range (4, 6)
2532```
2533
2534For the purpose of typing, you can view
2535```
2536MATCHER_Pk(Foo, p1, ..., pk, "description string") { ... }
2537```
2538as shorthand for
2539```
2540template <typename p1_type, ..., typename pk_type>
2541FooMatcherPk<p1_type, ..., pk_type>
2542Foo(p1_type p1, ..., pk_type pk) { ... }
2543```
2544
2545When you write `Foo(v1, ..., vk)`, the compiler infers the types of
2546the parameters `v1`, ..., and `vk` for you.  If you are not happy with
2547the result of the type inference, you can specify the types by
2548explicitly instantiating the template, as in `Foo<long, bool>(5, false)`.
2549As said earlier, you don't get to (or need to) specify
2550`arg_type` as that's determined by the context in which the matcher
2551is used.
2552
2553You can assign the result of expression `Foo(p1, ..., pk)` to a
2554variable of type `FooMatcherPk<p1_type, ..., pk_type>`.  This can be
2555useful when composing matchers.  Matchers that don't have a parameter
2556or have only one parameter have special types: you can assign `Foo()`
2557to a `FooMatcher`-typed variable, and assign `Foo(p)` to a
2558`FooMatcherP<p_type>`-typed variable.
2559
2560While you can instantiate a matcher template with reference types,
2561passing the parameters by pointer usually makes your code more
2562readable.  If, however, you still want to pass a parameter by
2563reference, be aware that in the failure message generated by the
2564matcher you will see the value of the referenced object but not its
2565address.
2566
2567You can overload matchers with different numbers of parameters:
2568```
2569MATCHER_P(Blah, a, "description string 1") { ... }
2570MATCHER_P2(Blah, a, b, "description string 2") { ... }
2571```
2572
2573While it's tempting to always use the `MATCHER*` macros when defining
2574a new matcher, you should also consider implementing
2575`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see
2576the recipes that follow), especially if you need to use the matcher a
2577lot.  While these approaches require more work, they give you more
2578control on the types of the value being matched and the matcher
2579parameters, which in general leads to better compiler error messages
2580that pay off in the long run.  They also allow overloading matchers
2581based on parameter types (as opposed to just based on the number of
2582parameters).
2583
2584## Writing New Monomorphic Matchers ##
2585
2586A matcher of argument type `T` implements
2587`::testing::MatcherInterface<T>` and does two things: it tests whether a
2588value of type `T` matches the matcher, and can describe what kind of
2589values it matches. The latter ability is used for generating readable
2590error messages when expectations are violated.
2591
2592The interface looks like this:
2593
2594```
2595class MatchResultListener {
2596 public:
2597  ...
2598  // Streams x to the underlying ostream; does nothing if the ostream
2599  // is NULL.
2600  template <typename T>
2601  MatchResultListener& operator<<(const T& x);
2602
2603  // Returns the underlying ostream.
2604  ::std::ostream* stream();
2605};
2606
2607template <typename T>
2608class MatcherInterface {
2609 public:
2610  virtual ~MatcherInterface();
2611
2612  // Returns true iff the matcher matches x; also explains the match
2613  // result to 'listener'.
2614  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
2615
2616  // Describes this matcher to an ostream.
2617  virtual void DescribeTo(::std::ostream* os) const = 0;
2618
2619  // Describes the negation of this matcher to an ostream.
2620  virtual void DescribeNegationTo(::std::ostream* os) const;
2621};
2622```
2623
2624If you need a custom matcher but `Truly()` is not a good option (for
2625example, you may not be happy with the way `Truly(predicate)`
2626describes itself, or you may want your matcher to be polymorphic as
2627`Eq(value)` is), you can define a matcher to do whatever you want in
2628two steps: first implement the matcher interface, and then define a
2629factory function to create a matcher instance. The second step is not
2630strictly needed but it makes the syntax of using the matcher nicer.
2631
2632For example, you can define a matcher to test whether an `int` is
2633divisible by 7 and then use it like this:
2634```
2635using ::testing::MakeMatcher;
2636using ::testing::Matcher;
2637using ::testing::MatcherInterface;
2638using ::testing::MatchResultListener;
2639
2640class DivisibleBy7Matcher : public MatcherInterface<int> {
2641 public:
2642  virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
2643    return (n % 7) == 0;
2644  }
2645
2646  virtual void DescribeTo(::std::ostream* os) const {
2647    *os << "is divisible by 7";
2648  }
2649
2650  virtual void DescribeNegationTo(::std::ostream* os) const {
2651    *os << "is not divisible by 7";
2652  }
2653};
2654
2655inline Matcher<int> DivisibleBy7() {
2656  return MakeMatcher(new DivisibleBy7Matcher);
2657}
2658...
2659
2660  EXPECT_CALL(foo, Bar(DivisibleBy7()));
2661```
2662
2663You may improve the matcher message by streaming additional
2664information to the `listener` argument in `MatchAndExplain()`:
2665
2666```
2667class DivisibleBy7Matcher : public MatcherInterface<int> {
2668 public:
2669  virtual bool MatchAndExplain(int n,
2670                               MatchResultListener* listener) const {
2671    const int remainder = n % 7;
2672    if (remainder != 0) {
2673      *listener << "the remainder is " << remainder;
2674    }
2675    return remainder == 0;
2676  }
2677  ...
2678};
2679```
2680
2681Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this:
2682```
2683Value of: x
2684Expected: is divisible by 7
2685  Actual: 23 (the remainder is 2)
2686```
2687
2688## Writing New Polymorphic Matchers ##
2689
2690You've learned how to write your own matchers in the previous
2691recipe. Just one problem: a matcher created using `MakeMatcher()` only
2692works for one particular type of arguments. If you want a
2693_polymorphic_ matcher that works with arguments of several types (for
2694instance, `Eq(x)` can be used to match a `value` as long as `value` ==
2695`x` compiles -- `value` and `x` don't have to share the same type),
2696you can learn the trick from `<gmock/gmock-matchers.h>` but it's a bit
2697involved.
2698
2699Fortunately, most of the time you can define a polymorphic matcher
2700easily with the help of `MakePolymorphicMatcher()`. Here's how you can
2701define `NotNull()` as an example:
2702
2703```
2704using ::testing::MakePolymorphicMatcher;
2705using ::testing::MatchResultListener;
2706using ::testing::NotNull;
2707using ::testing::PolymorphicMatcher;
2708
2709class NotNullMatcher {
2710 public:
2711  // To implement a polymorphic matcher, first define a COPYABLE class
2712  // that has three members MatchAndExplain(), DescribeTo(), and
2713  // DescribeNegationTo(), like the following.
2714
2715  // In this example, we want to use NotNull() with any pointer, so
2716  // MatchAndExplain() accepts a pointer of any type as its first argument.
2717  // In general, you can define MatchAndExplain() as an ordinary method or
2718  // a method template, or even overload it.
2719  template <typename T>
2720  bool MatchAndExplain(T* p,
2721                       MatchResultListener* /* listener */) const {
2722    return p != NULL;
2723  }
2724
2725  // Describes the property of a value matching this matcher.
2726  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
2727
2728  // Describes the property of a value NOT matching this matcher.
2729  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
2730};
2731
2732// To construct a polymorphic matcher, pass an instance of the class
2733// to MakePolymorphicMatcher().  Note the return type.
2734inline PolymorphicMatcher<NotNullMatcher> NotNull() {
2735  return MakePolymorphicMatcher(NotNullMatcher());
2736}
2737...
2738
2739  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.
2740```
2741
2742**Note:** Your polymorphic matcher class does **not** need to inherit from
2743`MatcherInterface` or any other class, and its methods do **not** need
2744to be virtual.
2745
2746Like in a monomorphic matcher, you may explain the match result by
2747streaming additional information to the `listener` argument in
2748`MatchAndExplain()`.
2749
2750## Writing New Cardinalities ##
2751
2752A cardinality is used in `Times()` to tell Google Mock how many times
2753you expect a call to occur. It doesn't have to be exact. For example,
2754you can say `AtLeast(5)` or `Between(2, 4)`.
2755
2756If the built-in set of cardinalities doesn't suit you, you are free to
2757define your own by implementing the following interface (in namespace
2758`testing`):
2759
2760```
2761class CardinalityInterface {
2762 public:
2763  virtual ~CardinalityInterface();
2764
2765  // Returns true iff call_count calls will satisfy this cardinality.
2766  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
2767
2768  // Returns true iff call_count calls will saturate this cardinality.
2769  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
2770
2771  // Describes self to an ostream.
2772  virtual void DescribeTo(::std::ostream* os) const = 0;
2773};
2774```
2775
2776For example, to specify that a call must occur even number of times,
2777you can write
2778
2779```
2780using ::testing::Cardinality;
2781using ::testing::CardinalityInterface;
2782using ::testing::MakeCardinality;
2783
2784class EvenNumberCardinality : public CardinalityInterface {
2785 public:
2786  virtual bool IsSatisfiedByCallCount(int call_count) const {
2787    return (call_count % 2) == 0;
2788  }
2789
2790  virtual bool IsSaturatedByCallCount(int call_count) const {
2791    return false;
2792  }
2793
2794  virtual void DescribeTo(::std::ostream* os) const {
2795    *os << "called even number of times";
2796  }
2797};
2798
2799Cardinality EvenNumber() {
2800  return MakeCardinality(new EvenNumberCardinality);
2801}
2802...
2803
2804  EXPECT_CALL(foo, Bar(3))
2805      .Times(EvenNumber());
2806```
2807
2808## Writing New Actions Quickly ##
2809
2810If the built-in actions don't work for you, and you find it
2811inconvenient to use `Invoke()`, you can use a macro from the `ACTION*`
2812family to quickly define a new action that can be used in your code as
2813if it's a built-in action.
2814
2815By writing
2816```
2817ACTION(name) { statements; }
2818```
2819in a namespace scope (i.e. not inside a class or function), you will
2820define an action with the given name that executes the statements.
2821The value returned by `statements` will be used as the return value of
2822the action.  Inside the statements, you can refer to the K-th
2823(0-based) argument of the mock function as `argK`.  For example:
2824```
2825ACTION(IncrementArg1) { return ++(*arg1); }
2826```
2827allows you to write
2828```
2829... WillOnce(IncrementArg1());
2830```
2831
2832Note that you don't need to specify the types of the mock function
2833arguments.  Rest assured that your code is type-safe though:
2834you'll get a compiler error if `*arg1` doesn't support the `++`
2835operator, or if the type of `++(*arg1)` isn't compatible with the mock
2836function's return type.
2837
2838Another example:
2839```
2840ACTION(Foo) {
2841  (*arg2)(5);
2842  Blah();
2843  *arg1 = 0;
2844  return arg0;
2845}
2846```
2847defines an action `Foo()` that invokes argument #2 (a function pointer)
2848with 5, calls function `Blah()`, sets the value pointed to by argument
2849#1 to 0, and returns argument #0.
2850
2851For more convenience and flexibility, you can also use the following
2852pre-defined symbols in the body of `ACTION`:
2853
2854| `argK_type` | The type of the K-th (0-based) argument of the mock function |
2855|:------------|:-------------------------------------------------------------|
2856| `args`      | All arguments of the mock function as a tuple                |
2857| `args_type` | The type of all arguments of the mock function as a tuple    |
2858| `return_type` | The return type of the mock function                         |
2859| `function_type` | The type of the mock function                                |
2860
2861For example, when using an `ACTION` as a stub action for mock function:
2862```
2863int DoSomething(bool flag, int* ptr);
2864```
2865we have:
2866| **Pre-defined Symbol** | **Is Bound To** |
2867|:-----------------------|:----------------|
2868| `arg0`                 | the value of `flag` |
2869| `arg0_type`            | the type `bool` |
2870| `arg1`                 | the value of `ptr` |
2871| `arg1_type`            | the type `int*` |
2872| `args`                 | the tuple `(flag, ptr)` |
2873| `args_type`            | the type `std::tr1::tuple<bool, int*>` |
2874| `return_type`          | the type `int`  |
2875| `function_type`        | the type `int(bool, int*)` |
2876
2877## Writing New Parameterized Actions Quickly ##
2878
2879Sometimes you'll want to parameterize an action you define.  For that
2880we have another macro
2881```
2882ACTION_P(name, param) { statements; }
2883```
2884
2885For example,
2886```
2887ACTION_P(Add, n) { return arg0 + n; }
2888```
2889will allow you to write
2890```
2891// Returns argument #0 + 5.
2892... WillOnce(Add(5));
2893```
2894
2895For convenience, we use the term _arguments_ for the values used to
2896invoke the mock function, and the term _parameters_ for the values
2897used to instantiate an action.
2898
2899Note that you don't need to provide the type of the parameter either.
2900Suppose the parameter is named `param`, you can also use the
2901Google-Mock-defined symbol `param_type` to refer to the type of the
2902parameter as inferred by the compiler.  For example, in the body of
2903`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`.
2904
2905Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support
2906multi-parameter actions.  For example,
2907```
2908ACTION_P2(ReturnDistanceTo, x, y) {
2909  double dx = arg0 - x;
2910  double dy = arg1 - y;
2911  return sqrt(dx*dx + dy*dy);
2912}
2913```
2914lets you write
2915```
2916... WillOnce(ReturnDistanceTo(5.0, 26.5));
2917```
2918
2919You can view `ACTION` as a degenerated parameterized action where the
2920number of parameters is 0.
2921
2922You can also easily define actions overloaded on the number of parameters:
2923```
2924ACTION_P(Plus, a) { ... }
2925ACTION_P2(Plus, a, b) { ... }
2926```
2927
2928## Restricting the Type of an Argument or Parameter in an ACTION ##
2929
2930For maximum brevity and reusability, the `ACTION*` macros don't ask
2931you to provide the types of the mock function arguments and the action
2932parameters.  Instead, we let the compiler infer the types for us.
2933
2934Sometimes, however, we may want to be more explicit about the types.
2935There are several tricks to do that.  For example:
2936```
2937ACTION(Foo) {
2938  // Makes sure arg0 can be converted to int.
2939  int n = arg0;
2940  ... use n instead of arg0 here ...
2941}
2942
2943ACTION_P(Bar, param) {
2944  // Makes sure the type of arg1 is const char*.
2945  ::testing::StaticAssertTypeEq<const char*, arg1_type>();
2946
2947  // Makes sure param can be converted to bool.
2948  bool flag = param;
2949}
2950```
2951where `StaticAssertTypeEq` is a compile-time assertion in Google Test
2952that verifies two types are the same.
2953
2954## Writing New Action Templates Quickly ##
2955
2956Sometimes you want to give an action explicit template parameters that
2957cannot be inferred from its value parameters.  `ACTION_TEMPLATE()`
2958supports that and can be viewed as an extension to `ACTION()` and
2959`ACTION_P*()`.
2960
2961The syntax:
2962```
2963ACTION_TEMPLATE(ActionName,
2964                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
2965                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
2966```
2967
2968defines an action template that takes _m_ explicit template parameters
2969and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is
2970between 0 and 10.  `name_i` is the name of the i-th template
2971parameter, and `kind_i` specifies whether it's a `typename`, an
2972integral constant, or a template.  `p_i` is the name of the i-th value
2973parameter.
2974
2975Example:
2976```
2977// DuplicateArg<k, T>(output) converts the k-th argument of the mock
2978// function to type T and copies it to *output.
2979ACTION_TEMPLATE(DuplicateArg,
2980                // Note the comma between int and k:
2981                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
2982                AND_1_VALUE_PARAMS(output)) {
2983  *output = T(std::tr1::get<k>(args));
2984}
2985```
2986
2987To create an instance of an action template, write:
2988```
2989  ActionName<t1, ..., t_m>(v1, ..., v_n)
2990```
2991where the `t`s are the template arguments and the
2992`v`s are the value arguments.  The value argument
2993types are inferred by the compiler.  For example:
2994```
2995using ::testing::_;
2996...
2997  int n;
2998  EXPECT_CALL(mock, Foo(_, _))
2999      .WillOnce(DuplicateArg<1, unsigned char>(&n));
3000```
3001
3002If you want to explicitly specify the value argument types, you can
3003provide additional template arguments:
3004```
3005  ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
3006```
3007where `u_i` is the desired type of `v_i`.
3008
3009`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the
3010number of value parameters, but not on the number of template
3011parameters.  Without the restriction, the meaning of the following is
3012unclear:
3013
3014```
3015  OverloadedAction<int, bool>(x);
3016```
3017
3018Are we using a single-template-parameter action where `bool` refers to
3019the type of `x`, or a two-template-parameter action where the compiler
3020is asked to infer the type of `x`?
3021
3022## Using the ACTION Object's Type ##
3023
3024If you are writing a function that returns an `ACTION` object, you'll
3025need to know its type.  The type depends on the macro used to define
3026the action and the parameter types.  The rule is relatively simple:
3027| **Given Definition** | **Expression** | **Has Type** |
3028|:---------------------|:---------------|:-------------|
3029| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
3030| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` |   `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
3031| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
3032| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` |
3033| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
3034| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` |
3035| ...                  | ...            | ...          |
3036
3037Note that we have to pick different suffixes (`Action`, `ActionP`,
3038`ActionP2`, and etc) for actions with different numbers of value
3039parameters, or the action definitions cannot be overloaded on the
3040number of them.
3041
3042## Writing New Monomorphic Actions ##
3043
3044While the `ACTION*` macros are very convenient, sometimes they are
3045inappropriate.  For example, despite the tricks shown in the previous
3046recipes, they don't let you directly specify the types of the mock
3047function arguments and the action parameters, which in general leads
3048to unoptimized compiler error messages that can baffle unfamiliar
3049users.  They also don't allow overloading actions based on parameter
3050types without jumping through some hoops.
3051
3052An alternative to the `ACTION*` macros is to implement
3053`::testing::ActionInterface<F>`, where `F` is the type of the mock
3054function in which the action will be used. For example:
3055
3056```
3057template <typename F>class ActionInterface {
3058 public:
3059  virtual ~ActionInterface();
3060
3061  // Performs the action.  Result is the return type of function type
3062  // F, and ArgumentTuple is the tuple of arguments of F.
3063  //
3064  // For example, if F is int(bool, const string&), then Result would
3065  // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>.
3066  virtual Result Perform(const ArgumentTuple& args) = 0;
3067};
3068
3069using ::testing::_;
3070using ::testing::Action;
3071using ::testing::ActionInterface;
3072using ::testing::MakeAction;
3073
3074typedef int IncrementMethod(int*);
3075
3076class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
3077 public:
3078  virtual int Perform(const tr1::tuple<int*>& args) {
3079    int* p = tr1::get<0>(args);  // Grabs the first argument.
3080    return *p++;
3081  }
3082};
3083
3084Action<IncrementMethod> IncrementArgument() {
3085  return MakeAction(new IncrementArgumentAction);
3086}
3087...
3088
3089  EXPECT_CALL(foo, Baz(_))
3090      .WillOnce(IncrementArgument());
3091
3092  int n = 5;
3093  foo.Baz(&n);  // Should return 5 and change n to 6.
3094```
3095
3096## Writing New Polymorphic Actions ##
3097
3098The previous recipe showed you how to define your own action. This is
3099all good, except that you need to know the type of the function in
3100which the action will be used. Sometimes that can be a problem. For
3101example, if you want to use the action in functions with _different_
3102types (e.g. like `Return()` and `SetArgumentPointee()`).
3103
3104If an action can be used in several types of mock functions, we say
3105it's _polymorphic_. The `MakePolymorphicAction()` function template
3106makes it easy to define such an action:
3107
3108```
3109namespace testing {
3110
3111template <typename Impl>
3112PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);
3113
3114}  // namespace testing
3115```
3116
3117As an example, let's define an action that returns the second argument
3118in the mock function's argument list. The first step is to define an
3119implementation class:
3120
3121```
3122class ReturnSecondArgumentAction {
3123 public:
3124  template <typename Result, typename ArgumentTuple>
3125  Result Perform(const ArgumentTuple& args) const {
3126    // To get the i-th (0-based) argument, use tr1::get<i>(args).
3127    return tr1::get<1>(args);
3128  }
3129};
3130```
3131
3132This implementation class does _not_ need to inherit from any
3133particular class. What matters is that it must have a `Perform()`
3134method template. This method template takes the mock function's
3135arguments as a tuple in a **single** argument, and returns the result of
3136the action. It can be either `const` or not, but must be invokable
3137with exactly one template argument, which is the result type. In other
3138words, you must be able to call `Perform<R>(args)` where `R` is the
3139mock function's return type and `args` is its arguments in a tuple.
3140
3141Next, we use `MakePolymorphicAction()` to turn an instance of the
3142implementation class into the polymorphic action we need. It will be
3143convenient to have a wrapper for this:
3144
3145```
3146using ::testing::MakePolymorphicAction;
3147using ::testing::PolymorphicAction;
3148
3149PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
3150  return MakePolymorphicAction(ReturnSecondArgumentAction());
3151}
3152```
3153
3154Now, you can use this polymorphic action the same way you use the
3155built-in ones:
3156
3157```
3158using ::testing::_;
3159
3160class MockFoo : public Foo {
3161 public:
3162  MOCK_METHOD2(DoThis, int(bool flag, int n));
3163  MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
3164};
3165...
3166
3167  MockFoo foo;
3168  EXPECT_CALL(foo, DoThis(_, _))
3169      .WillOnce(ReturnSecondArgument());
3170  EXPECT_CALL(foo, DoThat(_, _, _))
3171      .WillOnce(ReturnSecondArgument());
3172  ...
3173  foo.DoThis(true, 5);         // Will return 5.
3174  foo.DoThat(1, "Hi", "Bye");  // Will return "Hi".
3175```
3176
3177## Teaching Google Mock How to Print Your Values ##
3178
3179When an uninteresting or unexpected call occurs, Google Mock prints
3180the argument values to help you debug.  The `EXPECT_THAT` and
3181`ASSERT_THAT` assertions also print the value being validated when the
3182test fails.  Google Mock does this using the user-extensible value
3183printer defined in `<gmock/gmock-printers.h>`.
3184
3185This printer knows how to print the built-in C++ types, native arrays,
3186STL containers, and any type that supports the `<<` operator. For
3187other types, it prints the raw bytes in the value and hope you the
3188user can figure it out.
3189
3190Did I say that the printer is `extensible`? That means you can teach
3191it to do a better job at printing your particular type than to dump
3192the bytes. To do that, you just need to define `<<` for your type:
3193
3194```
3195#include <iostream>
3196
3197namespace foo {
3198
3199class Foo { ... };
3200
3201// It's important that the << operator is defined in the SAME
3202// namespace that defines Foo.  C++'s look-up rules rely on that.
3203::std::ostream& operator<<(::std::ostream& os, const Foo& foo) {
3204  return os << foo.DebugString();  // Whatever needed to print foo to os.
3205}
3206
3207}  // namespace foo
3208```
3209
3210Sometimes, this might not be an option. For example, your team may
3211consider it dangerous or bad style to have a `<<` operator for `Foo`,
3212or `Foo` may already have a `<<` operator that doesn't do what you
3213want (and you cannot change it). Don't despair though - Google Mock
3214gives you a second chance to get it right. Namely, you can define a
3215`PrintTo()` function like this:
3216
3217```
3218#include <iostream>
3219
3220namespace foo {
3221
3222class Foo { ... };
3223
3224// It's important that PrintTo() is defined in the SAME
3225// namespace that defines Foo.  C++'s look-up rules rely on that.
3226void PrintTo(const Foo& foo, ::std::ostream* os) {
3227  *os << foo.DebugString();  // Whatever needed to print foo to os.
3228}
3229
3230}  // namespace foo
3231```
3232
3233What if you have both `<<` and `PrintTo()`? In this case, the latter
3234will override the former when Google Mock is concerned. This allows
3235you to customize how the value should appear in Google Mock's output
3236without affecting code that relies on the behavior of its `<<`
3237operator.
3238
3239**Note:** When printing a pointer of type `T*`, Google Mock calls
3240`PrintTo(T*, std::ostream* os)` instead of `operator<<(std::ostream&, T*)`.
3241Therefore the only way to affect how a pointer is printed by Google
3242Mock is to define `PrintTo()` for it. Also note that `T*` and `const T*`
3243are different types, so you may need to define `PrintTo()` for both.
3244
3245Why does Google Mock treat pointers specially? There are several reasons:
3246
3247  * We cannot use `operator<<` to print a `signed char*` or `unsigned char*`, since it will print the pointer as a NUL-terminated C string, which likely will cause an access violation.
3248  * We want `NULL` pointers to be printed as `"NULL"`, but `operator<<` prints it as `"0"`, `"nullptr"`, or something else, depending on the compiler.
3249  * With some compilers, printing a `NULL` `char*` using `operator<<` will segfault.
3250  * `operator<<` prints a function pointer as a `bool` (hence it always prints `"1"`), which is not very useful.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_5/Documentation.md
r0r249096
1This page lists all documentation wiki pages for Google Mock **version 1.5.0** -- **if you use a different version of Google Mock, please read the documentation for that specific version instead.**
2
3  * [ForDummies](V1_5_ForDummies.md) -- start here if you are new to Google Mock.
4  * [CheatSheet](V1_5_CheatSheet.md) -- a quick reference.
5  * [CookBook](V1_5_CookBook.md) -- recipes for doing various tasks using Google Mock.
6  * [FrequentlyAskedQuestions](V1_5_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list.
7
8To contribute code to Google Mock, read:
9
10  * DevGuide -- read this _before_ writing your first patch.
11  * [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_5/ForDummies.md
r0r249096
1
2
3(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](V1_5_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md).)
4
5# What Is Google C++ Mocking Framework? #
6When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc).
7
8**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community:
9
10  * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
11  * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive.
12
13If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks.
14
15**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java.
16
17Using Google Mock involves three basic steps:
18
19  1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class;
20  1. Create some mock objects and specify its expectations and behavior using an intuitive syntax;
21  1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises.
22
23# Why Google Mock? #
24While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_:
25
26  * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it.
27  * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions.
28  * The knowledge you gained from using one mock doesn't transfer to the next.
29
30In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference.
31
32Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you:
33
34  * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid".
35  * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database).
36  * Your tests are brittle as some resources they use are unreliable (e.g. the network).
37  * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one.
38  * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best.
39  * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks.
40
41We encourage you to use Google Mock as:
42
43  * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs!
44  * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators.
45
46# Getting Started #
47Using Google Mock is easy! Inside your C++ source file, just #include `<gtest/gtest.h>` and `<gmock/gmock.h>`, and you are ready to go.
48
49# A Case for Mock Turtles #
50Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
51
52```
53class Turtle {
54  ...
55  virtual ~Turtle() {}
56  virtual void PenUp() = 0;
57  virtual void PenDown() = 0;
58  virtual void Forward(int distance) = 0;
59  virtual void Turn(int degrees) = 0;
60  virtual void GoTo(int x, int y) = 0;
61  virtual int GetX() const = 0;
62  virtual int GetY() const = 0;
63};
64```
65
66(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.)
67
68You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle.
69
70Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_.
71
72# Writing the Mock Class #
73If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.)
74
75## How to Define It ##
76Using the `Turtle` interface as example, here are the simple steps you need to follow:
77
78  1. Derive a class `MockTurtle` from `Turtle`.
79  1. Take a virtual function of `Turtle`. Count how many arguments it has.
80  1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so.
81  1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_).
82  1. Repeat until all virtual functions you want to mock are done.
83
84After the process, you should have something like:
85
86```
87#include <gmock/gmock.h>  // Brings in Google Mock.
88class MockTurtle : public Turtle {
89 public:
90  ...
91  MOCK_METHOD0(PenUp, void());
92  MOCK_METHOD0(PenDown, void());
93  MOCK_METHOD1(Forward, void(int distance));
94  MOCK_METHOD1(Turn, void(int degrees));
95  MOCK_METHOD2(GoTo, void(int x, int y));
96  MOCK_CONST_METHOD0(GetX, int());
97  MOCK_CONST_METHOD0(GetY, int());
98};
99```
100
101You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins.
102
103**Tip:** If even this is too much work for you, you'll find the
104`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful.  This command-line
105tool requires that you have Python 2.4 installed.  You give it a C++ file and the name of an abstract class defined in it,
106and it will print the definition of the mock class for you.  Due to the
107complexity of the C++ language, this script may not always work, but
108it can be quite handy when it does.  For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README).
109
110## Where to Put It ##
111When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?)
112
113So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed.
114
115Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does.
116
117# Using Mocks in Tests #
118Once you have a mock class, using it is easy. The typical work flow is:
119
120  1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.).
121  1. Create some mock objects.
122  1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.).
123  1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately.
124  1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.
125
126Here's an example:
127
128```
129#include "path/to/mock-turtle.h"
130#include <gmock/gmock.h>
131#include <gtest/gtest.h>
132using ::testing::AtLeast;                     // #1
133
134TEST(PainterTest, CanDrawSomething) {
135  MockTurtle turtle;                          // #2
136  EXPECT_CALL(turtle, PenDown())              // #3
137      .Times(AtLeast(1));
138
139  Painter painter(&turtle);                   // #4
140
141  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
142}                                             // #5
143
144int main(int argc, char** argv) {
145  // The following line must be executed to initialize Google Mock
146  // (and Google Test) before running the tests.
147  ::testing::InitGoogleMock(&argc, argv);
148  return RUN_ALL_TESTS();
149}
150```
151
152As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this:
153
154```
155path/to/my_test.cc:119: Failure
156Actual function call count doesn't match this expectation:
157Actually: never called;
158Expected: called at least once.
159```
160
161**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation.
162
163**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap.
164
165**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions.
166
167This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier.
168
169Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks.
170
171## Using Google Mock with Any Testing Framework ##
172If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or
173[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to:
174```
175int main(int argc, char** argv) {
176  // The following line causes Google Mock to throw an exception on failure,
177  // which will be interpreted by your testing framework as a test failure.
178  ::testing::GTEST_FLAG(throw_on_failure) = true;
179  ::testing::InitGoogleMock(&argc, argv);
180  ... whatever your testing framework requires ...
181}
182```
183
184This approach has a catch: it makes Google Mock throw an exception
185from a mock object's destructor sometimes.  With some compilers, this
186sometimes causes the test program to crash.  You'll still be able to
187notice that the test has failed, but it's not a graceful failure.
188
189A better solution is to use Google Test's
190[event listener API](http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide#Extending_Google_Test_by_Handling_Test_Events)
191to report a test failure to your testing framework properly.  You'll need to
192implement the `OnTestPartResult()` method of the event listener interface, but it
193should be straightforward.
194
195If this turns out to be too much work, we suggest that you stick with
196Google Test, which works with Google Mock seamlessly (in fact, it is
197technically part of Google Mock.).  If there is a reason that you
198cannot use Google Test, please let us know.
199
200# Setting Expectations #
201The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right."
202
203## General Syntax ##
204In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
205
206```
207EXPECT_CALL(mock_object, method(matchers))
208    .Times(cardinality)
209    .WillOnce(action)
210    .WillRepeatedly(action);
211```
212
213The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.)
214
215The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections.
216
217This syntax is designed to make an expectation read like English. For example, you can probably guess that
218
219```
220using ::testing::Return;...
221EXPECT_CALL(turtle, GetX())
222    .Times(5)
223    .WillOnce(Return(100))
224    .WillOnce(Return(150))
225    .WillRepeatedly(Return(200));
226```
227
228says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL).
229
230**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier.
231
232## Matchers: What Arguments Do We Expect? ##
233When a mock function takes arguments, we must specify what arguments we are expecting; for example:
234
235```
236// Expects the turtle to move forward by 100 units.
237EXPECT_CALL(turtle, Forward(100));
238```
239
240Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
241
242```
243using ::testing::_;
244...
245// Expects the turtle to move forward.
246EXPECT_CALL(turtle, Forward(_));
247```
248
249`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected.
250
251A list of built-in matchers can be found in the [CheatSheet](V1_5_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
252
253```
254using ::testing::Ge;...
255EXPECT_CALL(turtle, Forward(Ge(100)));
256```
257
258This checks that the turtle will be told to go forward by at least 100 units.
259
260## Cardinalities: How Many Times Will It Be Called? ##
261The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly.
262
263An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called.
264
265We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_5_CheatSheet.md).
266
267The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember:
268
269  * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
270  * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`.
271  * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`.
272
273**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times?
274
275## Actions: What Should It Do? ##
276Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock.
277
278First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used.
279
280Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
281
282```
283using ::testing::Return;...
284EXPECT_CALL(turtle, GetX())
285    .WillOnce(Return(100))
286    .WillOnce(Return(200))
287    .WillOnce(Return(300));
288```
289
290This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
291
292```
293using ::testing::Return;...
294EXPECT_CALL(turtle, GetY())
295    .WillOnce(Return(100))
296    .WillOnce(Return(200))
297    .WillRepeatedly(Return(300));
298```
299
300says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on.
301
302Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).
303
304What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](V1_5_CheatSheet#Actions.md).
305
306**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
307
308```
309int n = 100;
310EXPECT_CALL(turtle, GetX())
311.Times(4)
312.WillOnce(Return(n++));
313```
314
315Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_5_CookBook.md).
316
317Time for another quiz! What do you think the following means?
318
319```
320using ::testing::Return;...
321EXPECT_CALL(turtle, GetY())
322.Times(4)
323.WillOnce(Return(100));
324```
325
326Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions.
327
328## Using Multiple Expectations ##
329So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects.
330
331By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:
332
333```
334using ::testing::_;...
335EXPECT_CALL(turtle, Forward(_));  // #1
336EXPECT_CALL(turtle, Forward(10))  // #2
337    .Times(2);
338```
339
340If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation.
341
342**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it.
343
344## Ordered vs Unordered Calls ##
345By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified.
346
347Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
348
349```
350using ::testing::InSequence;...
351TEST(FooTest, DrawsLineSegment) {
352  ...
353  {
354    InSequence dummy;
355
356    EXPECT_CALL(turtle, PenDown());
357    EXPECT_CALL(turtle, Forward(100));
358    EXPECT_CALL(turtle, PenUp());
359  }
360  Foo();
361}
362```
363
364By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant.
365
366In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error.
367
368(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_5_CookBook.md).)
369
370## All Expectations Are Sticky (Unless Said Otherwise) ##
371Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)?
372
373After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
374
375```
376using ::testing::_;...
377EXPECT_CALL(turtle, GoTo(_, _))  // #1
378    .Times(AnyNumber());
379EXPECT_CALL(turtle, GoTo(0, 0))  // #2
380    .Times(2);
381```
382
383Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above.
384
385This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.).
386
387Simple? Let's see if you've really understood it: what does the following code say?
388
389```
390using ::testing::Return;
391...
392for (int i = n; i > 0; i--) {
393  EXPECT_CALL(turtle, GetX())
394      .WillOnce(Return(10*i));
395}
396```
397
398If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful!
399
400One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
401
402```
403using ::testing::Return;
404...
405for (int i = n; i > 0; i--) {
406  EXPECT_CALL(turtle, GetX())
407    .WillOnce(Return(10*i))
408    .RetiresOnSaturation();
409}
410```
411
412And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:
413
414```
415using ::testing::InSequence;
416using ::testing::Return;
417...
418{
419  InSequence s;
420
421  for (int i = 1; i <= n; i++) {
422    EXPECT_CALL(turtle, GetX())
423        .WillOnce(Return(10*i))
424        .RetiresOnSaturation();
425  }
426}
427```
428
429By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call).
430
431## Uninteresting Calls ##
432A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called.
433
434In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure.
435
436# What Now? #
437Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.
438
439Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_5_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_5/FrequentlyAskedQuestions.md
r0r249096
1
2
3Please send your questions to the
4[googlemock](http://groups.google.com/group/googlemock) discussion
5group. If you need help with compiler errors, make sure you have
6tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.
7
8## I wrote some matchers.  After I upgraded to a new version of Google Mock, they no longer compile.  What's going on? ##
9
10After version 1.4.0 of Google Mock was released, we had an idea on how
11to make it easier to write matchers that can generate informative
12messages efficiently.  We experimented with this idea and liked what
13we saw.  Therefore we decided to implement it.
14
15Unfortunately, this means that if you have defined your own matchers
16by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
17your definitions will no longer compile.  Matchers defined using the
18`MATCHER*` family of macros are not affected.
19
20Sorry for the hassle if your matchers are affected.  We believe it's
21in everyone's long-term interest to make this change sooner than
22later.  Fortunately, it's usually not hard to migrate an existing
23matcher to the new API.  Here's what you need to do:
24
25If you wrote your matcher like this:
26```
27// Old matcher definition that doesn't work with the latest
28// Google Mock.
29using ::testing::MatcherInterface;
30...
31class MyWonderfulMatcher : public MatcherInterface<MyType> {
32 public:
33  ...
34  virtual bool Matches(MyType value) const {
35    // Returns true if value matches.
36    return value.GetFoo() > 5;
37  }
38  ...
39};
40```
41
42you'll need to change it to:
43```
44// New matcher definition that works with the latest Google Mock.
45using ::testing::MatcherInterface;
46using ::testing::MatchResultListener;
47...
48class MyWonderfulMatcher : public MatcherInterface<MyType> {
49 public:
50  ...
51  virtual bool MatchAndExplain(MyType value,
52                               MatchResultListener* listener) const {
53    // Returns true if value matches.
54    return value.GetFoo() > 5;
55  }
56  ...
57};
58```
59(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
60argument of type `MatchResultListener*`.)
61
62If you were also using `ExplainMatchResultTo()` to improve the matcher
63message:
64```
65// Old matcher definition that doesn't work with the lastest
66// Google Mock.
67using ::testing::MatcherInterface;
68...
69class MyWonderfulMatcher : public MatcherInterface<MyType> {
70 public:
71  ...
72  virtual bool Matches(MyType value) const {
73    // Returns true if value matches.
74    return value.GetFoo() > 5;
75  }
76
77  virtual void ExplainMatchResultTo(MyType value,
78                                    ::std::ostream* os) const {
79    // Prints some helpful information to os to help
80    // a user understand why value matches (or doesn't match).
81    *os << "the Foo property is " << value.GetFoo();
82  }
83  ...
84};
85```
86
87you should move the logic of `ExplainMatchResultTo()` into
88`MatchAndExplain()`, using the `MatchResultListener` argument where
89the `::std::ostream` was used:
90```
91// New matcher definition that works with the latest Google Mock.
92using ::testing::MatcherInterface;
93using ::testing::MatchResultListener;
94...
95class MyWonderfulMatcher : public MatcherInterface<MyType> {
96 public:
97  ...
98  virtual bool MatchAndExplain(MyType value,
99                               MatchResultListener* listener) const {
100    // Returns true if value matches.
101    *listener << "the Foo property is " << value.GetFoo();
102    return value.GetFoo() > 5;
103  }
104  ...
105};
106```
107
108If your matcher is defined using `MakePolymorphicMatcher()`:
109```
110// Old matcher definition that doesn't work with the latest
111// Google Mock.
112using ::testing::MakePolymorphicMatcher;
113...
114class MyGreatMatcher {
115 public:
116  ...
117  bool Matches(MyType value) const {
118    // Returns true if value matches.
119    return value.GetBar() < 42;
120  }
121  ...
122};
123... MakePolymorphicMatcher(MyGreatMatcher()) ...
124```
125
126you should rename the `Matches()` method to `MatchAndExplain()` and
127add a `MatchResultListener*` argument (the same as what you need to do
128for matchers defined by implementing `MatcherInterface`):
129```
130// New matcher definition that works with the latest Google Mock.
131using ::testing::MakePolymorphicMatcher;
132using ::testing::MatchResultListener;
133...
134class MyGreatMatcher {
135 public:
136  ...
137  bool MatchAndExplain(MyType value,
138                       MatchResultListener* listener) const {
139    // Returns true if value matches.
140    return value.GetBar() < 42;
141  }
142  ...
143};
144... MakePolymorphicMatcher(MyGreatMatcher()) ...
145```
146
147If your polymorphic matcher uses `ExplainMatchResultTo()` for better
148failure messages:
149```
150// Old matcher definition that doesn't work with the latest
151// Google Mock.
152using ::testing::MakePolymorphicMatcher;
153...
154class MyGreatMatcher {
155 public:
156  ...
157  bool Matches(MyType value) const {
158    // Returns true if value matches.
159    return value.GetBar() < 42;
160  }
161  ...
162};
163void ExplainMatchResultTo(const MyGreatMatcher& matcher,
164                          MyType value,
165                          ::std::ostream* os) {
166  // Prints some helpful information to os to help
167  // a user understand why value matches (or doesn't match).
168  *os << "the Bar property is " << value.GetBar();
169}
170... MakePolymorphicMatcher(MyGreatMatcher()) ...
171```
172
173you'll need to move the logic inside `ExplainMatchResultTo()` to
174`MatchAndExplain()`:
175```
176// New matcher definition that works with the latest Google Mock.
177using ::testing::MakePolymorphicMatcher;
178using ::testing::MatchResultListener;
179...
180class MyGreatMatcher {
181 public:
182  ...
183  bool MatchAndExplain(MyType value,
184                       MatchResultListener* listener) const {
185    // Returns true if value matches.
186    *listener << "the Bar property is " << value.GetBar();
187    return value.GetBar() < 42;
188  }
189  ...
190};
191... MakePolymorphicMatcher(MyGreatMatcher()) ...
192```
193
194For more information, you can read these
195[two](V1_5_CookBook#Writing_New_Monomorphic_Matchers.md)
196[recipes](V1_5_CookBook#Writing_New_Polymorphic_Matchers.md)
197from the cookbook.  As always, you
198are welcome to post questions on `googlemock@googlegroups.com` if you
199need any help.
200
201## When using Google Mock, do I have to use Google Test as the testing framework?  I have my favorite testing framework and don't want to switch. ##
202
203Google Mock works out of the box with Google Test.  However, it's easy
204to configure it to work with any testing framework of your choice.
205[Here](V1_5_ForDummies#Using_Google_Mock_with_Any_Testing_Framework.md) is how.
206
207## How am I supposed to make sense of these horrible template errors? ##
208
209If you are confused by the compiler errors gcc threw at you,
210try consulting the _Google Mock Doctor_ tool first.  What it does is to
211scan stdin for gcc error messages, and spit out diagnoses on the
212problems (we call them diseases) your code has.
213
214To "install", run command:
215```
216alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
217```
218
219To use it, do:
220```
221<your-favorite-build-command> <your-test> 2>&1 | gmd
222```
223
224For example:
225```
226make my_test 2>&1 | gmd
227```
228
229Or you can run `gmd` and copy-n-paste gcc's error messages to it.
230
231## Can I mock a variadic function? ##
232
233You cannot mock a variadic function (i.e. a function taking ellipsis
234(`...`) arguments) directly in Google Mock.
235
236The problem is that in general, there is _no way_ for a mock object to
237know how many arguments are passed to the variadic method, and what
238the arguments' types are.  Only the _author of the base class_ knows
239the protocol, and we cannot look into his head.
240
241Therefore, to mock such a function, the _user_ must teach the mock
242object how to figure out the number of arguments and their types.  One
243way to do it is to provide overloaded versions of the function.
244
245Ellipsis arguments are inherited from C and not really a C++ feature.
246They are unsafe to use and don't work with arguments that have
247constructors or destructors.  Therefore we recommend to avoid them in
248C++ as much as possible.
249
250## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter.  Why? ##
251
252If you compile this using Microsoft Visual C++ 2005 SP1:
253```
254class Foo {
255  ...
256  virtual void Bar(const int i) = 0;
257};
258
259class MockFoo : public Foo {
260  ...
261  MOCK_METHOD1(Bar, void(const int i));
262};
263```
264You may get the following warning:
265```
266warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
267```
268
269This is a MSVC bug.  The same code compiles fine with gcc ,for
270example.  If you use Visual C++ 2008 SP1, you would get the warning:
271```
272warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
273```
274
275In C++, if you _declare_ a function with a `const` parameter, the
276`const` modifier is _ignored_.  Therefore, the `Foo` base class above
277is equivalent to:
278```
279class Foo {
280  ...
281  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
282};
283```
284
285In fact, you can _declare_ Bar() with an `int` parameter, and _define_
286it with a `const int` parameter.  The compiler will still match them
287up.
288
289Since making a parameter `const` is meaningless in the method
290_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
291That should workaround the VC bug.
292
293Note that we are talking about the _top-level_ `const` modifier here.
294If the function parameter is passed by pointer or reference, declaring
295the _pointee_ or _referee_ as `const` is still meaningful.  For
296example, the following two declarations are _not_ equivalent:
297```
298void Bar(int* p);        // Neither p nor *p is const.
299void Bar(const int* p);  // p is not const, but *p is.
300```
301
302## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it.  What can I do? ##
303
304We've noticed that when the `/clr` compiler flag is used, Visual C++
305uses 5~6 times as much memory when compiling a mock class.  We suggest
306to avoid `/clr` when compiling native C++ mocks.
307
308## I can't figure out why Google Mock thinks my expectations are not satisfied.  What should I do? ##
309
310You might want to run your test with
311`--gmock_verbose=info`.  This flag lets Google Mock print a trace
312of every mock function call it receives.  By studying the trace,
313you'll gain insights on why the expectations you set are not met.
314
315## How can I assert that a function is NEVER called? ##
316
317```
318EXPECT_CALL(foo, Bar(_))
319    .Times(0);
320```
321
322## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied.  Isn't this redundant? ##
323
324When Google Mock detects a failure, it prints relevant information
325(the mock function arguments, the state of relevant expectations, and
326etc) to help the user debug.  If another failure is detected, Google
327Mock will do the same, including printing the state of relevant
328expectations.
329
330Sometimes an expectation's state didn't change between two failures,
331and you'll see the same description of the state twice.  They are
332however _not_ redundant, as they refer to _different points in time_.
333The fact they are the same _is_ interesting information.
334
335## I get a heap check failure when using a mock object, but using a real object is fine.  What can be wrong? ##
336
337Does the class (hopefully a pure interface) you are mocking have a
338virtual destructor?
339
340Whenever you derive from a base class, make sure its destructor is
341virtual.  Otherwise Bad Things will happen.  Consider the following
342code:
343
344```
345class Base {
346 public:
347  // Not virtual, but should be.
348  ~Base() { ... }
349  ...
350};
351
352class Derived : public Base {
353 public:
354  ...
355 private:
356  std::string value_;
357};
358
359...
360  Base* p = new Derived;
361  ...
362  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not
363             // - value_ is leaked.
364```
365
366By changing `~Base()` to virtual, `~Derived()` will be correctly
367called when `delete p` is executed, and the heap checker
368will be happy.
369
370## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##
371
372When people complain about this, often they are referring to code like:
373
374```
375// foo.Bar() should be called twice, return 1 the first time, and return
376// 2 the second time.  However, I have to write the expectations in the
377// reverse order.  This sucks big time!!!
378EXPECT_CALL(foo, Bar())
379    .WillOnce(Return(2))
380    .RetiresOnSaturation();
381EXPECT_CALL(foo, Bar())
382    .WillOnce(Return(1))
383    .RetiresOnSaturation();
384```
385
386The problem is that they didn't pick the **best** way to express the test's
387intent.
388
389By default, expectations don't have to be matched in _any_ particular
390order.  If you want them to match in a certain order, you need to be
391explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
392easy to accidentally over-specify your tests, and we want to make it
393harder to do so.
394
395There are two better ways to write the test spec.  You could either
396put the expectations in sequence:
397
398```
399// foo.Bar() should be called twice, return 1 the first time, and return
400// 2 the second time.  Using a sequence, we can write the expectations
401// in their natural order.
402{
403  InSequence s;
404  EXPECT_CALL(foo, Bar())
405      .WillOnce(Return(1))
406      .RetiresOnSaturation();
407  EXPECT_CALL(foo, Bar())
408      .WillOnce(Return(2))
409      .RetiresOnSaturation();
410}
411```
412
413or you can put the sequence of actions in the same expectation:
414
415```
416// foo.Bar() should be called twice, return 1 the first time, and return
417// 2 the second time.
418EXPECT_CALL(foo, Bar())
419    .WillOnce(Return(1))
420    .WillOnce(Return(2))
421    .RetiresOnSaturation();
422```
423
424Back to the original questions: why does Google Mock search the
425expectations (and `ON_CALL`s) from back to front?  Because this
426allows a user to set up a mock's behavior for the common case early
427(e.g. in the mock's constructor or the test fixture's set-up phase)
428and customize it with more specific rules later.  If Google Mock
429searches from front to back, this very useful pattern won't be
430possible.
431
432## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL.  Would it be reasonable not to show the warning in this case? ##
433
434When choosing between being neat and being safe, we lean toward the
435latter.  So the answer is that we think it's better to show the
436warning.
437
438Often people write `ON_CALL`s in the mock object's
439constructor or `SetUp()`, as the default behavior rarely changes from
440test to test.  Then in the test body they set the expectations, which
441are often different for each test.  Having an `ON_CALL` in the set-up
442part of a test doesn't mean that the calls are expected.  If there's
443no `EXPECT_CALL` and the method is called, it's possibly an error.  If
444we quietly let the call go through without notifying the user, bugs
445may creep in unnoticed.
446
447If, however, you are sure that the calls are OK, you can write
448
449```
450EXPECT_CALL(foo, Bar(_))
451    .WillRepeatedly(...);
452```
453
454instead of
455
456```
457ON_CALL(foo, Bar(_))
458    .WillByDefault(...);
459```
460
461This tells Google Mock that you do expect the calls and no warning should be
462printed.
463
464Also, you can control the verbosity using the `--gmock_verbose` flag.
465If you find the output too noisy when debugging, just choose a less
466verbose level.
467
468## How can I delete the mock function's argument in an action? ##
469
470If you find yourself needing to perform some action that's not
471supported by Google Mock directly, remember that you can define your own
472actions using
473[MakeAction()](V1_5_CookBook#Writing_New_Actions.md) or
474[MakePolymorphicAction()](V1_5_CookBook#Writing_New_Polymorphic_Actions.md),
475or you can write a stub function and invoke it using
476[Invoke()](V1_5_CookBook#Using_Functions_Methods_Functors.md).
477
478## MOCK\_METHODn()'s second argument looks funny.  Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##
479
480What?!  I think it's beautiful. :-)
481
482While which syntax looks more natural is a subjective matter to some
483extent, Google Mock's syntax was chosen for several practical advantages it
484has.
485
486Try to mock a function that takes a map as an argument:
487```
488virtual int GetSize(const map<int, std::string>& m);
489```
490
491Using the proposed syntax, it would be:
492```
493MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
494```
495
496Guess what?  You'll get a compiler error as the compiler thinks that
497`const map<int, std::string>& m` are **two**, not one, arguments. To work
498around this you can use `typedef` to give the map type a name, but
499that gets in the way of your work.  Google Mock's syntax avoids this
500problem as the function's argument types are protected inside a pair
501of parentheses:
502```
503// This compiles fine.
504MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
505```
506
507You still need a `typedef` if the return type contains an unprotected
508comma, but that's much rarer.
509
510Other advantages include:
511  1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
512  1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it.  The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively.  Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
513  1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features.  We'd as well stick to the same syntax in `MOCK_METHOD*`!
514
515## My code calls a static/global function.  Can I mock it? ##
516
517You can, but you need to make some changes.
518
519In general, if you find yourself needing to mock a static function,
520it's a sign that your modules are too tightly coupled (and less
521flexible, less reusable, less testable, etc).  You are probably better
522off defining a small interface and call the function through that
523interface, which then can be easily mocked.  It's a bit of work
524initially, but usually pays for itself quickly.
525
526This Google Testing Blog
527[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
528says it excellently.  Check it out.
529
530## My mock object needs to do complex stuff.  It's a lot of pain to specify the actions.  Google Mock sucks! ##
531
532I know it's not a question, but you get an answer for free any way. :-)
533
534With Google Mock, you can create mocks in C++ easily.  And people might be
535tempted to use them everywhere. Sometimes they work great, and
536sometimes you may find them, well, a pain to use. So, what's wrong in
537the latter case?
538
539When you write a test without using mocks, you exercise the code and
540assert that it returns the correct value or that the system is in an
541expected state.  This is sometimes called "state-based testing".
542
543Mocks are great for what some call "interaction-based" testing:
544instead of checking the system state at the very end, mock objects
545verify that they are invoked the right way and report an error as soon
546as it arises, giving you a handle on the precise context in which the
547error was triggered.  This is often more effective and economical to
548do than state-based testing.
549
550If you are doing state-based testing and using a test double just to
551simulate the real object, you are probably better off using a fake.
552Using a mock in this case causes pain, as it's not a strong point for
553mocks to perform complex actions.  If you experience this and think
554that mocks suck, you are just not using the right tool for your
555problem. Or, you might be trying to solve the wrong problem. :-)
556
557## I got a warning "Uninteresting function call encountered - default action taken.."  Should I panic? ##
558
559By all means, NO!  It's just an FYI.
560
561What it means is that you have a mock function, you haven't set any
562expectations on it (by Google Mock's rule this means that you are not
563interested in calls to this function and therefore it can be called
564any number of times), and it is called.  That's OK - you didn't say
565it's not OK to call the function!
566
567What if you actually meant to disallow this function to be called, but
568forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
569one can argue that it's the user's fault, Google Mock tries to be nice and
570prints you a note.
571
572So, when you see the message and believe that there shouldn't be any
573uninteresting calls, you should investigate what's going on.  To make
574your life easier, Google Mock prints the function name and arguments
575when an uninteresting call is encountered.
576
577## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##
578
579Either way is fine - you want to choose the one that's more convenient
580for your circumstance.
581
582Usually, if your action is for a particular function type, defining it
583using `Invoke()` should be easier; if your action can be used in
584functions of different types (e.g. if you are defining
585`Return(value)`), `MakePolymorphicAction()` is
586easiest.  Sometimes you want precise control on what types of
587functions the action can be used in, and implementing
588`ActionInterface` is the way to go here. See the implementation of
589`Return()` in `include/gmock/gmock-actions.h` for an example.
590
591## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified".  What does it mean? ##
592
593You got this error as Google Mock has no idea what value it should return
594when the mock method is called.  `SetArgumentPointee()` says what the
595side effect is, but doesn't say what the return value should be.  You
596need `DoAll()` to chain a `SetArgumentPointee()` with a `Return()`.
597
598See this [recipe](V1_5_CookBook#Mocking_Side_Effects.md) for more details and an example.
599
600
601## My question is not in your FAQ! ##
602
603If you cannot find the answer to your question in this FAQ, there are
604some other resources you can use:
605
606  1. read other [wiki pages](http://code.google.com/p/googlemock/w/list),
607  1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
608  1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).
609
610Please note that creating an issue in the
611[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_
612a good way to get your answer, as it is monitored infrequently by a
613very small number of people.
614
615When asking a question, it's helpful to provide as much of the
616following information as possible (people cannot help you if there's
617not enough information in your question):
618
619  * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
620  * your operating system,
621  * the name and version of your compiler,
622  * the complete command line flags you give to your compiler,
623  * the complete compiler error messages (if the question is about compilation),
624  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_6/CheatSheet.md
r0r249096
1
2
3# Defining a Mock Class #
4
5## Mocking a Normal Class ##
6
7Given
8```
9class Foo {
10  ...
11  virtual ~Foo();
12  virtual int GetSize() const = 0;
13  virtual string Describe(const char* name) = 0;
14  virtual string Describe(int type) = 0;
15  virtual bool Process(Bar elem, int count) = 0;
16};
17```
18(note that `~Foo()` **must** be virtual) we can define its mock as
19```
20#include "gmock/gmock.h"
21
22class MockFoo : public Foo {
23  MOCK_CONST_METHOD0(GetSize, int());
24  MOCK_METHOD1(Describe, string(const char* name));
25  MOCK_METHOD1(Describe, string(int type));
26  MOCK_METHOD2(Process, bool(Bar elem, int count));
27};
28```
29
30To create a "nice" mock object which ignores all uninteresting calls,
31or a "strict" mock object, which treats them as failures:
32```
33NiceMock<MockFoo> nice_foo;     // The type is a subclass of MockFoo.
34StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
35```
36
37## Mocking a Class Template ##
38
39To mock
40```
41template <typename Elem>
42class StackInterface {
43 public:
44  ...
45  virtual ~StackInterface();
46  virtual int GetSize() const = 0;
47  virtual void Push(const Elem& x) = 0;
48};
49```
50(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros:
51```
52template <typename Elem>
53class MockStack : public StackInterface<Elem> {
54 public:
55  ...
56  MOCK_CONST_METHOD0_T(GetSize, int());
57  MOCK_METHOD1_T(Push, void(const Elem& x));
58};
59```
60
61## Specifying Calling Conventions for Mock Functions ##
62
63If your mock function doesn't use the default calling convention, you
64can specify it by appending `_WITH_CALLTYPE` to any of the macros
65described in the previous two sections and supplying the calling
66convention as the first argument to the macro. For example,
67```
68  MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n));
69  MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y));
70```
71where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
72
73# Using Mocks in Tests #
74
75The typical flow is:
76  1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted.
77  1. Create the mock objects.
78  1. Optionally, set the default actions of the mock objects.
79  1. Set your expectations on the mock objects (How will they be called? What wil they do?).
80  1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions.
81  1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied.
82
83Here is an example:
84```
85using ::testing::Return;                            // #1
86
87TEST(BarTest, DoesThis) {
88  MockFoo foo;                                    // #2
89
90  ON_CALL(foo, GetSize())                         // #3
91      .WillByDefault(Return(1));
92  // ... other default actions ...
93
94  EXPECT_CALL(foo, Describe(5))                   // #4
95      .Times(3)
96      .WillRepeatedly(Return("Category 5"));
97  // ... other expectations ...
98
99  EXPECT_EQ("good", MyProductionFunction(&foo));  // #5
100}                                                 // #6
101```
102
103# Setting Default Actions #
104
105Google Mock has a **built-in default action** for any function that
106returns `void`, `bool`, a numeric value, or a pointer.
107
108To customize the default action for functions with return type `T` globally:
109```
110using ::testing::DefaultValue;
111
112DefaultValue<T>::Set(value);  // Sets the default value to be returned.
113// ... use the mocks ...
114DefaultValue<T>::Clear();     // Resets the default value.
115```
116
117To customize the default action for a particular method, use `ON_CALL()`:
118```
119ON_CALL(mock_object, method(matchers))
120    .With(multi_argument_matcher)  ?
121    .WillByDefault(action);
122```
123
124# Setting Expectations #
125
126`EXPECT_CALL()` sets **expectations** on a mock method (How will it be
127called? What will it do?):
128```
129EXPECT_CALL(mock_object, method(matchers))
130    .With(multi_argument_matcher)  ?
131    .Times(cardinality)            ?
132    .InSequence(sequences)         *
133    .After(expectations)           *
134    .WillOnce(action)              *
135    .WillRepeatedly(action)        ?
136    .RetiresOnSaturation();        ?
137```
138
139If `Times()` is omitted, the cardinality is assumed to be:
140
141  * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
142  * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or
143  * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0.
144
145A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time.
146
147# Matchers #
148
149A **matcher** matches a _single_ argument.  You can use it inside
150`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value
151directly:
152
153| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. |
154|:------------------------------|:----------------------------------------|
155| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. |
156
157Built-in matchers (where `argument` is the function argument) are
158divided into several categories:
159
160## Wildcard ##
161|`_`|`argument` can be any value of the correct type.|
162|:--|:-----------------------------------------------|
163|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`.     |
164
165## Generic Comparison ##
166
167|`Eq(value)` or `value`|`argument == value`|
168|:---------------------|:------------------|
169|`Ge(value)`           |`argument >= value`|
170|`Gt(value)`           |`argument > value` |
171|`Le(value)`           |`argument <= value`|
172|`Lt(value)`           |`argument < value` |
173|`Ne(value)`           |`argument != value`|
174|`IsNull()`            |`argument` is a `NULL` pointer (raw or smart).|
175|`NotNull()`           |`argument` is a non-null pointer (raw or smart).|
176|`Ref(variable)`       |`argument` is a reference to `variable`.|
177|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|
178
179Except `Ref()`, these matchers make a _copy_ of `value` in case it's
180modified or destructed later. If the compiler complains that `value`
181doesn't have a public copy constructor, try wrap it in `ByRef()`,
182e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure
183`non_copyable_value` is not changed afterwards, or the meaning of your
184matcher will be changed.
185
186## Floating-Point Matchers ##
187
188|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
189|:-------------------|:----------------------------------------------------------------------------------------------|
190|`FloatEq(a_float)`  |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal.  |
191|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal.  |
192|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal.    |
193
194These matchers use ULP-based comparison (the same as used in
195[Google Test](http://code.google.com/p/googletest/)). They
196automatically pick a reasonable error bound based on the absolute
197value of the expected value.  `DoubleEq()` and `FloatEq()` conform to
198the IEEE standard, which requires comparing two NaNs for equality to
199return false. The `NanSensitive*` version instead treats two NaNs as
200equal, which is often what a user wants.
201
202## String Matchers ##
203
204The `argument` can be either a C string or a C++ string object:
205
206|`ContainsRegex(string)`|`argument` matches the given regular expression.|
207|:----------------------|:-----------------------------------------------|
208|`EndsWith(suffix)`     |`argument` ends with string `suffix`.           |
209|`HasSubstr(string)`    |`argument` contains `string` as a sub-string.   |
210|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.|
211|`StartsWith(prefix)`   |`argument` starts with string `prefix`.         |
212|`StrCaseEq(string)`    |`argument` is equal to `string`, ignoring case. |
213|`StrCaseNe(string)`    |`argument` is not equal to `string`, ignoring case.|
214|`StrEq(string)`        |`argument` is equal to `string`.                |
215|`StrNe(string)`        |`argument` is not equal to `string`.            |
216
217`ContainsRegex()` and `MatchesRegex()` use the regular expression
218syntax defined
219[here](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Regular_Expression_Syntax).
220`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
221strings as well.
222
223## Container Matchers ##
224
225Most STL-style containers support `==`, so you can use
226`Eq(expected_container)` or simply `expected_container` to match a
227container exactly.   If you want to write the elements in-line,
228match them more flexibly, or get more informative messages, you can use:
229
230| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |
231|:--------------|:-------------------------------------------------------------------------------------------|
232| `Each(e)`     | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. |
233| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. |
234| `ElementsAreArray(array)` or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array. |
235| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
236| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. |
237
238These matchers can also match:
239
240  1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and
241  1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)).
242
243where the array may be multi-dimensional (i.e. its elements can be arrays).
244
245## Member Matchers ##
246
247|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
248|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------|
249|`Key(e)`                 |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
250|`Pair(m1, m2)`           |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.                                                |
251|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
252
253## Matching the Result of a Function or Functor ##
254
255|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
256|:---------------|:---------------------------------------------------------------------|
257
258## Pointer Matchers ##
259
260|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.|
261|:-----------|:-----------------------------------------------------------------------------------------------|
262
263## Multiargument Matchers ##
264
265Technically, all matchers match a _single_ value. A "multi-argument"
266matcher is just one that matches a _tuple_. The following matchers can
267be used to match a tuple `(x, y)`:
268
269|`Eq()`|`x == y`|
270|:-----|:-------|
271|`Ge()`|`x >= y`|
272|`Gt()`|`x > y` |
273|`Le()`|`x <= y`|
274|`Lt()`|`x < y` |
275|`Ne()`|`x != y`|
276
277You can use the following selectors to pick a subset of the arguments
278(or reorder them) to participate in the matching:
279
280|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.|
281|:-----------|:-------------------------------------------------------------------|
282|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.|
283
284## Composite Matchers ##
285
286You can make a matcher from one or more other matchers:
287
288|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.|
289|:-----------------------|:---------------------------------------------------|
290|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.|
291|`Not(m)`                |`argument` doesn't match matcher `m`.               |
292
293## Adapters for Matchers ##
294
295|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.|
296|:------------------|:--------------------------------------|
297|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. |
298|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.|
299
300## Matchers as Predicates ##
301
302|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.|
303|:------------------|:---------------------------------------------------------------------------------------------|
304|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`.       |
305|`Value(value, m)`  |evaluates to `true` if `value` matches `m`.                                                   |
306
307## Defining Matchers ##
308
309| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
310|:-------------------------------------------------|:------------------------------------------------------|
311| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
312| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
313
314**Notes:**
315
316  1. The `MATCHER*` macros cannot be used inside a function or class.
317  1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters).
318  1. You can use `PrintToString(x)` to convert a value `x` of any type to a string.
319
320## Matchers as Test Assertions ##
321
322|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/V1_6_Primer#Assertions) if the value of `expression` doesn't match matcher `m`.|
323|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------|
324|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.                                                               |
325
326# Actions #
327
328**Actions** specify what a mock function should do when invoked.
329
330## Returning a Value ##
331
332|`Return()`|Return from a `void` mock function.|
333|:---------|:----------------------------------|
334|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.|
335|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
336|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
337|`ReturnNull()`|Return a null pointer.             |
338|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
339|`ReturnRef(variable)`|Return a reference to `variable`.  |
340|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.|
341
342## Side Effects ##
343
344|`Assign(&variable, value)`|Assign `value` to variable.|
345|:-------------------------|:--------------------------|
346| `DeleteArg<N>()`         | Delete the `N`-th (0-based) argument, which must be a pointer. |
347| `SaveArg<N>(pointer)`    | Save the `N`-th (0-based) argument to `*pointer`. |
348| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
349| `SetArgReferee<N>(value)` |   Assign value to the variable referenced by the `N`-th (0-based) argument. |
350|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
351|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.|
352|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
353|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
354|`Throw(exception)`        |Throws the given exception, which can be any copyable value. Available since v1.1.0.|
355
356## Using a Function or a Functor as an Action ##
357
358|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
359|:----------|:-----------------------------------------------------------------------------------------------------------------|
360|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.                                  |
361|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.                       |
362|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.                                                        |
363|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|
364
365The return value of the invoked function is used as the return value
366of the action.
367
368When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
369```
370  double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
371  ...
372  EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
373```
374
375In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example,
376```
377  InvokeArgument<2>(5, string("Hi"), ByRef(foo))
378```
379calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference.
380
381## Default Action ##
382
383|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).|
384|:------------|:--------------------------------------------------------------------|
385
386**Note:** due to technical reasons, `DoDefault()` cannot be used inside  a composite action - trying to do so will result in a run-time error.
387
388## Composite Actions ##
389
390|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
391|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------|
392|`IgnoreResult(a)`       |Perform action `a` and ignore its result. `a` must not return void.                                                           |
393|`WithArg<N>(a)`         |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it.                                         |
394|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it.                                      |
395|`WithoutArgs(a)`        |Perform action `a` without any arguments.                                                                                     |
396
397## Defining Actions ##
398
399| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
400|:--------------------------------------|:---------------------------------------------------------------------------------------|
401| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
402| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`.   |
403
404The `ACTION*` macros cannot be used inside a function or class.
405
406# Cardinalities #
407
408These are used in `Times()` to specify how many times a mock function will be called:
409
410|`AnyNumber()`|The function can be called any number of times.|
411|:------------|:----------------------------------------------|
412|`AtLeast(n)` |The call is expected at least `n` times.       |
413|`AtMost(n)`  |The call is expected at most `n` times.        |
414|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.|
415|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.|
416
417# Expectation Order #
418
419By default, the expectations can be matched in _any_ order.  If some
420or all expectations must be matched in a given order, there are two
421ways to specify it.  They can be used either independently or
422together.
423
424## The After Clause ##
425
426```
427using ::testing::Expectation;
428...
429Expectation init_x = EXPECT_CALL(foo, InitX());
430Expectation init_y = EXPECT_CALL(foo, InitY());
431EXPECT_CALL(foo, Bar())
432    .After(init_x, init_y);
433```
434says that `Bar()` can be called only after both `InitX()` and
435`InitY()` have been called.
436
437If you don't know how many pre-requisites an expectation has when you
438write it, you can use an `ExpectationSet` to collect them:
439
440```
441using ::testing::ExpectationSet;
442...
443ExpectationSet all_inits;
444for (int i = 0; i < element_count; i++) {
445  all_inits += EXPECT_CALL(foo, InitElement(i));
446}
447EXPECT_CALL(foo, Bar())
448    .After(all_inits);
449```
450says that `Bar()` can be called only after all elements have been
451initialized (but we don't care about which elements get initialized
452before the others).
453
454Modifying an `ExpectationSet` after using it in an `.After()` doesn't
455affect the meaning of the `.After()`.
456
457## Sequences ##
458
459When you have a long chain of sequential expectations, it's easier to
460specify the order using **sequences**, which don't require you to given
461each expectation in the chain a different name.  <i>All expected<br>
462calls</i> in the same sequence must occur in the order they are
463specified.
464
465```
466using ::testing::Sequence;
467Sequence s1, s2;
468...
469EXPECT_CALL(foo, Reset())
470    .InSequence(s1, s2)
471    .WillOnce(Return(true));
472EXPECT_CALL(foo, GetSize())
473    .InSequence(s1)
474    .WillOnce(Return(1));
475EXPECT_CALL(foo, Describe(A<const char*>()))
476    .InSequence(s2)
477    .WillOnce(Return("dummy"));
478```
479says that `Reset()` must be called before _both_ `GetSize()` _and_
480`Describe()`, and the latter two can occur in any order.
481
482To put many expectations in a sequence conveniently:
483```
484using ::testing::InSequence;
485{
486  InSequence dummy;
487
488  EXPECT_CALL(...)...;
489  EXPECT_CALL(...)...;
490  ...
491  EXPECT_CALL(...)...;
492}
493```
494says that all expected calls in the scope of `dummy` must occur in
495strict order. The name `dummy` is irrelevant.)
496
497# Verifying and Resetting a Mock #
498
499Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier:
500```
501using ::testing::Mock;
502...
503// Verifies and removes the expectations on mock_obj;
504// returns true iff successful.
505Mock::VerifyAndClearExpectations(&mock_obj);
506...
507// Verifies and removes the expectations on mock_obj;
508// also removes the default actions set by ON_CALL();
509// returns true iff successful.
510Mock::VerifyAndClear(&mock_obj);
511```
512
513You can also tell Google Mock that a mock object can be leaked and doesn't
514need to be verified:
515```
516Mock::AllowLeak(&mock_obj);
517```
518
519# Mock Classes #
520
521Google Mock defines a convenient mock class template
522```
523class MockFunction<R(A1, ..., An)> {
524 public:
525  MOCK_METHODn(Call, R(A1, ..., An));
526};
527```
528See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Check_Points) for one application of it.
529
530# Flags #
531
532| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
533|:-------------------------------|:----------------------------------------------|
534| `--gmock_verbose=LEVEL`        | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_6/CookBook.md
r0r249096
1
2
3You can find recipes for using Google Mock here. If you haven't yet,
4please read the [ForDummies](V1_6_ForDummies.md) document first to make sure you understand
5the basics.
6
7**Note:** Google Mock lives in the `testing` name space. For
8readability, it is recommended to write `using ::testing::Foo;` once in
9your file before using the name `Foo` defined by Google Mock. We omit
10such `using` statements in this page for brevity, but you should do it
11in your own code.
12
13# Creating Mock Classes #
14
15## Mocking Private or Protected Methods ##
16
17You must always put a mock method definition (`MOCK_METHOD*`) in a
18`public:` section of the mock class, regardless of the method being
19mocked being `public`, `protected`, or `private` in the base class.
20This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function
21from outside of the mock class.  (Yes, C++ allows a subclass to change
22the access level of a virtual function in the base class.)  Example:
23
24```
25class Foo {
26 public:
27  ...
28  virtual bool Transform(Gadget* g) = 0;
29
30 protected:
31  virtual void Resume();
32
33 private:
34  virtual int GetTimeOut();
35};
36
37class MockFoo : public Foo {
38 public:
39  ...
40  MOCK_METHOD1(Transform, bool(Gadget* g));
41
42  // The following must be in the public section, even though the
43  // methods are protected or private in the base class.
44  MOCK_METHOD0(Resume, void());
45  MOCK_METHOD0(GetTimeOut, int());
46};
47```
48
49## Mocking Overloaded Methods ##
50
51You can mock overloaded functions as usual. No special attention is required:
52
53```
54class Foo {
55  ...
56
57  // Must be virtual as we'll inherit from Foo.
58  virtual ~Foo();
59
60  // Overloaded on the types and/or numbers of arguments.
61  virtual int Add(Element x);
62  virtual int Add(int times, Element x);
63
64  // Overloaded on the const-ness of this object.
65  virtual Bar& GetBar();
66  virtual const Bar& GetBar() const;
67};
68
69class MockFoo : public Foo {
70  ...
71  MOCK_METHOD1(Add, int(Element x));
72  MOCK_METHOD2(Add, int(int times, Element x);
73
74  MOCK_METHOD0(GetBar, Bar&());
75  MOCK_CONST_METHOD0(GetBar, const Bar&());
76};
77```
78
79**Note:** if you don't mock all versions of the overloaded method, the
80compiler will give you a warning about some methods in the base class
81being hidden. To fix that, use `using` to bring them in scope:
82
83```
84class MockFoo : public Foo {
85  ...
86  using Foo::Add;
87  MOCK_METHOD1(Add, int(Element x));
88  // We don't want to mock int Add(int times, Element x);
89  ...
90};
91```
92
93## Mocking Class Templates ##
94
95To mock a class template, append `_T` to the `MOCK_*` macros:
96
97```
98template <typename Elem>
99class StackInterface {
100  ...
101  // Must be virtual as we'll inherit from StackInterface.
102  virtual ~StackInterface();
103
104  virtual int GetSize() const = 0;
105  virtual void Push(const Elem& x) = 0;
106};
107
108template <typename Elem>
109class MockStack : public StackInterface<Elem> {
110  ...
111  MOCK_CONST_METHOD0_T(GetSize, int());
112  MOCK_METHOD1_T(Push, void(const Elem& x));
113};
114```
115
116## Mocking Nonvirtual Methods ##
117
118Google Mock can mock non-virtual functions to be used in what we call _hi-perf
119dependency injection_.
120
121In this case, instead of sharing a common base class with the real
122class, your mock class will be _unrelated_ to the real class, but
123contain methods with the same signatures.  The syntax for mocking
124non-virtual methods is the _same_ as mocking virtual methods:
125
126```
127// A simple packet stream class.  None of its members is virtual.
128class ConcretePacketStream {
129 public:
130  void AppendPacket(Packet* new_packet);
131  const Packet* GetPacket(size_t packet_number) const;
132  size_t NumberOfPackets() const;
133  ...
134};
135
136// A mock packet stream class.  It inherits from no other, but defines
137// GetPacket() and NumberOfPackets().
138class MockPacketStream {
139 public:
140  MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
141  MOCK_CONST_METHOD0(NumberOfPackets, size_t());
142  ...
143};
144```
145
146Note that the mock class doesn't define `AppendPacket()`, unlike the
147real class. That's fine as long as the test doesn't need to call it.
148
149Next, you need a way to say that you want to use
150`ConcretePacketStream` in production code, and use `MockPacketStream`
151in tests.  Since the functions are not virtual and the two classes are
152unrelated, you must specify your choice at _compile time_ (as opposed
153to run time).
154
155One way to do it is to templatize your code that needs to use a packet
156stream.  More specifically, you will give your code a template type
157argument for the type of the packet stream.  In production, you will
158instantiate your template with `ConcretePacketStream` as the type
159argument.  In tests, you will instantiate the same template with
160`MockPacketStream`.  For example, you may write:
161
162```
163template <class PacketStream>
164void CreateConnection(PacketStream* stream) { ... }
165
166template <class PacketStream>
167class PacketReader {
168 public:
169  void ReadPackets(PacketStream* stream, size_t packet_num);
170};
171```
172
173Then you can use `CreateConnection<ConcretePacketStream>()` and
174`PacketReader<ConcretePacketStream>` in production code, and use
175`CreateConnection<MockPacketStream>()` and
176`PacketReader<MockPacketStream>` in tests.
177
178```
179  MockPacketStream mock_stream;
180  EXPECT_CALL(mock_stream, ...)...;
181  .. set more expectations on mock_stream ...
182  PacketReader<MockPacketStream> reader(&mock_stream);
183  ... exercise reader ...
184```
185
186## Mocking Free Functions ##
187
188It's possible to use Google Mock to mock a free function (i.e. a
189C-style function or a static method).  You just need to rewrite your
190code to use an interface (abstract class).
191
192Instead of calling a free function (say, `OpenFile`) directly,
193introduce an interface for it and have a concrete subclass that calls
194the free function:
195
196```
197class FileInterface {
198 public:
199  ...
200  virtual bool Open(const char* path, const char* mode) = 0;
201};
202
203class File : public FileInterface {
204 public:
205  ...
206  virtual bool Open(const char* path, const char* mode) {
207    return OpenFile(path, mode);
208  }
209};
210```
211
212Your code should talk to `FileInterface` to open a file.  Now it's
213easy to mock out the function.
214
215This may seem much hassle, but in practice you often have multiple
216related functions that you can put in the same interface, so the
217per-function syntactic overhead will be much lower.
218
219If you are concerned about the performance overhead incurred by
220virtual functions, and profiling confirms your concern, you can
221combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md).
222
223## Nice Mocks and Strict Mocks ##
224
225If a mock method has no `EXPECT_CALL` spec but is called, Google Mock
226will print a warning about the "uninteresting call". The rationale is:
227
228  * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called.
229  * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning.
230
231However, sometimes you may want to suppress all "uninteresting call"
232warnings, while sometimes you may want the opposite, i.e. to treat all
233of them as errors. Google Mock lets you make the decision on a
234per-mock-object basis.
235
236Suppose your test uses a mock class `MockFoo`:
237
238```
239TEST(...) {
240  MockFoo mock_foo;
241  EXPECT_CALL(mock_foo, DoThis());
242  ... code that uses mock_foo ...
243}
244```
245
246If a method of `mock_foo` other than `DoThis()` is called, it will be
247reported by Google Mock as a warning. However, if you rewrite your
248test to use `NiceMock<MockFoo>` instead, the warning will be gone,
249resulting in a cleaner test output:
250
251```
252using ::testing::NiceMock;
253
254TEST(...) {
255  NiceMock<MockFoo> mock_foo;
256  EXPECT_CALL(mock_foo, DoThis());
257  ... code that uses mock_foo ...
258}
259```
260
261`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used
262wherever `MockFoo` is accepted.
263
264It also works if `MockFoo`'s constructor takes some arguments, as
265`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:
266
267```
268using ::testing::NiceMock;
269
270TEST(...) {
271  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
272  EXPECT_CALL(mock_foo, DoThis());
273  ... code that uses mock_foo ...
274}
275```
276
277The usage of `StrictMock` is similar, except that it makes all
278uninteresting calls failures:
279
280```
281using ::testing::StrictMock;
282
283TEST(...) {
284  StrictMock<MockFoo> mock_foo;
285  EXPECT_CALL(mock_foo, DoThis());
286  ... code that uses mock_foo ...
287
288  // The test will fail if a method of mock_foo other than DoThis()
289  // is called.
290}
291```
292
293There are some caveats though (I don't like them just as much as the
294next guy, but sadly they are side effects of C++'s limitations):
295
296  1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported.
297  1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
298  1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict.  This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual.  In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class.  This rule is required for safety.  Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.)
299
300Finally, you should be **very cautious** when using this feature, as the
301decision you make applies to **all** future changes to the mock
302class. If an important change is made in the interface you are mocking
303(and thus in the mock class), it could break your tests (if you use
304`StrictMock`) or let bugs pass through without a warning (if you use
305`NiceMock`). Therefore, try to specify the mock's behavior using
306explicit `EXPECT_CALL` first, and only turn to `NiceMock` or
307`StrictMock` as the last resort.
308
309## Simplifying the Interface without Breaking Existing Code ##
310
311Sometimes a method has a long list of arguments that is mostly
312uninteresting. For example,
313
314```
315class LogSink {
316 public:
317  ...
318  virtual void send(LogSeverity severity, const char* full_filename,
319                    const char* base_filename, int line,
320                    const struct tm* tm_time,
321                    const char* message, size_t message_len) = 0;
322};
323```
324
325This method's argument list is lengthy and hard to work with (let's
326say that the `message` argument is not even 0-terminated). If we mock
327it as is, using the mock will be awkward. If, however, we try to
328simplify this interface, we'll need to fix all clients depending on
329it, which is often infeasible.
330
331The trick is to re-dispatch the method in the mock class:
332
333```
334class ScopedMockLog : public LogSink {
335 public:
336  ...
337  virtual void send(LogSeverity severity, const char* full_filename,
338                    const char* base_filename, int line, const tm* tm_time,
339                    const char* message, size_t message_len) {
340    // We are only interested in the log severity, full file name, and
341    // log message.
342    Log(severity, full_filename, std::string(message, message_len));
343  }
344
345  // Implements the mock method:
346  //
347  //   void Log(LogSeverity severity,
348  //            const string& file_path,
349  //            const string& message);
350  MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
351                         const string& message));
352};
353```
354
355By defining a new mock method with a trimmed argument list, we make
356the mock class much more user-friendly.
357
358## Alternative to Mocking Concrete Classes ##
359
360Often you may find yourself using classes that don't implement
361interfaces. In order to test your code that uses such a class (let's
362call it `Concrete`), you may be tempted to make the methods of
363`Concrete` virtual and then mock it.
364
365Try not to do that.
366
367Making a non-virtual function virtual is a big decision. It creates an
368extension point where subclasses can tweak your class' behavior. This
369weakens your control on the class because now it's harder to maintain
370the class' invariants. You should make a function virtual only when
371there is a valid reason for a subclass to override it.
372
373Mocking concrete classes directly is problematic as it creates a tight
374coupling between the class and the tests - any small change in the
375class may invalidate your tests and make test maintenance a pain.
376
377To avoid such problems, many programmers have been practicing "coding
378to interfaces": instead of talking to the `Concrete` class, your code
379would define an interface and talk to it. Then you implement that
380interface as an adaptor on top of `Concrete`. In tests, you can easily
381mock that interface to observe how your code is doing.
382
383This technique incurs some overhead:
384
385  * You pay the cost of virtual function calls (usually not a problem).
386  * There is more abstraction for the programmers to learn.
387
388However, it can also bring significant benefits in addition to better
389testability:
390
391  * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive.
392  * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change.
393
394Some people worry that if everyone is practicing this technique, they
395will end up writing lots of redundant code. This concern is totally
396understandable. However, there are two reasons why it may not be the
397case:
398
399  * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code.
400  * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it.
401
402You need to weigh the pros and cons carefully for your particular
403problem, but I'd like to assure you that the Java community has been
404practicing this for a long time and it's a proven effective technique
405applicable in a wide variety of situations. :-)
406
407## Delegating Calls to a Fake ##
408
409Some times you have a non-trivial fake implementation of an
410interface. For example:
411
412```
413class Foo {
414 public:
415  virtual ~Foo() {}
416  virtual char DoThis(int n) = 0;
417  virtual void DoThat(const char* s, int* p) = 0;
418};
419
420class FakeFoo : public Foo {
421 public:
422  virtual char DoThis(int n) {
423    return (n > 0) ? '+' :
424        (n < 0) ? '-' : '0';
425  }
426
427  virtual void DoThat(const char* s, int* p) {
428    *p = strlen(s);
429  }
430};
431```
432
433Now you want to mock this interface such that you can set expectations
434on it. However, you also want to use `FakeFoo` for the default
435behavior, as duplicating it in the mock object is, well, a lot of
436work.
437
438When you define the mock class using Google Mock, you can have it
439delegate its default action to a fake class you already have, using
440this pattern:
441
442```
443using ::testing::_;
444using ::testing::Invoke;
445
446class MockFoo : public Foo {
447 public:
448  // Normal mock method definitions using Google Mock.
449  MOCK_METHOD1(DoThis, char(int n));
450  MOCK_METHOD2(DoThat, void(const char* s, int* p));
451
452  // Delegates the default actions of the methods to a FakeFoo object.
453  // This must be called *before* the custom ON_CALL() statements.
454  void DelegateToFake() {
455    ON_CALL(*this, DoThis(_))
456        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
457    ON_CALL(*this, DoThat(_, _))
458        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
459  }
460 private:
461  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
462};
463```
464
465With that, you can use `MockFoo` in your tests as usual. Just remember
466that if you don't explicitly set an action in an `ON_CALL()` or
467`EXPECT_CALL()`, the fake will be called upon to do it:
468
469```
470using ::testing::_;
471
472TEST(AbcTest, Xyz) {
473  MockFoo foo;
474  foo.DelegateToFake(); // Enables the fake for delegation.
475
476  // Put your ON_CALL(foo, ...)s here, if any.
477
478  // No action specified, meaning to use the default action.
479  EXPECT_CALL(foo, DoThis(5));
480  EXPECT_CALL(foo, DoThat(_, _));
481
482  int n = 0;
483  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
484  foo.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
485  EXPECT_EQ(2, n);
486}
487```
488
489**Some tips:**
490
491  * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
492  * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use.
493  * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type.
494  * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code.
495
496Regarding the tip on mixing a mock and a fake, here's an example on
497why it may be a bad sign: Suppose you have a class `System` for
498low-level system operations. In particular, it does file and I/O
499operations. And suppose you want to test how your code uses `System`
500to do I/O, and you just want the file operations to work normally. If
501you mock out the entire `System` class, you'll have to provide a fake
502implementation for the file operation part, which suggests that
503`System` is taking on too many roles.
504
505Instead, you can define a `FileOps` interface and an `IOOps` interface
506and split `System`'s functionalities into the two. Then you can mock
507`IOOps` without mocking `FileOps`.
508
509## Delegating Calls to a Real Object ##
510
511When using testing doubles (mocks, fakes, stubs, and etc), sometimes
512their behaviors will differ from those of the real objects. This
513difference could be either intentional (as in simulating an error such
514that you can test the error handling code) or unintentional. If your
515mocks have different behaviors than the real objects by mistake, you
516could end up with code that passes the tests but fails in production.
517
518You can use the _delegating-to-real_ technique to ensure that your
519mock has the same behavior as the real object while retaining the
520ability to validate calls. This technique is very similar to the
521delegating-to-fake technique, the difference being that we use a real
522object instead of a fake. Here's an example:
523
524```
525using ::testing::_;
526using ::testing::AtLeast;
527using ::testing::Invoke;
528
529class MockFoo : public Foo {
530 public:
531  MockFoo() {
532    // By default, all calls are delegated to the real object.
533    ON_CALL(*this, DoThis())
534        .WillByDefault(Invoke(&real_, &Foo::DoThis));
535    ON_CALL(*this, DoThat(_))
536        .WillByDefault(Invoke(&real_, &Foo::DoThat));
537    ...
538  }
539  MOCK_METHOD0(DoThis, ...);
540  MOCK_METHOD1(DoThat, ...);
541  ...
542 private:
543  Foo real_;
544};
545...
546
547  MockFoo mock;
548
549  EXPECT_CALL(mock, DoThis())
550      .Times(3);
551  EXPECT_CALL(mock, DoThat("Hi"))
552      .Times(AtLeast(1));
553  ... use mock in test ...
554```
555
556With this, Google Mock will verify that your code made the right calls
557(with the right arguments, in the right order, called the right number
558of times, etc), and a real object will answer the calls (so the
559behavior will be the same as in production). This gives you the best
560of both worlds.
561
562## Delegating Calls to a Parent Class ##
563
564Ideally, you should code to interfaces, whose methods are all pure
565virtual. In reality, sometimes you do need to mock a virtual method
566that is not pure (i.e, it already has an implementation). For example:
567
568```
569class Foo {
570 public:
571  virtual ~Foo();
572
573  virtual void Pure(int n) = 0;
574  virtual int Concrete(const char* str) { ... }
575};
576
577class MockFoo : public Foo {
578 public:
579  // Mocking a pure method.
580  MOCK_METHOD1(Pure, void(int n));
581  // Mocking a concrete method.  Foo::Concrete() is shadowed.
582  MOCK_METHOD1(Concrete, int(const char* str));
583};
584```
585
586Sometimes you may want to call `Foo::Concrete()` instead of
587`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub
588action, or perhaps your test doesn't need to mock `Concrete()` at all
589(but it would be oh-so painful to have to define a new mock class
590whenever you don't need to mock one of its methods).
591
592The trick is to leave a back door in your mock class for accessing the
593real methods in the base class:
594
595```
596class MockFoo : public Foo {
597 public:
598  // Mocking a pure method.
599  MOCK_METHOD1(Pure, void(int n));
600  // Mocking a concrete method.  Foo::Concrete() is shadowed.
601  MOCK_METHOD1(Concrete, int(const char* str));
602
603  // Use this to call Concrete() defined in Foo.
604  int FooConcrete(const char* str) { return Foo::Concrete(str); }
605};
606```
607
608Now, you can call `Foo::Concrete()` inside an action by:
609
610```
611using ::testing::_;
612using ::testing::Invoke;
613...
614  EXPECT_CALL(foo, Concrete(_))
615      .WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
616```
617
618or tell the mock object that you don't want to mock `Concrete()`:
619
620```
621using ::testing::Invoke;
622...
623  ON_CALL(foo, Concrete(_))
624      .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
625```
626
627(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do
628that, `MockFoo::Concrete()` will be called (and cause an infinite
629recursion) since `Foo::Concrete()` is virtual. That's just how C++
630works.)
631
632# Using Matchers #
633
634## Matching Argument Values Exactly ##
635
636You can specify exactly which arguments a mock method is expecting:
637
638```
639using ::testing::Return;
640...
641  EXPECT_CALL(foo, DoThis(5))
642      .WillOnce(Return('a'));
643  EXPECT_CALL(foo, DoThat("Hello", bar));
644```
645
646## Using Simple Matchers ##
647
648You can use matchers to match arguments that have a certain property:
649
650```
651using ::testing::Ge;
652using ::testing::NotNull;
653using ::testing::Return;
654...
655  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
656      .WillOnce(Return('a'));
657  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
658  // The second argument must not be NULL.
659```
660
661A frequently used matcher is `_`, which matches anything:
662
663```
664using ::testing::_;
665using ::testing::NotNull;
666...
667  EXPECT_CALL(foo, DoThat(_, NotNull()));
668```
669
670## Combining Matchers ##
671
672You can build complex matchers from existing ones using `AllOf()`,
673`AnyOf()`, and `Not()`:
674
675```
676using ::testing::AllOf;
677using ::testing::Gt;
678using ::testing::HasSubstr;
679using ::testing::Ne;
680using ::testing::Not;
681...
682  // The argument must be > 5 and != 10.
683  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
684                                Ne(10))));
685
686  // The first argument must not contain sub-string "blah".
687  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
688                          NULL));
689```
690
691## Casting Matchers ##
692
693Google Mock matchers are statically typed, meaning that the compiler
694can catch your mistake if you use a matcher of the wrong type (for
695example, if you use `Eq(5)` to match a `string` argument). Good for
696you!
697
698Sometimes, however, you know what you're doing and want the compiler
699to give you some slack. One example is that you have a matcher for
700`long` and the argument you want to match is `int`. While the two
701types aren't exactly the same, there is nothing really wrong with
702using a `Matcher<long>` to match an `int` - after all, we can first
703convert the `int` argument to a `long` before giving it to the
704matcher.
705
706To support this need, Google Mock gives you the
707`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type
708`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the
709type `m` accepts):
710
711  1. Type `T` can be implicitly cast to type `U`;
712  1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and
713  1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value).
714
715The code won't compile if any of these conditions isn't met.
716
717Here's one example:
718
719```
720using ::testing::SafeMatcherCast;
721
722// A base class and a child class.
723class Base { ... };
724class Derived : public Base { ... };
725
726class MockFoo : public Foo {
727 public:
728  MOCK_METHOD1(DoThis, void(Derived* derived));
729};
730...
731
732  MockFoo foo;
733  // m is a Matcher<Base*> we got from somewhere.
734  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
735```
736
737If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar
738function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works
739as long as you can `static_cast` type `T` to type `U`.
740
741`MatcherCast` essentially lets you bypass C++'s type system
742(`static_cast` isn't always safe as it could throw away information,
743for example), so be careful not to misuse/abuse it.
744
745## Selecting Between Overloaded Functions ##
746
747If you expect an overloaded function to be called, the compiler may
748need some help on which overloaded version it is.
749
750To disambiguate functions overloaded on the const-ness of this object,
751use the `Const()` argument wrapper.
752
753```
754using ::testing::ReturnRef;
755
756class MockFoo : public Foo {
757  ...
758  MOCK_METHOD0(GetBar, Bar&());
759  MOCK_CONST_METHOD0(GetBar, const Bar&());
760};
761...
762
763  MockFoo foo;
764  Bar bar1, bar2;
765  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
766      .WillOnce(ReturnRef(bar1));
767  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
768      .WillOnce(ReturnRef(bar2));
769```
770
771(`Const()` is defined by Google Mock and returns a `const` reference
772to its argument.)
773
774To disambiguate overloaded functions with the same number of arguments
775but different argument types, you may need to specify the exact type
776of a matcher, either by wrapping your matcher in `Matcher<type>()`, or
777using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`,
778etc):
779
780```
781using ::testing::An;
782using ::testing::Lt;
783using ::testing::Matcher;
784using ::testing::TypedEq;
785
786class MockPrinter : public Printer {
787 public:
788  MOCK_METHOD1(Print, void(int n));
789  MOCK_METHOD1(Print, void(char c));
790};
791
792TEST(PrinterTest, Print) {
793  MockPrinter printer;
794
795  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
796  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
797  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);
798
799  printer.Print(3);
800  printer.Print(6);
801  printer.Print('a');
802}
803```
804
805## Performing Different Actions Based on the Arguments ##
806
807When a mock method is called, the _last_ matching expectation that's
808still active will be selected (think "newer overrides older"). So, you
809can make a method do different things depending on its argument values
810like this:
811
812```
813using ::testing::_;
814using ::testing::Lt;
815using ::testing::Return;
816...
817  // The default case.
818  EXPECT_CALL(foo, DoThis(_))
819      .WillRepeatedly(Return('b'));
820
821  // The more specific case.
822  EXPECT_CALL(foo, DoThis(Lt(5)))
823      .WillRepeatedly(Return('a'));
824```
825
826Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will
827be returned; otherwise `'b'` will be returned.
828
829## Matching Multiple Arguments as a Whole ##
830
831Sometimes it's not enough to match the arguments individually. For
832example, we may want to say that the first argument must be less than
833the second argument. The `With()` clause allows us to match
834all arguments of a mock function as a whole. For example,
835
836```
837using ::testing::_;
838using ::testing::Lt;
839using ::testing::Ne;
840...
841  EXPECT_CALL(foo, InRange(Ne(0), _))
842      .With(Lt());
843```
844
845says that the first argument of `InRange()` must not be 0, and must be
846less than the second argument.
847
848The expression inside `With()` must be a matcher of type
849`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the
850types of the function arguments.
851
852You can also write `AllArgs(m)` instead of `m` inside `.With()`. The
853two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable
854than `.With(Lt())`.
855
856You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments
857(as a tuple) against `m`. For example,
858
859```
860using ::testing::_;
861using ::testing::AllOf;
862using ::testing::Args;
863using ::testing::Lt;
864...
865  EXPECT_CALL(foo, Blah(_, _, _))
866      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
867```
868
869says that `Blah()` will be called with arguments `x`, `y`, and `z` where
870`x < y < z`.
871
872As a convenience and example, Google Mock provides some matchers for
8732-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_6_CheatSheet.md) for
874the complete list.
875
876Note that if you want to pass the arguments to a predicate of your own
877(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be
878written to take a `tr1::tuple` as its argument; Google Mock will pass the `n`
879selected arguments as _one_ single tuple to the predicate.
880
881## Using Matchers as Predicates ##
882
883Have you noticed that a matcher is just a fancy predicate that also
884knows how to describe itself? Many existing algorithms take predicates
885as arguments (e.g. those defined in STL's `<algorithm>` header), and
886it would be a shame if Google Mock matchers are not allowed to
887participate.
888
889Luckily, you can use a matcher where a unary predicate functor is
890expected by wrapping it inside the `Matches()` function. For example,
891
892```
893#include <algorithm>
894#include <vector>
895
896std::vector<int> v;
897...
898// How many elements in v are >= 10?
899const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
900```
901
902Since you can build complex matchers from simpler ones easily using
903Google Mock, this gives you a way to conveniently construct composite
904predicates (doing the same using STL's `<functional>` header is just
905painful). For example, here's a predicate that's satisfied by any
906number that is >= 0, <= 100, and != 50:
907
908```
909Matches(AllOf(Ge(0), Le(100), Ne(50)))
910```
911
912## Using Matchers in Google Test Assertions ##
913
914Since matchers are basically predicates that also know how to describe
915themselves, there is a way to take advantage of them in
916[Google Test](http://code.google.com/p/googletest/) assertions. It's
917called `ASSERT_THAT` and `EXPECT_THAT`:
918
919```
920  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
921  EXPECT_THAT(value, matcher);  // The non-fatal version.
922```
923
924For example, in a Google Test test you can write:
925
926```
927#include "gmock/gmock.h"
928
929using ::testing::AllOf;
930using ::testing::Ge;
931using ::testing::Le;
932using ::testing::MatchesRegex;
933using ::testing::StartsWith;
934...
935
936  EXPECT_THAT(Foo(), StartsWith("Hello"));
937  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
938  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
939```
940
941which (as you can probably guess) executes `Foo()`, `Bar()`, and
942`Baz()`, and verifies that:
943
944  * `Foo()` returns a string that starts with `"Hello"`.
945  * `Bar()` returns a string that matches regular expression `"Line \\d+"`.
946  * `Baz()` returns a number in the range [5, 10].
947
948The nice thing about these macros is that _they read like
949English_. They generate informative messages too. For example, if the
950first `EXPECT_THAT()` above fails, the message will be something like:
951
952```
953Value of: Foo()
954  Actual: "Hi, world!"
955Expected: starts with "Hello"
956```
957
958**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the
959[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds
960`assertThat()` to JUnit.
961
962## Using Predicates as Matchers ##
963
964Google Mock provides a built-in set of matchers. In case you find them
965lacking, you can use an arbitray unary predicate function or functor
966as a matcher - as long as the predicate accepts a value of the type
967you want. You do this by wrapping the predicate inside the `Truly()`
968function, for example:
969
970```
971using ::testing::Truly;
972
973int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
974...
975
976  // Bar() must be called with an even number.
977  EXPECT_CALL(foo, Bar(Truly(IsEven)));
978```
979
980Note that the predicate function / functor doesn't have to return
981`bool`. It works as long as the return value can be used as the
982condition in statement `if (condition) ...`.
983
984## Matching Arguments that Are Not Copyable ##
985
986When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves
987away a copy of `bar`. When `Foo()` is called later, Google Mock
988compares the argument to `Foo()` with the saved copy of `bar`. This
989way, you don't need to worry about `bar` being modified or destroyed
990after the `EXPECT_CALL()` is executed. The same is true when you use
991matchers like `Eq(bar)`, `Le(bar)`, and so on.
992
993But what if `bar` cannot be copied (i.e. has no copy constructor)? You
994could define your own matcher function and use it with `Truly()`, as
995the previous couple of recipes have shown. Or, you may be able to get
996away from it if you can guarantee that `bar` won't be changed after
997the `EXPECT_CALL()` is executed. Just tell Google Mock that it should
998save a reference to `bar`, instead of a copy of it. Here's how:
999
1000```
1001using ::testing::Eq;
1002using ::testing::ByRef;
1003using ::testing::Lt;
1004...
1005  // Expects that Foo()'s argument == bar.
1006  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
1007
1008  // Expects that Foo()'s argument < bar.
1009  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
1010```
1011
1012Remember: if you do this, don't change `bar` after the
1013`EXPECT_CALL()`, or the result is undefined.
1014
1015## Validating a Member of an Object ##
1016
1017Often a mock function takes a reference to object as an argument. When
1018matching the argument, you may not want to compare the entire object
1019against a fixed object, as that may be over-specification. Instead,
1020you may need to validate a certain member variable or the result of a
1021certain getter method of the object. You can do this with `Field()`
1022and `Property()`. More specifically,
1023
1024```
1025Field(&Foo::bar, m)
1026```
1027
1028is a matcher that matches a `Foo` object whose `bar` member variable
1029satisfies matcher `m`.
1030
1031```
1032Property(&Foo::baz, m)
1033```
1034
1035is a matcher that matches a `Foo` object whose `baz()` method returns
1036a value that satisfies matcher `m`.
1037
1038For example:
1039
1040> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
1041|:-----------------------------|:-----------------------------------|
1042> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
1043
1044Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no
1045argument and be declared as `const`.
1046
1047BTW, `Field()` and `Property()` can also match plain pointers to
1048objects. For instance,
1049
1050```
1051Field(&Foo::number, Ge(3))
1052```
1053
1054matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`,
1055the match will always fail regardless of the inner matcher.
1056
1057What if you want to validate more than one members at the same time?
1058Remember that there is `AllOf()`.
1059
1060## Validating the Value Pointed to by a Pointer Argument ##
1061
1062C++ functions often take pointers as arguments. You can use matchers
1063like `NULL`, `NotNull()`, and other comparison matchers to match a
1064pointer, but what if you want to make sure the value _pointed to_ by
1065the pointer, instead of the pointer itself, has a certain property?
1066Well, you can use the `Pointee(m)` matcher.
1067
1068`Pointee(m)` matches a pointer iff `m` matches the value the pointer
1069points to. For example:
1070
1071```
1072using ::testing::Ge;
1073using ::testing::Pointee;
1074...
1075  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
1076```
1077
1078expects `foo.Bar()` to be called with a pointer that points to a value
1079greater than or equal to 3.
1080
1081One nice thing about `Pointee()` is that it treats a `NULL` pointer as
1082a match failure, so you can write `Pointee(m)` instead of
1083
1084```
1085  AllOf(NotNull(), Pointee(m))
1086```
1087
1088without worrying that a `NULL` pointer will crash your test.
1089
1090Also, did we tell you that `Pointee()` works with both raw pointers
1091**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and
1092etc)?
1093
1094What if you have a pointer to pointer? You guessed it - you can use
1095nested `Pointee()` to probe deeper inside the value. For example,
1096`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer
1097that points to a number less than 3 (what a mouthful...).
1098
1099## Testing a Certain Property of an Object ##
1100
1101Sometimes you want to specify that an object argument has a certain
1102property, but there is no existing matcher that does this. If you want
1103good error messages, you should define a matcher. If you want to do it
1104quick and dirty, you could get away with writing an ordinary function.
1105
1106Let's say you have a mock function that takes an object of type `Foo`,
1107which has an `int bar()` method and an `int baz()` method, and you
1108want to constrain that the argument's `bar()` value plus its `baz()`
1109value is a given number. Here's how you can define a matcher to do it:
1110
1111```
1112using ::testing::MatcherInterface;
1113using ::testing::MatchResultListener;
1114
1115class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
1116 public:
1117  explicit BarPlusBazEqMatcher(int expected_sum)
1118      : expected_sum_(expected_sum) {}
1119
1120  virtual bool MatchAndExplain(const Foo& foo,
1121                               MatchResultListener* listener) const {
1122    return (foo.bar() + foo.baz()) == expected_sum_;
1123  }
1124
1125  virtual void DescribeTo(::std::ostream* os) const {
1126    *os << "bar() + baz() equals " << expected_sum_;
1127  }
1128
1129  virtual void DescribeNegationTo(::std::ostream* os) const {
1130    *os << "bar() + baz() does not equal " << expected_sum_;
1131  }
1132 private:
1133  const int expected_sum_;
1134};
1135
1136inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
1137  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
1138}
1139
1140...
1141
1142  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
1143```
1144
1145## Matching Containers ##
1146
1147Sometimes an STL container (e.g. list, vector, map, ...) is passed to
1148a mock function and you may want to validate it. Since most STL
1149containers support the `==` operator, you can write
1150`Eq(expected_container)` or simply `expected_container` to match a
1151container exactly.
1152
1153Sometimes, though, you may want to be more flexible (for example, the
1154first element must be an exact match, but the second element can be
1155any positive number, and so on). Also, containers used in tests often
1156have a small number of elements, and having to define the expected
1157container out-of-line is a bit of a hassle.
1158
1159You can use the `ElementsAre()` matcher in such cases:
1160
1161```
1162using ::testing::_;
1163using ::testing::ElementsAre;
1164using ::testing::Gt;
1165...
1166
1167  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
1168...
1169
1170  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
1171```
1172
1173The above matcher says that the container must have 4 elements, which
1174must be 1, greater than 0, anything, and 5 respectively.
1175
1176`ElementsAre()` is overloaded to take 0 to 10 arguments. If more are
1177needed, you can place them in a C-style array and use
1178`ElementsAreArray()` instead:
1179
1180```
1181using ::testing::ElementsAreArray;
1182...
1183
1184  // ElementsAreArray accepts an array of element values.
1185  const int expected_vector1[] = { 1, 5, 2, 4, ... };
1186  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));
1187
1188  // Or, an array of element matchers.
1189  Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
1190  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
1191```
1192
1193In case the array needs to be dynamically created (and therefore the
1194array size cannot be inferred by the compiler), you can give
1195`ElementsAreArray()` an additional argument to specify the array size:
1196
1197```
1198using ::testing::ElementsAreArray;
1199...
1200  int* const expected_vector3 = new int[count];
1201  ... fill expected_vector3 with values ...
1202  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
1203```
1204
1205**Tips:**
1206
1207  * `ElementAre*()` works with _any_ container that implements the STL iterator concept (i.e. it has a `const_iterator` type and supports `begin()/end()`) and supports `size()`, not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern.
1208  * You can use nested `ElementAre*()` to match nested (multi-dimensional) containers.
1209  * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`.
1210  * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`).
1211
1212## Sharing Matchers ##
1213
1214Under the hood, a Google Mock matcher object consists of a pointer to
1215a ref-counted implementation object. Copying matchers is allowed and
1216very efficient, as only the pointer is copied. When the last matcher
1217that references the implementation object dies, the implementation
1218object will be deleted.
1219
1220Therefore, if you have some complex matcher that you want to use again
1221and again, there is no need to build it everytime. Just assign it to a
1222matcher variable and use that variable repeatedly! For example,
1223
1224```
1225  Matcher<int> in_range = AllOf(Gt(5), Le(10));
1226  ... use in_range as a matcher in multiple EXPECT_CALLs ...
1227```
1228
1229# Setting Expectations #
1230
1231## Ignoring Uninteresting Calls ##
1232
1233If you are not interested in how a mock method is called, just don't
1234say anything about it. In this case, if the method is ever called,
1235Google Mock will perform its default action to allow the test program
1236to continue. If you are not happy with the default action taken by
1237Google Mock, you can override it using `DefaultValue<T>::Set()`
1238(described later in this document) or `ON_CALL()`.
1239
1240Please note that once you expressed interest in a particular mock
1241method (via `EXPECT_CALL()`), all invocations to it must match some
1242expectation. If this function is called but the arguments don't match
1243any `EXPECT_CALL()` statement, it will be an error.
1244
1245## Disallowing Unexpected Calls ##
1246
1247If a mock method shouldn't be called at all, explicitly say so:
1248
1249```
1250using ::testing::_;
1251...
1252  EXPECT_CALL(foo, Bar(_))
1253      .Times(0);
1254```
1255
1256If some calls to the method are allowed, but the rest are not, just
1257list all the expected calls:
1258
1259```
1260using ::testing::AnyNumber;
1261using ::testing::Gt;
1262...
1263  EXPECT_CALL(foo, Bar(5));
1264  EXPECT_CALL(foo, Bar(Gt(10)))
1265      .Times(AnyNumber());
1266```
1267
1268A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()`
1269statements will be an error.
1270
1271## Expecting Ordered Calls ##
1272
1273Although an `EXPECT_CALL()` statement defined earlier takes precedence
1274when Google Mock tries to match a function call with an expectation,
1275by default calls don't have to happen in the order `EXPECT_CALL()`
1276statements are written. For example, if the arguments match the
1277matchers in the third `EXPECT_CALL()`, but not those in the first two,
1278then the third expectation will be used.
1279
1280If you would rather have all calls occur in the order of the
1281expectations, put the `EXPECT_CALL()` statements in a block where you
1282define a variable of type `InSequence`:
1283
1284```
1285  using ::testing::_;
1286  using ::testing::InSequence;
1287
1288  {
1289    InSequence s;
1290
1291    EXPECT_CALL(foo, DoThis(5));
1292    EXPECT_CALL(bar, DoThat(_))
1293        .Times(2);
1294    EXPECT_CALL(foo, DoThis(6));
1295  }
1296```
1297
1298In this example, we expect a call to `foo.DoThis(5)`, followed by two
1299calls to `bar.DoThat()` where the argument can be anything, which are
1300in turn followed by a call to `foo.DoThis(6)`. If a call occurred
1301out-of-order, Google Mock will report an error.
1302
1303## Expecting Partially Ordered Calls ##
1304
1305Sometimes requiring everything to occur in a predetermined order can
1306lead to brittle tests. For example, we may care about `A` occurring
1307before both `B` and `C`, but aren't interested in the relative order
1308of `B` and `C`. In this case, the test should reflect our real intent,
1309instead of being overly constraining.
1310
1311Google Mock allows you to impose an arbitrary DAG (directed acyclic
1312graph) on the calls. One way to express the DAG is to use the
1313[After](http://code.google.com/p/googlemock/wiki/V1_6_CheatSheet#The_After_Clause) clause of `EXPECT_CALL`.
1314
1315Another way is via the `InSequence()` clause (not the same as the
1316`InSequence` class), which we borrowed from jMock 2. It's less
1317flexible than `After()`, but more convenient when you have long chains
1318of sequential calls, as it doesn't require you to come up with
1319different names for the expectations in the chains.  Here's how it
1320works:
1321
1322If we view `EXPECT_CALL()` statements as nodes in a graph, and add an
1323edge from node A to node B wherever A must occur before B, we can get
1324a DAG. We use the term "sequence" to mean a directed path in this
1325DAG. Now, if we decompose the DAG into sequences, we just need to know
1326which sequences each `EXPECT_CALL()` belongs to in order to be able to
1327reconstruct the orginal DAG.
1328
1329So, to specify the partial order on the expectations we need to do two
1330things: first to define some `Sequence` objects, and then for each
1331`EXPECT_CALL()` say which `Sequence` objects it is part
1332of. Expectations in the same sequence must occur in the order they are
1333written. For example,
1334
1335```
1336  using ::testing::Sequence;
1337
1338  Sequence s1, s2;
1339
1340  EXPECT_CALL(foo, A())
1341      .InSequence(s1, s2);
1342  EXPECT_CALL(bar, B())
1343      .InSequence(s1);
1344  EXPECT_CALL(bar, C())
1345      .InSequence(s2);
1346  EXPECT_CALL(foo, D())
1347      .InSequence(s2);
1348```
1349
1350specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A ->
1351C -> D`):
1352
1353```
1354       +---> B
1355       |
1356  A ---|
1357       |
1358       +---> C ---> D
1359```
1360
1361This means that A must occur before B and C, and C must occur before
1362D. There's no restriction about the order other than these.
1363
1364## Controlling When an Expectation Retires ##
1365
1366When a mock method is called, Google Mock only consider expectations
1367that are still active. An expectation is active when created, and
1368becomes inactive (aka _retires_) when a call that has to occur later
1369has occurred. For example, in
1370
1371```
1372  using ::testing::_;
1373  using ::testing::Sequence;
1374
1375  Sequence s1, s2;
1376
1377  EXPECT_CALL(log, Log(WARNING, _, "File too large."))     // #1
1378      .Times(AnyNumber())
1379      .InSequence(s1, s2);
1380  EXPECT_CALL(log, Log(WARNING, _, "Data set is empty."))  // #2
1381      .InSequence(s1);
1382  EXPECT_CALL(log, Log(WARNING, _, "User not found."))     // #3
1383      .InSequence(s2);
1384```
1385
1386as soon as either #2 or #3 is matched, #1 will retire. If a warning
1387`"File too large."` is logged after this, it will be an error.
1388
1389Note that an expectation doesn't retire automatically when it's
1390saturated. For example,
1391
1392```
1393using ::testing::_;
1394...
1395  EXPECT_CALL(log, Log(WARNING, _, _));                  // #1
1396  EXPECT_CALL(log, Log(WARNING, _, "File too large."));  // #2
1397```
1398
1399says that there will be exactly one warning with the message `"File
1400too large."`. If the second warning contains this message too, #2 will
1401match again and result in an upper-bound-violated error.
1402
1403If this is not what you want, you can ask an expectation to retire as
1404soon as it becomes saturated:
1405
1406```
1407using ::testing::_;
1408...
1409  EXPECT_CALL(log, Log(WARNING, _, _));                 // #1
1410  EXPECT_CALL(log, Log(WARNING, _, "File too large."))  // #2
1411      .RetiresOnSaturation();
1412```
1413
1414Here #2 can be used only once, so if you have two warnings with the
1415message `"File too large."`, the first will match #2 and the second
1416will match #1 - there will be no error.
1417
1418# Using Actions #
1419
1420## Returning References from Mock Methods ##
1421
1422If a mock function's return type is a reference, you need to use
1423`ReturnRef()` instead of `Return()` to return a result:
1424
1425```
1426using ::testing::ReturnRef;
1427
1428class MockFoo : public Foo {
1429 public:
1430  MOCK_METHOD0(GetBar, Bar&());
1431};
1432...
1433
1434  MockFoo foo;
1435  Bar bar;
1436  EXPECT_CALL(foo, GetBar())
1437      .WillOnce(ReturnRef(bar));
1438```
1439
1440## Returning Live Values from Mock Methods ##
1441
1442The `Return(x)` action saves a copy of `x` when the action is
1443_created_, and always returns the same value whenever it's
1444executed. Sometimes you may want to instead return the _live_ value of
1445`x` (i.e. its value at the time when the action is _executed_.).
1446
1447If the mock function's return type is a reference, you can do it using
1448`ReturnRef(x)`, as shown in the previous recipe ("Returning References
1449from Mock Methods"). However, Google Mock doesn't let you use
1450`ReturnRef()` in a mock function whose return type is not a reference,
1451as doing that usually indicates a user error. So, what shall you do?
1452
1453You may be tempted to try `ByRef()`:
1454
1455```
1456using testing::ByRef;
1457using testing::Return;
1458
1459class MockFoo : public Foo {
1460 public:
1461  MOCK_METHOD0(GetValue, int());
1462};
1463...
1464  int x = 0;
1465  MockFoo foo;
1466  EXPECT_CALL(foo, GetValue())
1467      .WillRepeatedly(Return(ByRef(x)));
1468  x = 42;
1469  EXPECT_EQ(42, foo.GetValue());
1470```
1471
1472Unfortunately, it doesn't work here. The above code will fail with error:
1473
1474```
1475Value of: foo.GetValue()
1476  Actual: 0
1477Expected: 42
1478```
1479
1480The reason is that `Return(value)` converts `value` to the actual
1481return type of the mock function at the time when the action is
1482_created_, not when it is _executed_. (This behavior was chosen for
1483the action to be safe when `value` is a proxy object that references
1484some temporary objects.) As a result, `ByRef(x)` is converted to an
1485`int` value (instead of a `const int&`) when the expectation is set,
1486and `Return(ByRef(x))` will always return 0.
1487
1488`ReturnPointee(pointer)` was provided to solve this problem
1489specifically. It returns the value pointed to by `pointer` at the time
1490the action is _executed_:
1491
1492```
1493using testing::ReturnPointee;
1494...
1495  int x = 0;
1496  MockFoo foo;
1497  EXPECT_CALL(foo, GetValue())
1498      .WillRepeatedly(ReturnPointee(&x));  // Note the & here.
1499  x = 42;
1500  EXPECT_EQ(42, foo.GetValue());  // This will succeed now.
1501```
1502
1503## Combining Actions ##
1504
1505Want to do more than one thing when a function is called? That's
1506fine. `DoAll()` allow you to do sequence of actions every time. Only
1507the return value of the last action in the sequence will be used.
1508
1509```
1510using ::testing::DoAll;
1511
1512class MockFoo : public Foo {
1513 public:
1514  MOCK_METHOD1(Bar, bool(int n));
1515};
1516...
1517
1518  EXPECT_CALL(foo, Bar(_))
1519      .WillOnce(DoAll(action_1,
1520                      action_2,
1521                      ...
1522                      action_n));
1523```
1524
1525## Mocking Side Effects ##
1526
1527Sometimes a method exhibits its effect not via returning a value but
1528via side effects. For example, it may change some global state or
1529modify an output argument. To mock side effects, in general you can
1530define your own action by implementing `::testing::ActionInterface`.
1531
1532If all you need to do is to change an output argument, the built-in
1533`SetArgPointee()` action is convenient:
1534
1535```
1536using ::testing::SetArgPointee;
1537
1538class MockMutator : public Mutator {
1539 public:
1540  MOCK_METHOD2(Mutate, void(bool mutate, int* value));
1541  ...
1542};
1543...
1544
1545  MockMutator mutator;
1546  EXPECT_CALL(mutator, Mutate(true, _))
1547      .WillOnce(SetArgPointee<1>(5));
1548```
1549
1550In this example, when `mutator.Mutate()` is called, we will assign 5
1551to the `int` variable pointed to by argument #1
1552(0-based).
1553
1554`SetArgPointee()` conveniently makes an internal copy of the
1555value you pass to it, removing the need to keep the value in scope and
1556alive. The implication however is that the value must have a copy
1557constructor and assignment operator.
1558
1559If the mock method also needs to return a value as well, you can chain
1560`SetArgPointee()` with `Return()` using `DoAll()`:
1561
1562```
1563using ::testing::_;
1564using ::testing::Return;
1565using ::testing::SetArgPointee;
1566
1567class MockMutator : public Mutator {
1568 public:
1569  ...
1570  MOCK_METHOD1(MutateInt, bool(int* value));
1571};
1572...
1573
1574  MockMutator mutator;
1575  EXPECT_CALL(mutator, MutateInt(_))
1576      .WillOnce(DoAll(SetArgPointee<0>(5),
1577                      Return(true)));
1578```
1579
1580If the output argument is an array, use the
1581`SetArrayArgument<N>(first, last)` action instead. It copies the
1582elements in source range `[first, last)` to the array pointed to by
1583the `N`-th (0-based) argument:
1584
1585```
1586using ::testing::NotNull;
1587using ::testing::SetArrayArgument;
1588
1589class MockArrayMutator : public ArrayMutator {
1590 public:
1591  MOCK_METHOD2(Mutate, void(int* values, int num_values));
1592  ...
1593};
1594...
1595
1596  MockArrayMutator mutator;
1597  int values[5] = { 1, 2, 3, 4, 5 };
1598  EXPECT_CALL(mutator, Mutate(NotNull(), 5))
1599      .WillOnce(SetArrayArgument<0>(values, values + 5));
1600```
1601
1602This also works when the argument is an output iterator:
1603
1604```
1605using ::testing::_;
1606using ::testing::SeArrayArgument;
1607
1608class MockRolodex : public Rolodex {
1609 public:
1610  MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
1611  ...
1612};
1613...
1614
1615  MockRolodex rolodex;
1616  vector<string> names;
1617  names.push_back("George");
1618  names.push_back("John");
1619  names.push_back("Thomas");
1620  EXPECT_CALL(rolodex, GetNames(_))
1621      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
1622```
1623
1624## Changing a Mock Object's Behavior Based on the State ##
1625
1626If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:
1627
1628```
1629using ::testing::InSequence;
1630using ::testing::Return;
1631
1632...
1633  {
1634    InSequence seq;
1635    EXPECT_CALL(my_mock, IsDirty())
1636        .WillRepeatedly(Return(true));
1637    EXPECT_CALL(my_mock, Flush());
1638    EXPECT_CALL(my_mock, IsDirty())
1639        .WillRepeatedly(Return(false));
1640  }
1641  my_mock.FlushIfDirty();
1642```
1643
1644This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards.
1645
1646If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
1647
1648```
1649using ::testing::_;
1650using ::testing::SaveArg;
1651using ::testing::Return;
1652
1653ACTION_P(ReturnPointee, p) { return *p; }
1654...
1655  int previous_value = 0;
1656  EXPECT_CALL(my_mock, GetPrevValue())
1657      .WillRepeatedly(ReturnPointee(&previous_value));
1658  EXPECT_CALL(my_mock, UpdateValue(_))
1659      .WillRepeatedly(SaveArg<0>(&previous_value));
1660  my_mock.DoSomethingToUpdateValue();
1661```
1662
1663Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call.
1664
1665## Setting the Default Value for a Return Type ##
1666
1667If a mock method's return type is a built-in C++ type or pointer, by
1668default it will return 0 when invoked. You only need to specify an
1669action if this default value doesn't work for you.
1670
1671Sometimes, you may want to change this default value, or you may want
1672to specify a default value for types Google Mock doesn't know
1673about. You can do this using the `::testing::DefaultValue` class
1674template:
1675
1676```
1677class MockFoo : public Foo {
1678 public:
1679  MOCK_METHOD0(CalculateBar, Bar());
1680};
1681...
1682
1683  Bar default_bar;
1684  // Sets the default return value for type Bar.
1685  DefaultValue<Bar>::Set(default_bar);
1686
1687  MockFoo foo;
1688
1689  // We don't need to specify an action here, as the default
1690  // return value works for us.
1691  EXPECT_CALL(foo, CalculateBar());
1692
1693  foo.CalculateBar();  // This should return default_bar.
1694
1695  // Unsets the default return value.
1696  DefaultValue<Bar>::Clear();
1697```
1698
1699Please note that changing the default value for a type can make you
1700tests hard to understand. We recommend you to use this feature
1701judiciously. For example, you may want to make sure the `Set()` and
1702`Clear()` calls are right next to the code that uses your mock.
1703
1704## Setting the Default Actions for a Mock Method ##
1705
1706You've learned how to change the default value of a given
1707type. However, this may be too coarse for your purpose: perhaps you
1708have two mock methods with the same return type and you want them to
1709have different behaviors. The `ON_CALL()` macro allows you to
1710customize your mock's behavior at the method level:
1711
1712```
1713using ::testing::_;
1714using ::testing::AnyNumber;
1715using ::testing::Gt;
1716using ::testing::Return;
1717...
1718  ON_CALL(foo, Sign(_))
1719      .WillByDefault(Return(-1));
1720  ON_CALL(foo, Sign(0))
1721      .WillByDefault(Return(0));
1722  ON_CALL(foo, Sign(Gt(0)))
1723      .WillByDefault(Return(1));
1724
1725  EXPECT_CALL(foo, Sign(_))
1726      .Times(AnyNumber());
1727
1728  foo.Sign(5);   // This should return 1.
1729  foo.Sign(-9);  // This should return -1.
1730  foo.Sign(0);   // This should return 0.
1731```
1732
1733As you may have guessed, when there are more than one `ON_CALL()`
1734statements, the news order take precedence over the older ones. In
1735other words, the **last** one that matches the function arguments will
1736be used. This matching order allows you to set up the common behavior
1737in a mock object's constructor or the test fixture's set-up phase and
1738specialize the mock's behavior later.
1739
1740## Using Functions/Methods/Functors as Actions ##
1741
1742If the built-in actions don't suit you, you can easily use an existing
1743function, method, or functor as an action:
1744
1745```
1746using ::testing::_;
1747using ::testing::Invoke;
1748
1749class MockFoo : public Foo {
1750 public:
1751  MOCK_METHOD2(Sum, int(int x, int y));
1752  MOCK_METHOD1(ComplexJob, bool(int x));
1753};
1754
1755int CalculateSum(int x, int y) { return x + y; }
1756
1757class Helper {
1758 public:
1759  bool ComplexJob(int x);
1760};
1761...
1762
1763  MockFoo foo;
1764  Helper helper;
1765  EXPECT_CALL(foo, Sum(_, _))
1766      .WillOnce(Invoke(CalculateSum));
1767  EXPECT_CALL(foo, ComplexJob(_))
1768      .WillOnce(Invoke(&helper, &Helper::ComplexJob));
1769
1770  foo.Sum(5, 6);       // Invokes CalculateSum(5, 6).
1771  foo.ComplexJob(10);  // Invokes helper.ComplexJob(10);
1772```
1773
1774The only requirement is that the type of the function, etc must be
1775_compatible_ with the signature of the mock function, meaning that the
1776latter's arguments can be implicitly converted to the corresponding
1777arguments of the former, and the former's return type can be
1778implicitly converted to that of the latter. So, you can invoke
1779something whose type is _not_ exactly the same as the mock function,
1780as long as it's safe to do so - nice, huh?
1781
1782## Invoking a Function/Method/Functor Without Arguments ##
1783
1784`Invoke()` is very useful for doing actions that are more complex. It
1785passes the mock function's arguments to the function or functor being
1786invoked such that the callee has the full context of the call to work
1787with. If the invoked function is not interested in some or all of the
1788arguments, it can simply ignore them.
1789
1790Yet, a common pattern is that a test author wants to invoke a function
1791without the arguments of the mock function. `Invoke()` allows her to
1792do that using a wrapper function that throws away the arguments before
1793invoking an underlining nullary function. Needless to say, this can be
1794tedious and obscures the intent of the test.
1795
1796`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except
1797that it doesn't pass the mock function's arguments to the
1798callee. Here's an example:
1799
1800```
1801using ::testing::_;
1802using ::testing::InvokeWithoutArgs;
1803
1804class MockFoo : public Foo {
1805 public:
1806  MOCK_METHOD1(ComplexJob, bool(int n));
1807};
1808
1809bool Job1() { ... }
1810...
1811
1812  MockFoo foo;
1813  EXPECT_CALL(foo, ComplexJob(_))
1814      .WillOnce(InvokeWithoutArgs(Job1));
1815
1816  foo.ComplexJob(10);  // Invokes Job1().
1817```
1818
1819## Invoking an Argument of the Mock Function ##
1820
1821Sometimes a mock function will receive a function pointer or a functor
1822(in other words, a "callable") as an argument, e.g.
1823
1824```
1825class MockFoo : public Foo {
1826 public:
1827  MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
1828};
1829```
1830
1831and you may want to invoke this callable argument:
1832
1833```
1834using ::testing::_;
1835...
1836  MockFoo foo;
1837  EXPECT_CALL(foo, DoThis(_, _))
1838      .WillOnce(...);
1839  // Will execute (*fp)(5), where fp is the
1840  // second argument DoThis() receives.
1841```
1842
1843Arghh, you need to refer to a mock function argument but C++ has no
1844lambda (yet), so you have to define your own action. :-( Or do you
1845really?
1846
1847Well, Google Mock has an action to solve _exactly_ this problem:
1848
1849```
1850  InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
1851```
1852
1853will invoke the `N`-th (0-based) argument the mock function receives,
1854with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is
1855a function pointer or a functor, Google Mock handles them both.
1856
1857With that, you could write:
1858
1859```
1860using ::testing::_;
1861using ::testing::InvokeArgument;
1862...
1863  EXPECT_CALL(foo, DoThis(_, _))
1864      .WillOnce(InvokeArgument<1>(5));
1865  // Will execute (*fp)(5), where fp is the
1866  // second argument DoThis() receives.
1867```
1868
1869What if the callable takes an argument by reference? No problem - just
1870wrap it inside `ByRef()`:
1871
1872```
1873...
1874  MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
1875...
1876using ::testing::_;
1877using ::testing::ByRef;
1878using ::testing::InvokeArgument;
1879...
1880
1881  MockFoo foo;
1882  Helper helper;
1883  ...
1884  EXPECT_CALL(foo, Bar(_))
1885      .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
1886  // ByRef(helper) guarantees that a reference to helper, not a copy of it,
1887  // will be passed to the callable.
1888```
1889
1890What if the callable takes an argument by reference and we do **not**
1891wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a
1892copy_ of the argument, and pass a _reference to the copy_, instead of
1893a reference to the original value, to the callable. This is especially
1894handy when the argument is a temporary value:
1895
1896```
1897...
1898  MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
1899...
1900using ::testing::_;
1901using ::testing::InvokeArgument;
1902...
1903
1904  MockFoo foo;
1905  ...
1906  EXPECT_CALL(foo, DoThat(_))
1907      .WillOnce(InvokeArgument<0>(5.0, string("Hi")));
1908  // Will execute (*f)(5.0, string("Hi")), where f is the function pointer
1909  // DoThat() receives.  Note that the values 5.0 and string("Hi") are
1910  // temporary and dead once the EXPECT_CALL() statement finishes.  Yet
1911  // it's fine to perform this action later, since a copy of the values
1912  // are kept inside the InvokeArgument action.
1913```
1914
1915## Ignoring an Action's Result ##
1916
1917Sometimes you have an action that returns _something_, but you need an
1918action that returns `void` (perhaps you want to use it in a mock
1919function that returns `void`, or perhaps it needs to be used in
1920`DoAll()` and it's not the last in the list). `IgnoreResult()` lets
1921you do that. For example:
1922
1923```
1924using ::testing::_;
1925using ::testing::Invoke;
1926using ::testing::Return;
1927
1928int Process(const MyData& data);
1929string DoSomething();
1930
1931class MockFoo : public Foo {
1932 public:
1933  MOCK_METHOD1(Abc, void(const MyData& data));
1934  MOCK_METHOD0(Xyz, bool());
1935};
1936...
1937
1938  MockFoo foo;
1939  EXPECT_CALL(foo, Abc(_))
1940  // .WillOnce(Invoke(Process));
1941  // The above line won't compile as Process() returns int but Abc() needs
1942  // to return void.
1943      .WillOnce(IgnoreResult(Invoke(Process)));
1944
1945  EXPECT_CALL(foo, Xyz())
1946      .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
1947      // Ignores the string DoSomething() returns.
1948                      Return(true)));
1949```
1950
1951Note that you **cannot** use `IgnoreResult()` on an action that already
1952returns `void`. Doing so will lead to ugly compiler errors.
1953
1954## Selecting an Action's Arguments ##
1955
1956Say you have a mock function `Foo()` that takes seven arguments, and
1957you have a custom action that you want to invoke when `Foo()` is
1958called. Trouble is, the custom action only wants three arguments:
1959
1960```
1961using ::testing::_;
1962using ::testing::Invoke;
1963...
1964  MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
1965                         const map<pair<int, int>, double>& weight,
1966                         double min_weight, double max_wight));
1967...
1968
1969bool IsVisibleInQuadrant1(bool visible, int x, int y) {
1970  return visible && x >= 0 && y >= 0;
1971}
1972...
1973
1974  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1975      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(
1976```
1977
1978To please the compiler God, you can to define an "adaptor" that has
1979the same signature as `Foo()` and calls the custom action with the
1980right arguments:
1981
1982```
1983using ::testing::_;
1984using ::testing::Invoke;
1985
1986bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
1987                            const map<pair<int, int>, double>& weight,
1988                            double min_weight, double max_wight) {
1989  return IsVisibleInQuadrant1(visible, x, y);
1990}
1991...
1992
1993  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1994      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.
1995```
1996
1997But isn't this awkward?
1998
1999Google Mock provides a generic _action adaptor_, so you can spend your
2000time minding more important business than writing your own
2001adaptors. Here's the syntax:
2002
2003```
2004  WithArgs<N1, N2, ..., Nk>(action)
2005```
2006
2007creates an action that passes the arguments of the mock function at
2008the given indices (0-based) to the inner `action` and performs
2009it. Using `WithArgs`, our original example can be written as:
2010
2011```
2012using ::testing::_;
2013using ::testing::Invoke;
2014using ::testing::WithArgs;
2015...
2016  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
2017      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
2018      // No need to define your own adaptor.
2019```
2020
2021For better readability, Google Mock also gives you:
2022
2023  * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and
2024  * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument.
2025
2026As you may have realized, `InvokeWithoutArgs(...)` is just syntactic
2027sugar for `WithoutArgs(Inovke(...))`.
2028
2029Here are more tips:
2030
2031  * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything.
2032  * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`.
2033  * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.
2034  * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work.
2035
2036## Ignoring Arguments in Action Functions ##
2037
2038The selecting-an-action's-arguments recipe showed us one way to make a
2039mock function and an action with incompatible argument lists fit
2040together. The downside is that wrapping the action in
2041`WithArgs<...>()` can get tedious for people writing the tests.
2042
2043If you are defining a function, method, or functor to be used with
2044`Invoke*()`, and you are not interested in some of its arguments, an
2045alternative to `WithArgs` is to declare the uninteresting arguments as
2046`Unused`. This makes the definition less cluttered and less fragile in
2047case the types of the uninteresting arguments change. It could also
2048increase the chance the action function can be reused. For example,
2049given
2050
2051```
2052  MOCK_METHOD3(Foo, double(const string& label, double x, double y));
2053  MOCK_METHOD3(Bar, double(int index, double x, double y));
2054```
2055
2056instead of
2057
2058```
2059using ::testing::_;
2060using ::testing::Invoke;
2061
2062double DistanceToOriginWithLabel(const string& label, double x, double y) {
2063  return sqrt(x*x + y*y);
2064}
2065
2066double DistanceToOriginWithIndex(int index, double x, double y) {
2067  return sqrt(x*x + y*y);
2068}
2069...
2070
2071  EXEPCT_CALL(mock, Foo("abc", _, _))
2072      .WillOnce(Invoke(DistanceToOriginWithLabel));
2073  EXEPCT_CALL(mock, Bar(5, _, _))
2074      .WillOnce(Invoke(DistanceToOriginWithIndex));
2075```
2076
2077you could write
2078
2079```
2080using ::testing::_;
2081using ::testing::Invoke;
2082using ::testing::Unused;
2083
2084double DistanceToOrigin(Unused, double x, double y) {
2085  return sqrt(x*x + y*y);
2086}
2087...
2088
2089  EXEPCT_CALL(mock, Foo("abc", _, _))
2090      .WillOnce(Invoke(DistanceToOrigin));
2091  EXEPCT_CALL(mock, Bar(5, _, _))
2092      .WillOnce(Invoke(DistanceToOrigin));
2093```
2094
2095## Sharing Actions ##
2096
2097Just like matchers, a Google Mock action object consists of a pointer
2098to a ref-counted implementation object. Therefore copying actions is
2099also allowed and very efficient. When the last action that references
2100the implementation object dies, the implementation object will be
2101deleted.
2102
2103If you have some complex action that you want to use again and again,
2104you may not have to build it from scratch everytime. If the action
2105doesn't have an internal state (i.e. if it always does the same thing
2106no matter how many times it has been called), you can assign it to an
2107action variable and use that variable repeatedly. For example:
2108
2109```
2110  Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5),
2111                                      Return(true));
2112  ... use set_flag in .WillOnce() and .WillRepeatedly() ...
2113```
2114
2115However, if the action has its own state, you may be surprised if you
2116share the action object. Suppose you have an action factory
2117`IncrementCounter(init)` which creates an action that increments and
2118returns a counter whose initial value is `init`, using two actions
2119created from the same expression and using a shared action will
2120exihibit different behaviors. Example:
2121
2122```
2123  EXPECT_CALL(foo, DoThis())
2124      .WillRepeatedly(IncrementCounter(0));
2125  EXPECT_CALL(foo, DoThat())
2126      .WillRepeatedly(IncrementCounter(0));
2127  foo.DoThis();  // Returns 1.
2128  foo.DoThis();  // Returns 2.
2129  foo.DoThat();  // Returns 1 - Blah() uses a different
2130                 // counter than Bar()'s.
2131```
2132
2133versus
2134
2135```
2136  Action<int()> increment = IncrementCounter(0);
2137
2138  EXPECT_CALL(foo, DoThis())
2139      .WillRepeatedly(increment);
2140  EXPECT_CALL(foo, DoThat())
2141      .WillRepeatedly(increment);
2142  foo.DoThis();  // Returns 1.
2143  foo.DoThis();  // Returns 2.
2144  foo.DoThat();  // Returns 3 - the counter is shared.
2145```
2146
2147# Misc Recipes on Using Google Mock #
2148
2149## Making the Compilation Faster ##
2150
2151Believe it or not, the _vast majority_ of the time spent on compiling
2152a mock class is in generating its constructor and destructor, as they
2153perform non-trivial tasks (e.g. verification of the
2154expectations). What's more, mock methods with different signatures
2155have different types and thus their constructors/destructors need to
2156be generated by the compiler separately. As a result, if you mock many
2157different types of methods, compiling your mock class can get really
2158slow.
2159
2160If you are experiencing slow compilation, you can move the definition
2161of your mock class' constructor and destructor out of the class body
2162and into a `.cpp` file. This way, even if you `#include` your mock
2163class in N files, the compiler only needs to generate its constructor
2164and destructor once, resulting in a much faster compilation.
2165
2166Let's illustrate the idea using an example. Here's the definition of a
2167mock class before applying this recipe:
2168
2169```
2170// File mock_foo.h.
2171...
2172class MockFoo : public Foo {
2173 public:
2174  // Since we don't declare the constructor or the destructor,
2175  // the compiler will generate them in every translation unit
2176  // where this mock class is used.
2177
2178  MOCK_METHOD0(DoThis, int());
2179  MOCK_METHOD1(DoThat, bool(const char* str));
2180  ... more mock methods ...
2181};
2182```
2183
2184After the change, it would look like:
2185
2186```
2187// File mock_foo.h.
2188...
2189class MockFoo : public Foo {
2190 public:
2191  // The constructor and destructor are declared, but not defined, here.
2192  MockFoo();
2193  virtual ~MockFoo();
2194
2195  MOCK_METHOD0(DoThis, int());
2196  MOCK_METHOD1(DoThat, bool(const char* str));
2197  ... more mock methods ...
2198};
2199```
2200and
2201```
2202// File mock_foo.cpp.
2203#include "path/to/mock_foo.h"
2204
2205// The definitions may appear trivial, but the functions actually do a
2206// lot of things through the constructors/destructors of the member
2207// variables used to implement the mock methods.
2208MockFoo::MockFoo() {}
2209MockFoo::~MockFoo() {}
2210```
2211
2212## Forcing a Verification ##
2213
2214When it's being destoyed, your friendly mock object will automatically
2215verify that all expectations on it have been satisfied, and will
2216generate [Google Test](http://code.google.com/p/googletest/) failures
2217if not. This is convenient as it leaves you with one less thing to
2218worry about. That is, unless you are not sure if your mock object will
2219be destoyed.
2220
2221How could it be that your mock object won't eventually be destroyed?
2222Well, it might be created on the heap and owned by the code you are
2223testing. Suppose there's a bug in that code and it doesn't delete the
2224mock object properly - you could end up with a passing test when
2225there's actually a bug.
2226
2227Using a heap checker is a good idea and can alleviate the concern, but
2228its implementation may not be 100% reliable. So, sometimes you do want
2229to _force_ Google Mock to verify a mock object before it is
2230(hopefully) destructed. You can do this with
2231`Mock::VerifyAndClearExpectations(&mock_object)`:
2232
2233```
2234TEST(MyServerTest, ProcessesRequest) {
2235  using ::testing::Mock;
2236
2237  MockFoo* const foo = new MockFoo;
2238  EXPECT_CALL(*foo, ...)...;
2239  // ... other expectations ...
2240
2241  // server now owns foo.
2242  MyServer server(foo);
2243  server.ProcessRequest(...);
2244
2245  // In case that server's destructor will forget to delete foo,
2246  // this will verify the expectations anyway.
2247  Mock::VerifyAndClearExpectations(foo);
2248}  // server is destroyed when it goes out of scope here.
2249```
2250
2251**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a
2252`bool` to indicate whether the verification was successful (`true` for
2253yes), so you can wrap that function call inside a `ASSERT_TRUE()` if
2254there is no point going further when the verification has failed.
2255
2256## Using Check Points ##
2257
2258Sometimes you may want to "reset" a mock object at various check
2259points in your test: at each check point, you verify that all existing
2260expectations on the mock object have been satisfied, and then you set
2261some new expectations on it as if it's newly created. This allows you
2262to work with a mock object in "phases" whose sizes are each
2263manageable.
2264
2265One such scenario is that in your test's `SetUp()` function, you may
2266want to put the object you are testing into a certain state, with the
2267help from a mock object. Once in the desired state, you want to clear
2268all expectations on the mock, such that in the `TEST_F` body you can
2269set fresh expectations on it.
2270
2271As you may have figured out, the `Mock::VerifyAndClearExpectations()`
2272function we saw in the previous recipe can help you here. Or, if you
2273are using `ON_CALL()` to set default actions on the mock object and
2274want to clear the default actions as well, use
2275`Mock::VerifyAndClear(&mock_object)` instead. This function does what
2276`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the
2277same `bool`, **plus** it clears the `ON_CALL()` statements on
2278`mock_object` too.
2279
2280Another trick you can use to achieve the same effect is to put the
2281expectations in sequences and insert calls to a dummy "check-point"
2282function at specific places. Then you can verify that the mock
2283function calls do happen at the right time. For example, if you are
2284exercising code:
2285
2286```
2287Foo(1);
2288Foo(2);
2289Foo(3);
2290```
2291
2292and want to verify that `Foo(1)` and `Foo(3)` both invoke
2293`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write:
2294
2295```
2296using ::testing::MockFunction;
2297
2298TEST(FooTest, InvokesBarCorrectly) {
2299  MyMock mock;
2300  // Class MockFunction<F> has exactly one mock method.  It is named
2301  // Call() and has type F.
2302  MockFunction<void(string check_point_name)> check;
2303  {
2304    InSequence s;
2305
2306    EXPECT_CALL(mock, Bar("a"));
2307    EXPECT_CALL(check, Call("1"));
2308    EXPECT_CALL(check, Call("2"));
2309    EXPECT_CALL(mock, Bar("a"));
2310  }
2311  Foo(1);
2312  check.Call("1");
2313  Foo(2);
2314  check.Call("2");
2315  Foo(3);
2316}
2317```
2318
2319The expectation spec says that the first `Bar("a")` must happen before
2320check point "1", the second `Bar("a")` must happen after check point "2",
2321and nothing should happen between the two check points. The explicit
2322check points make it easy to tell which `Bar("a")` is called by which
2323call to `Foo()`.
2324
2325## Mocking Destructors ##
2326
2327Sometimes you want to make sure a mock object is destructed at the
2328right time, e.g. after `bar->A()` is called but before `bar->B()` is
2329called. We already know that you can specify constraints on the order
2330of mock function calls, so all we need to do is to mock the destructor
2331of the mock function.
2332
2333This sounds simple, except for one problem: a destructor is a special
2334function with special syntax and special semantics, and the
2335`MOCK_METHOD0` macro doesn't work for it:
2336
2337```
2338  MOCK_METHOD0(~MockFoo, void());  // Won't compile!
2339```
2340
2341The good news is that you can use a simple pattern to achieve the same
2342effect. First, add a mock function `Die()` to your mock class and call
2343it in the destructor, like this:
2344
2345```
2346class MockFoo : public Foo {
2347  ...
2348  // Add the following two lines to the mock class.
2349  MOCK_METHOD0(Die, void());
2350  virtual ~MockFoo() { Die(); }
2351};
2352```
2353
2354(If the name `Die()` clashes with an existing symbol, choose another
2355name.) Now, we have translated the problem of testing when a `MockFoo`
2356object dies to testing when its `Die()` method is called:
2357
2358```
2359  MockFoo* foo = new MockFoo;
2360  MockBar* bar = new MockBar;
2361  ...
2362  {
2363    InSequence s;
2364
2365    // Expects *foo to die after bar->A() and before bar->B().
2366    EXPECT_CALL(*bar, A());
2367    EXPECT_CALL(*foo, Die());
2368    EXPECT_CALL(*bar, B());
2369  }
2370```
2371
2372And that's that.
2373
2374## Using Google Mock and Threads ##
2375
2376**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on
2377platforms where Google Mock is thread-safe. Currently these are only
2378platforms that support the pthreads library (this includes Linux and Mac).
2379To make it thread-safe on other platforms we only need to implement
2380some synchronization operations in `"gtest/internal/gtest-port.h"`.
2381
2382In a **unit** test, it's best if you could isolate and test a piece of
2383code in a single-threaded context. That avoids race conditions and
2384dead locks, and makes debugging your test much easier.
2385
2386Yet many programs are multi-threaded, and sometimes to test something
2387we need to pound on it from more than one thread. Google Mock works
2388for this purpose too.
2389
2390Remember the steps for using a mock:
2391
2392  1. Create a mock object `foo`.
2393  1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`.
2394  1. The code under test calls methods of `foo`.
2395  1. Optionally, verify and reset the mock.
2396  1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.
2397
2398If you follow the following simple rules, your mocks and threads can
2399live happily togeter:
2400
2401  * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow.
2402  * Obviously, you can do step #1 without locking.
2403  * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh?
2404  * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic.
2405
2406If you violate the rules (for example, if you set expectations on a
2407mock while another thread is calling its methods), you get undefined
2408behavior. That's not fun, so don't do it.
2409
2410Google Mock guarantees that the action for a mock function is done in
2411the same thread that called the mock function. For example, in
2412
2413```
2414  EXPECT_CALL(mock, Foo(1))
2415      .WillOnce(action1);
2416  EXPECT_CALL(mock, Foo(2))
2417      .WillOnce(action2);
2418```
2419
2420if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2,
2421Google Mock will execute `action1` in thread 1 and `action2` in thread
24222.
2423
2424Google Mock does _not_ impose a sequence on actions performed in
2425different threads (doing so may create deadlocks as the actions may
2426need to cooperate). This means that the execution of `action1` and
2427`action2` in the above example _may_ interleave. If this is a problem,
2428you should add proper synchronization logic to `action1` and `action2`
2429to make the test thread-safe.
2430
2431
2432Also, remember that `DefaultValue<T>` is a global resource that
2433potentially affects _all_ living mock objects in your
2434program. Naturally, you won't want to mess with it from multiple
2435threads or when there still are mocks in action.
2436
2437## Controlling How Much Information Google Mock Prints ##
2438
2439When Google Mock sees something that has the potential of being an
2440error (e.g. a mock function with no expectation is called, a.k.a. an
2441uninteresting call, which is allowed but perhaps you forgot to
2442explicitly ban the call), it prints some warning messages, including
2443the arguments of the function and the return value. Hopefully this
2444will remind you to take a look and see if there is indeed a problem.
2445
2446Sometimes you are confident that your tests are correct and may not
2447appreciate such friendly messages. Some other times, you are debugging
2448your tests or learning about the behavior of the code you are testing,
2449and wish you could observe every mock call that happens (including
2450argument values and the return value). Clearly, one size doesn't fit
2451all.
2452
2453You can control how much Google Mock tells you using the
2454`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string
2455with three possible values:
2456
2457  * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros.
2458  * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default.
2459  * `error`: Google Mock will print errors only (least verbose).
2460
2461Alternatively, you can adjust the value of that flag from within your
2462tests like so:
2463
2464```
2465  ::testing::FLAGS_gmock_verbose = "error";
2466```
2467
2468Now, judiciously use the right flag to enable Google Mock serve you better!
2469
2470## Running Tests in Emacs ##
2471
2472If you build and run your tests in Emacs, the source file locations of
2473Google Mock and [Google Test](http://code.google.com/p/googletest/)
2474errors will be highlighted. Just press `<Enter>` on one of them and
2475you'll be taken to the offending line. Or, you can just type `C-x ``
2476to jump to the next error.
2477
2478To make it even easier, you can add the following lines to your
2479`~/.emacs` file:
2480
2481```
2482(global-set-key "\M-m"   'compile)  ; m is for make
2483(global-set-key [M-down] 'next-error)
2484(global-set-key [M-up]   '(lambda () (interactive) (next-error -1)))
2485```
2486
2487Then you can type `M-m` to start a build, or `M-up`/`M-down` to move
2488back and forth between errors.
2489
2490## Fusing Google Mock Source Files ##
2491
2492Google Mock's implementation consists of dozens of files (excluding
2493its own tests).  Sometimes you may want them to be packaged up in
2494fewer files instead, such that you can easily copy them to a new
2495machine and start hacking there.  For this we provide an experimental
2496Python script `fuse_gmock_files.py` in the `scripts/` directory
2497(starting with release 1.2.0).  Assuming you have Python 2.4 or above
2498installed on your machine, just go to that directory and run
2499```
2500python fuse_gmock_files.py OUTPUT_DIR
2501```
2502
2503and you should see an `OUTPUT_DIR` directory being created with files
2504`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it.
2505These three files contain everything you need to use Google Mock (and
2506Google Test).  Just copy them to anywhere you want and you are ready
2507to write tests and use mocks.  You can use the
2508[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests
2509against them.
2510
2511# Extending Google Mock #
2512
2513## Writing New Matchers Quickly ##
2514
2515The `MATCHER*` family of macros can be used to define custom matchers
2516easily.  The syntax:
2517
2518```
2519MATCHER(name, description_string_expression) { statements; }
2520```
2521
2522will define a matcher with the given name that executes the
2523statements, which must return a `bool` to indicate if the match
2524succeeds.  Inside the statements, you can refer to the value being
2525matched by `arg`, and refer to its type by `arg_type`.
2526
2527The description string is a `string`-typed expression that documents
2528what the matcher does, and is used to generate the failure message
2529when the match fails.  It can (and should) reference the special
2530`bool` variable `negation`, and should evaluate to the description of
2531the matcher when `negation` is `false`, or that of the matcher's
2532negation when `negation` is `true`.
2533
2534For convenience, we allow the description string to be empty (`""`),
2535in which case Google Mock will use the sequence of words in the
2536matcher name as the description.
2537
2538For example:
2539```
2540MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
2541```
2542allows you to write
2543```
2544  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.
2545  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
2546```
2547or,
2548```
2549using ::testing::Not;
2550...
2551  EXPECT_THAT(some_expression, IsDivisibleBy7());
2552  EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));
2553```
2554If the above assertions fail, they will print something like:
2555```
2556  Value of: some_expression
2557  Expected: is divisible by 7
2558    Actual: 27
2559...
2560  Value of: some_other_expression
2561  Expected: not (is divisible by 7)
2562    Actual: 21
2563```
2564where the descriptions `"is divisible by 7"` and `"not (is divisible
2565by 7)"` are automatically calculated from the matcher name
2566`IsDivisibleBy7`.
2567
2568As you may have noticed, the auto-generated descriptions (especially
2569those for the negation) may not be so great. You can always override
2570them with a string expression of your own:
2571```
2572MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") +
2573                        " divisible by 7") {
2574  return (arg % 7) == 0;
2575}
2576```
2577
2578Optionally, you can stream additional information to a hidden argument
2579named `result_listener` to explain the match result. For example, a
2580better definition of `IsDivisibleBy7` is:
2581```
2582MATCHER(IsDivisibleBy7, "") {
2583  if ((arg % 7) == 0)
2584    return true;
2585
2586  *result_listener << "the remainder is " << (arg % 7);
2587  return false;
2588}
2589```
2590
2591With this definition, the above assertion will give a better message:
2592```
2593  Value of: some_expression
2594  Expected: is divisible by 7
2595    Actual: 27 (the remainder is 6)
2596```
2597
2598You should let `MatchAndExplain()` print _any additional information_
2599that can help a user understand the match result. Note that it should
2600explain why the match succeeds in case of a success (unless it's
2601obvious) - this is useful when the matcher is used inside
2602`Not()`. There is no need to print the argument value itself, as
2603Google Mock already prints it for you.
2604
2605**Notes:**
2606
2607  1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you).  This allows the matcher to be polymorphic.  For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`.  In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on.
2608  1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock.
2609
2610## Writing New Parameterized Matchers Quickly ##
2611
2612Sometimes you'll want to define a matcher that has parameters.  For that you
2613can use the macro:
2614```
2615MATCHER_P(name, param_name, description_string) { statements; }
2616```
2617where the description string can be either `""` or a string expression
2618that references `negation` and `param_name`.
2619
2620For example:
2621```
2622MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2623```
2624will allow you to write:
2625```
2626  EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2627```
2628which may lead to this message (assuming `n` is 10):
2629```
2630  Value of: Blah("a")
2631  Expected: has absolute value 10
2632    Actual: -9
2633```
2634
2635Note that both the matcher description and its parameter are
2636printed, making the message human-friendly.
2637
2638In the matcher definition body, you can write `foo_type` to
2639reference the type of a parameter named `foo`.  For example, in the
2640body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write
2641`value_type` to refer to the type of `value`.
2642
2643Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to
2644`MATCHER_P10` to support multi-parameter matchers:
2645```
2646MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }
2647```
2648
2649Please note that the custom description string is for a particular
2650**instance** of the matcher, where the parameters have been bound to
2651actual values.  Therefore usually you'll want the parameter values to
2652be part of the description.  Google Mock lets you do that by
2653referencing the matcher parameters in the description string
2654expression.
2655
2656For example,
2657```
2658  using ::testing::PrintToString;
2659  MATCHER_P2(InClosedRange, low, hi,
2660             std::string(negation ? "isn't" : "is") + " in range [" +
2661             PrintToString(low) + ", " + PrintToString(hi) + "]") {
2662    return low <= arg && arg <= hi;
2663  }
2664  ...
2665  EXPECT_THAT(3, InClosedRange(4, 6));
2666```
2667would generate a failure that contains the message:
2668```
2669  Expected: is in range [4, 6]
2670```
2671
2672If you specify `""` as the description, the failure message will
2673contain the sequence of words in the matcher name followed by the
2674parameter values printed as a tuple.  For example,
2675```
2676  MATCHER_P2(InClosedRange, low, hi, "") { ... }
2677  ...
2678  EXPECT_THAT(3, InClosedRange(4, 6));
2679```
2680would generate a failure that contains the text:
2681```
2682  Expected: in closed range (4, 6)
2683```
2684
2685For the purpose of typing, you can view
2686```
2687MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
2688```
2689as shorthand for
2690```
2691template <typename p1_type, ..., typename pk_type>
2692FooMatcherPk<p1_type, ..., pk_type>
2693Foo(p1_type p1, ..., pk_type pk) { ... }
2694```
2695
2696When you write `Foo(v1, ..., vk)`, the compiler infers the types of
2697the parameters `v1`, ..., and `vk` for you.  If you are not happy with
2698the result of the type inference, you can specify the types by
2699explicitly instantiating the template, as in `Foo<long, bool>(5, false)`.
2700As said earlier, you don't get to (or need to) specify
2701`arg_type` as that's determined by the context in which the matcher
2702is used.
2703
2704You can assign the result of expression `Foo(p1, ..., pk)` to a
2705variable of type `FooMatcherPk<p1_type, ..., pk_type>`.  This can be
2706useful when composing matchers.  Matchers that don't have a parameter
2707or have only one parameter have special types: you can assign `Foo()`
2708to a `FooMatcher`-typed variable, and assign `Foo(p)` to a
2709`FooMatcherP<p_type>`-typed variable.
2710
2711While you can instantiate a matcher template with reference types,
2712passing the parameters by pointer usually makes your code more
2713readable.  If, however, you still want to pass a parameter by
2714reference, be aware that in the failure message generated by the
2715matcher you will see the value of the referenced object but not its
2716address.
2717
2718You can overload matchers with different numbers of parameters:
2719```
2720MATCHER_P(Blah, a, description_string_1) { ... }
2721MATCHER_P2(Blah, a, b, description_string_2) { ... }
2722```
2723
2724While it's tempting to always use the `MATCHER*` macros when defining
2725a new matcher, you should also consider implementing
2726`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see
2727the recipes that follow), especially if you need to use the matcher a
2728lot.  While these approaches require more work, they give you more
2729control on the types of the value being matched and the matcher
2730parameters, which in general leads to better compiler error messages
2731that pay off in the long run.  They also allow overloading matchers
2732based on parameter types (as opposed to just based on the number of
2733parameters).
2734
2735## Writing New Monomorphic Matchers ##
2736
2737A matcher of argument type `T` implements
2738`::testing::MatcherInterface<T>` and does two things: it tests whether a
2739value of type `T` matches the matcher, and can describe what kind of
2740values it matches. The latter ability is used for generating readable
2741error messages when expectations are violated.
2742
2743The interface looks like this:
2744
2745```
2746class MatchResultListener {
2747 public:
2748  ...
2749  // Streams x to the underlying ostream; does nothing if the ostream
2750  // is NULL.
2751  template <typename T>
2752  MatchResultListener& operator<<(const T& x);
2753
2754  // Returns the underlying ostream.
2755  ::std::ostream* stream();
2756};
2757
2758template <typename T>
2759class MatcherInterface {
2760 public:
2761  virtual ~MatcherInterface();
2762
2763  // Returns true iff the matcher matches x; also explains the match
2764  // result to 'listener'.
2765  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
2766
2767  // Describes this matcher to an ostream.
2768  virtual void DescribeTo(::std::ostream* os) const = 0;
2769
2770  // Describes the negation of this matcher to an ostream.
2771  virtual void DescribeNegationTo(::std::ostream* os) const;
2772};
2773```
2774
2775If you need a custom matcher but `Truly()` is not a good option (for
2776example, you may not be happy with the way `Truly(predicate)`
2777describes itself, or you may want your matcher to be polymorphic as
2778`Eq(value)` is), you can define a matcher to do whatever you want in
2779two steps: first implement the matcher interface, and then define a
2780factory function to create a matcher instance. The second step is not
2781strictly needed but it makes the syntax of using the matcher nicer.
2782
2783For example, you can define a matcher to test whether an `int` is
2784divisible by 7 and then use it like this:
2785```
2786using ::testing::MakeMatcher;
2787using ::testing::Matcher;
2788using ::testing::MatcherInterface;
2789using ::testing::MatchResultListener;
2790
2791class DivisibleBy7Matcher : public MatcherInterface<int> {
2792 public:
2793  virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
2794    return (n % 7) == 0;
2795  }
2796
2797  virtual void DescribeTo(::std::ostream* os) const {
2798    *os << "is divisible by 7";
2799  }
2800
2801  virtual void DescribeNegationTo(::std::ostream* os) const {
2802    *os << "is not divisible by 7";
2803  }
2804};
2805
2806inline Matcher<int> DivisibleBy7() {
2807  return MakeMatcher(new DivisibleBy7Matcher);
2808}
2809...
2810
2811  EXPECT_CALL(foo, Bar(DivisibleBy7()));
2812```
2813
2814You may improve the matcher message by streaming additional
2815information to the `listener` argument in `MatchAndExplain()`:
2816
2817```
2818class DivisibleBy7Matcher : public MatcherInterface<int> {
2819 public:
2820  virtual bool MatchAndExplain(int n,
2821                               MatchResultListener* listener) const {
2822    const int remainder = n % 7;
2823    if (remainder != 0) {
2824      *listener << "the remainder is " << remainder;
2825    }
2826    return remainder == 0;
2827  }
2828  ...
2829};
2830```
2831
2832Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this:
2833```
2834Value of: x
2835Expected: is divisible by 7
2836  Actual: 23 (the remainder is 2)
2837```
2838
2839## Writing New Polymorphic Matchers ##
2840
2841You've learned how to write your own matchers in the previous
2842recipe. Just one problem: a matcher created using `MakeMatcher()` only
2843works for one particular type of arguments. If you want a
2844_polymorphic_ matcher that works with arguments of several types (for
2845instance, `Eq(x)` can be used to match a `value` as long as `value` ==
2846`x` compiles -- `value` and `x` don't have to share the same type),
2847you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit
2848involved.
2849
2850Fortunately, most of the time you can define a polymorphic matcher
2851easily with the help of `MakePolymorphicMatcher()`. Here's how you can
2852define `NotNull()` as an example:
2853
2854```
2855using ::testing::MakePolymorphicMatcher;
2856using ::testing::MatchResultListener;
2857using ::testing::NotNull;
2858using ::testing::PolymorphicMatcher;
2859
2860class NotNullMatcher {
2861 public:
2862  // To implement a polymorphic matcher, first define a COPYABLE class
2863  // that has three members MatchAndExplain(), DescribeTo(), and
2864  // DescribeNegationTo(), like the following.
2865
2866  // In this example, we want to use NotNull() with any pointer, so
2867  // MatchAndExplain() accepts a pointer of any type as its first argument.
2868  // In general, you can define MatchAndExplain() as an ordinary method or
2869  // a method template, or even overload it.
2870  template <typename T>
2871  bool MatchAndExplain(T* p,
2872                       MatchResultListener* /* listener */) const {
2873    return p != NULL;
2874  }
2875
2876  // Describes the property of a value matching this matcher.
2877  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
2878
2879  // Describes the property of a value NOT matching this matcher.
2880  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
2881};
2882
2883// To construct a polymorphic matcher, pass an instance of the class
2884// to MakePolymorphicMatcher().  Note the return type.
2885inline PolymorphicMatcher<NotNullMatcher> NotNull() {
2886  return MakePolymorphicMatcher(NotNullMatcher());
2887}
2888...
2889
2890  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.
2891```
2892
2893**Note:** Your polymorphic matcher class does **not** need to inherit from
2894`MatcherInterface` or any other class, and its methods do **not** need
2895to be virtual.
2896
2897Like in a monomorphic matcher, you may explain the match result by
2898streaming additional information to the `listener` argument in
2899`MatchAndExplain()`.
2900
2901## Writing New Cardinalities ##
2902
2903A cardinality is used in `Times()` to tell Google Mock how many times
2904you expect a call to occur. It doesn't have to be exact. For example,
2905you can say `AtLeast(5)` or `Between(2, 4)`.
2906
2907If the built-in set of cardinalities doesn't suit you, you are free to
2908define your own by implementing the following interface (in namespace
2909`testing`):
2910
2911```
2912class CardinalityInterface {
2913 public:
2914  virtual ~CardinalityInterface();
2915
2916  // Returns true iff call_count calls will satisfy this cardinality.
2917  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
2918
2919  // Returns true iff call_count calls will saturate this cardinality.
2920  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
2921
2922  // Describes self to an ostream.
2923  virtual void DescribeTo(::std::ostream* os) const = 0;
2924};
2925```
2926
2927For example, to specify that a call must occur even number of times,
2928you can write
2929
2930```
2931using ::testing::Cardinality;
2932using ::testing::CardinalityInterface;
2933using ::testing::MakeCardinality;
2934
2935class EvenNumberCardinality : public CardinalityInterface {
2936 public:
2937  virtual bool IsSatisfiedByCallCount(int call_count) const {
2938    return (call_count % 2) == 0;
2939  }
2940
2941  virtual bool IsSaturatedByCallCount(int call_count) const {
2942    return false;
2943  }
2944
2945  virtual void DescribeTo(::std::ostream* os) const {
2946    *os << "called even number of times";
2947  }
2948};
2949
2950Cardinality EvenNumber() {
2951  return MakeCardinality(new EvenNumberCardinality);
2952}
2953...
2954
2955  EXPECT_CALL(foo, Bar(3))
2956      .Times(EvenNumber());
2957```
2958
2959## Writing New Actions Quickly ##
2960
2961If the built-in actions don't work for you, and you find it
2962inconvenient to use `Invoke()`, you can use a macro from the `ACTION*`
2963family to quickly define a new action that can be used in your code as
2964if it's a built-in action.
2965
2966By writing
2967```
2968ACTION(name) { statements; }
2969```
2970in a namespace scope (i.e. not inside a class or function), you will
2971define an action with the given name that executes the statements.
2972The value returned by `statements` will be used as the return value of
2973the action.  Inside the statements, you can refer to the K-th
2974(0-based) argument of the mock function as `argK`.  For example:
2975```
2976ACTION(IncrementArg1) { return ++(*arg1); }
2977```
2978allows you to write
2979```
2980... WillOnce(IncrementArg1());
2981```
2982
2983Note that you don't need to specify the types of the mock function
2984arguments.  Rest assured that your code is type-safe though:
2985you'll get a compiler error if `*arg1` doesn't support the `++`
2986operator, or if the type of `++(*arg1)` isn't compatible with the mock
2987function's return type.
2988
2989Another example:
2990```
2991ACTION(Foo) {
2992  (*arg2)(5);
2993  Blah();
2994  *arg1 = 0;
2995  return arg0;
2996}
2997```
2998defines an action `Foo()` that invokes argument #2 (a function pointer)
2999with 5, calls function `Blah()`, sets the value pointed to by argument
3000#1 to 0, and returns argument #0.
3001
3002For more convenience and flexibility, you can also use the following
3003pre-defined symbols in the body of `ACTION`:
3004
3005| `argK_type` | The type of the K-th (0-based) argument of the mock function |
3006|:------------|:-------------------------------------------------------------|
3007| `args`      | All arguments of the mock function as a tuple                |
3008| `args_type` | The type of all arguments of the mock function as a tuple    |
3009| `return_type` | The return type of the mock function                         |
3010| `function_type` | The type of the mock function                                |
3011
3012For example, when using an `ACTION` as a stub action for mock function:
3013```
3014int DoSomething(bool flag, int* ptr);
3015```
3016we have:
3017| **Pre-defined Symbol** | **Is Bound To** |
3018|:-----------------------|:----------------|
3019| `arg0`                 | the value of `flag` |
3020| `arg0_type`            | the type `bool` |
3021| `arg1`                 | the value of `ptr` |
3022| `arg1_type`            | the type `int*` |
3023| `args`                 | the tuple `(flag, ptr)` |
3024| `args_type`            | the type `std::tr1::tuple<bool, int*>` |
3025| `return_type`          | the type `int`  |
3026| `function_type`        | the type `int(bool, int*)` |
3027
3028## Writing New Parameterized Actions Quickly ##
3029
3030Sometimes you'll want to parameterize an action you define.  For that
3031we have another macro
3032```
3033ACTION_P(name, param) { statements; }
3034```
3035
3036For example,
3037```
3038ACTION_P(Add, n) { return arg0 + n; }
3039```
3040will allow you to write
3041```
3042// Returns argument #0 + 5.
3043... WillOnce(Add(5));
3044```
3045
3046For convenience, we use the term _arguments_ for the values used to
3047invoke the mock function, and the term _parameters_ for the values
3048used to instantiate an action.
3049
3050Note that you don't need to provide the type of the parameter either.
3051Suppose the parameter is named `param`, you can also use the
3052Google-Mock-defined symbol `param_type` to refer to the type of the
3053parameter as inferred by the compiler.  For example, in the body of
3054`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`.
3055
3056Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support
3057multi-parameter actions.  For example,
3058```
3059ACTION_P2(ReturnDistanceTo, x, y) {
3060  double dx = arg0 - x;
3061  double dy = arg1 - y;
3062  return sqrt(dx*dx + dy*dy);
3063}
3064```
3065lets you write
3066```
3067... WillOnce(ReturnDistanceTo(5.0, 26.5));
3068```
3069
3070You can view `ACTION` as a degenerated parameterized action where the
3071number of parameters is 0.
3072
3073You can also easily define actions overloaded on the number of parameters:
3074```
3075ACTION_P(Plus, a) { ... }
3076ACTION_P2(Plus, a, b) { ... }
3077```
3078
3079## Restricting the Type of an Argument or Parameter in an ACTION ##
3080
3081For maximum brevity and reusability, the `ACTION*` macros don't ask
3082you to provide the types of the mock function arguments and the action
3083parameters.  Instead, we let the compiler infer the types for us.
3084
3085Sometimes, however, we may want to be more explicit about the types.
3086There are several tricks to do that.  For example:
3087```
3088ACTION(Foo) {
3089  // Makes sure arg0 can be converted to int.
3090  int n = arg0;
3091  ... use n instead of arg0 here ...
3092}
3093
3094ACTION_P(Bar, param) {
3095  // Makes sure the type of arg1 is const char*.
3096  ::testing::StaticAssertTypeEq<const char*, arg1_type>();
3097
3098  // Makes sure param can be converted to bool.
3099  bool flag = param;
3100}
3101```
3102where `StaticAssertTypeEq` is a compile-time assertion in Google Test
3103that verifies two types are the same.
3104
3105## Writing New Action Templates Quickly ##
3106
3107Sometimes you want to give an action explicit template parameters that
3108cannot be inferred from its value parameters.  `ACTION_TEMPLATE()`
3109supports that and can be viewed as an extension to `ACTION()` and
3110`ACTION_P*()`.
3111
3112The syntax:
3113```
3114ACTION_TEMPLATE(ActionName,
3115                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
3116                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
3117```
3118
3119defines an action template that takes _m_ explicit template parameters
3120and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is
3121between 0 and 10.  `name_i` is the name of the i-th template
3122parameter, and `kind_i` specifies whether it's a `typename`, an
3123integral constant, or a template.  `p_i` is the name of the i-th value
3124parameter.
3125
3126Example:
3127```
3128// DuplicateArg<k, T>(output) converts the k-th argument of the mock
3129// function to type T and copies it to *output.
3130ACTION_TEMPLATE(DuplicateArg,
3131                // Note the comma between int and k:
3132                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
3133                AND_1_VALUE_PARAMS(output)) {
3134  *output = T(std::tr1::get<k>(args));
3135}
3136```
3137
3138To create an instance of an action template, write:
3139```
3140  ActionName<t1, ..., t_m>(v1, ..., v_n)
3141```
3142where the `t`s are the template arguments and the
3143`v`s are the value arguments.  The value argument
3144types are inferred by the compiler.  For example:
3145```
3146using ::testing::_;
3147...
3148  int n;
3149  EXPECT_CALL(mock, Foo(_, _))
3150      .WillOnce(DuplicateArg<1, unsigned char>(&n));
3151```
3152
3153If you want to explicitly specify the value argument types, you can
3154provide additional template arguments:
3155```
3156  ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
3157```
3158where `u_i` is the desired type of `v_i`.
3159
3160`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the
3161number of value parameters, but not on the number of template
3162parameters.  Without the restriction, the meaning of the following is
3163unclear:
3164
3165```
3166  OverloadedAction<int, bool>(x);
3167```
3168
3169Are we using a single-template-parameter action where `bool` refers to
3170the type of `x`, or a two-template-parameter action where the compiler
3171is asked to infer the type of `x`?
3172
3173## Using the ACTION Object's Type ##
3174
3175If you are writing a function that returns an `ACTION` object, you'll
3176need to know its type.  The type depends on the macro used to define
3177the action and the parameter types.  The rule is relatively simple:
3178| **Given Definition** | **Expression** | **Has Type** |
3179|:---------------------|:---------------|:-------------|
3180| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
3181| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` |   `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
3182| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
3183| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` |
3184| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
3185| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` |
3186| ...                  | ...            | ...          |
3187
3188Note that we have to pick different suffixes (`Action`, `ActionP`,
3189`ActionP2`, and etc) for actions with different numbers of value
3190parameters, or the action definitions cannot be overloaded on the
3191number of them.
3192
3193## Writing New Monomorphic Actions ##
3194
3195While the `ACTION*` macros are very convenient, sometimes they are
3196inappropriate.  For example, despite the tricks shown in the previous
3197recipes, they don't let you directly specify the types of the mock
3198function arguments and the action parameters, which in general leads
3199to unoptimized compiler error messages that can baffle unfamiliar
3200users.  They also don't allow overloading actions based on parameter
3201types without jumping through some hoops.
3202
3203An alternative to the `ACTION*` macros is to implement
3204`::testing::ActionInterface<F>`, where `F` is the type of the mock
3205function in which the action will be used. For example:
3206
3207```
3208template <typename F>class ActionInterface {
3209 public:
3210  virtual ~ActionInterface();
3211
3212  // Performs the action.  Result is the return type of function type
3213  // F, and ArgumentTuple is the tuple of arguments of F.
3214  //
3215  // For example, if F is int(bool, const string&), then Result would
3216  // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>.
3217  virtual Result Perform(const ArgumentTuple& args) = 0;
3218};
3219
3220using ::testing::_;
3221using ::testing::Action;
3222using ::testing::ActionInterface;
3223using ::testing::MakeAction;
3224
3225typedef int IncrementMethod(int*);
3226
3227class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
3228 public:
3229  virtual int Perform(const tr1::tuple<int*>& args) {
3230    int* p = tr1::get<0>(args);  // Grabs the first argument.
3231    return *p++;
3232  }
3233};
3234
3235Action<IncrementMethod> IncrementArgument() {
3236  return MakeAction(new IncrementArgumentAction);
3237}
3238...
3239
3240  EXPECT_CALL(foo, Baz(_))
3241      .WillOnce(IncrementArgument());
3242
3243  int n = 5;
3244  foo.Baz(&n);  // Should return 5 and change n to 6.
3245```
3246
3247## Writing New Polymorphic Actions ##
3248
3249The previous recipe showed you how to define your own action. This is
3250all good, except that you need to know the type of the function in
3251which the action will be used. Sometimes that can be a problem. For
3252example, if you want to use the action in functions with _different_
3253types (e.g. like `Return()` and `SetArgPointee()`).
3254
3255If an action can be used in several types of mock functions, we say
3256it's _polymorphic_. The `MakePolymorphicAction()` function template
3257makes it easy to define such an action:
3258
3259```
3260namespace testing {
3261
3262template <typename Impl>
3263PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);
3264
3265}  // namespace testing
3266```
3267
3268As an example, let's define an action that returns the second argument
3269in the mock function's argument list. The first step is to define an
3270implementation class:
3271
3272```
3273class ReturnSecondArgumentAction {
3274 public:
3275  template <typename Result, typename ArgumentTuple>
3276  Result Perform(const ArgumentTuple& args) const {
3277    // To get the i-th (0-based) argument, use tr1::get<i>(args).
3278    return tr1::get<1>(args);
3279  }
3280};
3281```
3282
3283This implementation class does _not_ need to inherit from any
3284particular class. What matters is that it must have a `Perform()`
3285method template. This method template takes the mock function's
3286arguments as a tuple in a **single** argument, and returns the result of
3287the action. It can be either `const` or not, but must be invokable
3288with exactly one template argument, which is the result type. In other
3289words, you must be able to call `Perform<R>(args)` where `R` is the
3290mock function's return type and `args` is its arguments in a tuple.
3291
3292Next, we use `MakePolymorphicAction()` to turn an instance of the
3293implementation class into the polymorphic action we need. It will be
3294convenient to have a wrapper for this:
3295
3296```
3297using ::testing::MakePolymorphicAction;
3298using ::testing::PolymorphicAction;
3299
3300PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
3301  return MakePolymorphicAction(ReturnSecondArgumentAction());
3302}
3303```
3304
3305Now, you can use this polymorphic action the same way you use the
3306built-in ones:
3307
3308```
3309using ::testing::_;
3310
3311class MockFoo : public Foo {
3312 public:
3313  MOCK_METHOD2(DoThis, int(bool flag, int n));
3314  MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
3315};
3316...
3317
3318  MockFoo foo;
3319  EXPECT_CALL(foo, DoThis(_, _))
3320      .WillOnce(ReturnSecondArgument());
3321  EXPECT_CALL(foo, DoThat(_, _, _))
3322      .WillOnce(ReturnSecondArgument());
3323  ...
3324  foo.DoThis(true, 5);         // Will return 5.
3325  foo.DoThat(1, "Hi", "Bye");  // Will return "Hi".
3326```
3327
3328## Teaching Google Mock How to Print Your Values ##
3329
3330When an uninteresting or unexpected call occurs, Google Mock prints the
3331argument values and the stack trace to help you debug.  Assertion
3332macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in
3333question when the assertion fails.  Google Mock and Google Test do this using
3334Google Test's user-extensible value printer.
3335
3336This printer knows how to print built-in C++ types, native arrays, STL
3337containers, and any type that supports the `<<` operator.  For other
3338types, it prints the raw bytes in the value and hopes that you the
3339user can figure it out.
3340[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values)
3341explains how to extend the printer to do a better job at
3342printing your particular type than to dump the bytes.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_6/Documentation.md
r0r249096
1This page lists all documentation wiki pages for Google Mock **1.6**
2- **if you use a released version of Google Mock, please read the documentation for that specific version instead.**
3
4  * [ForDummies](V1_6_ForDummies.md) -- start here if you are new to Google Mock.
5  * [CheatSheet](V1_6_CheatSheet.md) -- a quick reference.
6  * [CookBook](V1_6_CookBook.md) -- recipes for doing various tasks using Google Mock.
7  * [FrequentlyAskedQuestions](V1_6_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list.
8
9To contribute code to Google Mock, read:
10
11  * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch.
12  * [Pump Manual](http://code.google.com/p/googletest/wiki/V1_6_PumpManual) -- how we generate some of Google Mock's source files.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_6/ForDummies.md
r0r249096
1
2
3(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_6_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).)
4
5# What Is Google C++ Mocking Framework? #
6When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc).
7
8**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community:
9
10  * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
11  * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive.
12
13If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks.
14
15**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java.
16
17Using Google Mock involves three basic steps:
18
19  1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class;
20  1. Create some mock objects and specify its expectations and behavior using an intuitive syntax;
21  1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises.
22
23# Why Google Mock? #
24While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_:
25
26  * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it.
27  * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions.
28  * The knowledge you gained from using one mock doesn't transfer to the next.
29
30In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference.
31
32Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you:
33
34  * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid".
35  * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database).
36  * Your tests are brittle as some resources they use are unreliable (e.g. the network).
37  * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one.
38  * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best.
39  * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks.
40
41We encourage you to use Google Mock as:
42
43  * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs!
44  * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators.
45
46# Getting Started #
47Using Google Mock is easy! Inside your C++ source file, just #include `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go.
48
49# A Case for Mock Turtles #
50Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
51
52```
53class Turtle {
54  ...
55  virtual ~Turtle() {}
56  virtual void PenUp() = 0;
57  virtual void PenDown() = 0;
58  virtual void Forward(int distance) = 0;
59  virtual void Turn(int degrees) = 0;
60  virtual void GoTo(int x, int y) = 0;
61  virtual int GetX() const = 0;
62  virtual int GetY() const = 0;
63};
64```
65
66(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.)
67
68You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle.
69
70Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_.
71
72# Writing the Mock Class #
73If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.)
74
75## How to Define It ##
76Using the `Turtle` interface as example, here are the simple steps you need to follow:
77
78  1. Derive a class `MockTurtle` from `Turtle`.
79  1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has.
80  1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so.
81  1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_).
82  1. Repeat until all virtual functions you want to mock are done.
83
84After the process, you should have something like:
85
86```
87#include "gmock/gmock.h"  // Brings in Google Mock.
88class MockTurtle : public Turtle {
89 public:
90  ...
91  MOCK_METHOD0(PenUp, void());
92  MOCK_METHOD0(PenDown, void());
93  MOCK_METHOD1(Forward, void(int distance));
94  MOCK_METHOD1(Turn, void(int degrees));
95  MOCK_METHOD2(GoTo, void(int x, int y));
96  MOCK_CONST_METHOD0(GetX, int());
97  MOCK_CONST_METHOD0(GetY, int());
98};
99```
100
101You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins.
102
103**Tip:** If even this is too much work for you, you'll find the
104`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful.  This command-line
105tool requires that you have Python 2.4 installed.  You give it a C++ file and the name of an abstract class defined in it,
106and it will print the definition of the mock class for you.  Due to the
107complexity of the C++ language, this script may not always work, but
108it can be quite handy when it does.  For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README).
109
110## Where to Put It ##
111When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?)
112
113So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed.
114
115Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does.
116
117# Using Mocks in Tests #
118Once you have a mock class, using it is easy. The typical work flow is:
119
120  1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.).
121  1. Create some mock objects.
122  1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.).
123  1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately.
124  1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.
125
126Here's an example:
127
128```
129#include "path/to/mock-turtle.h"
130#include "gmock/gmock.h"
131#include "gtest/gtest.h"
132using ::testing::AtLeast;                     // #1
133
134TEST(PainterTest, CanDrawSomething) {
135  MockTurtle turtle;                          // #2
136  EXPECT_CALL(turtle, PenDown())              // #3
137      .Times(AtLeast(1));
138
139  Painter painter(&turtle);                   // #4
140
141  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
142}                                             // #5
143
144int main(int argc, char** argv) {
145  // The following line must be executed to initialize Google Mock
146  // (and Google Test) before running the tests.
147  ::testing::InitGoogleMock(&argc, argv);
148  return RUN_ALL_TESTS();
149}
150```
151
152As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this:
153
154```
155path/to/my_test.cc:119: Failure
156Actual function call count doesn't match this expectation:
157Actually: never called;
158Expected: called at least once.
159```
160
161**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation.
162
163**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap.
164
165**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions.
166
167This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier.
168
169Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks.
170
171## Using Google Mock with Any Testing Framework ##
172If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or
173[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to:
174```
175int main(int argc, char** argv) {
176  // The following line causes Google Mock to throw an exception on failure,
177  // which will be interpreted by your testing framework as a test failure.
178  ::testing::GTEST_FLAG(throw_on_failure) = true;
179  ::testing::InitGoogleMock(&argc, argv);
180  ... whatever your testing framework requires ...
181}
182```
183
184This approach has a catch: it makes Google Mock throw an exception
185from a mock object's destructor sometimes.  With some compilers, this
186sometimes causes the test program to crash.  You'll still be able to
187notice that the test has failed, but it's not a graceful failure.
188
189A better solution is to use Google Test's
190[event listener API](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events)
191to report a test failure to your testing framework properly.  You'll need to
192implement the `OnTestPartResult()` method of the event listener interface, but it
193should be straightforward.
194
195If this turns out to be too much work, we suggest that you stick with
196Google Test, which works with Google Mock seamlessly (in fact, it is
197technically part of Google Mock.).  If there is a reason that you
198cannot use Google Test, please let us know.
199
200# Setting Expectations #
201The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right."
202
203## General Syntax ##
204In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
205
206```
207EXPECT_CALL(mock_object, method(matchers))
208    .Times(cardinality)
209    .WillOnce(action)
210    .WillRepeatedly(action);
211```
212
213The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.)
214
215The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections.
216
217This syntax is designed to make an expectation read like English. For example, you can probably guess that
218
219```
220using ::testing::Return;...
221EXPECT_CALL(turtle, GetX())
222    .Times(5)
223    .WillOnce(Return(100))
224    .WillOnce(Return(150))
225    .WillRepeatedly(Return(200));
226```
227
228says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL).
229
230**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier.
231
232## Matchers: What Arguments Do We Expect? ##
233When a mock function takes arguments, we must specify what arguments we are expecting; for example:
234
235```
236// Expects the turtle to move forward by 100 units.
237EXPECT_CALL(turtle, Forward(100));
238```
239
240Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
241
242```
243using ::testing::_;
244...
245// Expects the turtle to move forward.
246EXPECT_CALL(turtle, Forward(_));
247```
248
249`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected.
250
251A list of built-in matchers can be found in the [CheatSheet](V1_6_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
252
253```
254using ::testing::Ge;...
255EXPECT_CALL(turtle, Forward(Ge(100)));
256```
257
258This checks that the turtle will be told to go forward by at least 100 units.
259
260## Cardinalities: How Many Times Will It Be Called? ##
261The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly.
262
263An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called.
264
265We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_6_CheatSheet.md).
266
267The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember:
268
269  * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
270  * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`.
271  * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`.
272
273**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times?
274
275## Actions: What Should It Do? ##
276Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock.
277
278First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used.
279
280Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
281
282```
283using ::testing::Return;...
284EXPECT_CALL(turtle, GetX())
285    .WillOnce(Return(100))
286    .WillOnce(Return(200))
287    .WillOnce(Return(300));
288```
289
290This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
291
292```
293using ::testing::Return;...
294EXPECT_CALL(turtle, GetY())
295    .WillOnce(Return(100))
296    .WillOnce(Return(200))
297    .WillRepeatedly(Return(300));
298```
299
300says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on.
301
302Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).
303
304What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_6_CheatSheet#Actions).
305
306**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
307
308```
309int n = 100;
310EXPECT_CALL(turtle, GetX())
311.Times(4)
312.WillRepeatedly(Return(n++));
313```
314
315Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_6_CookBook.md).
316
317Time for another quiz! What do you think the following means?
318
319```
320using ::testing::Return;...
321EXPECT_CALL(turtle, GetY())
322.Times(4)
323.WillOnce(Return(100));
324```
325
326Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions.
327
328## Using Multiple Expectations ##
329So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects.
330
331By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:
332
333```
334using ::testing::_;...
335EXPECT_CALL(turtle, Forward(_));  // #1
336EXPECT_CALL(turtle, Forward(10))  // #2
337    .Times(2);
338```
339
340If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation.
341
342**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it.
343
344## Ordered vs Unordered Calls ##
345By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified.
346
347Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
348
349```
350using ::testing::InSequence;...
351TEST(FooTest, DrawsLineSegment) {
352  ...
353  {
354    InSequence dummy;
355
356    EXPECT_CALL(turtle, PenDown());
357    EXPECT_CALL(turtle, Forward(100));
358    EXPECT_CALL(turtle, PenUp());
359  }
360  Foo();
361}
362```
363
364By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant.
365
366In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error.
367
368(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_6_CookBook.md).)
369
370## All Expectations Are Sticky (Unless Said Otherwise) ##
371Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)?
372
373After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
374
375```
376using ::testing::_;...
377EXPECT_CALL(turtle, GoTo(_, _))  // #1
378    .Times(AnyNumber());
379EXPECT_CALL(turtle, GoTo(0, 0))  // #2
380    .Times(2);
381```
382
383Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above.
384
385This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.).
386
387Simple? Let's see if you've really understood it: what does the following code say?
388
389```
390using ::testing::Return;
391...
392for (int i = n; i > 0; i--) {
393  EXPECT_CALL(turtle, GetX())
394      .WillOnce(Return(10*i));
395}
396```
397
398If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful!
399
400One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
401
402```
403using ::testing::Return;
404...
405for (int i = n; i > 0; i--) {
406  EXPECT_CALL(turtle, GetX())
407    .WillOnce(Return(10*i))
408    .RetiresOnSaturation();
409}
410```
411
412And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:
413
414```
415using ::testing::InSequence;
416using ::testing::Return;
417...
418{
419  InSequence s;
420
421  for (int i = 1; i <= n; i++) {
422    EXPECT_CALL(turtle, GetX())
423        .WillOnce(Return(10*i))
424        .RetiresOnSaturation();
425  }
426}
427```
428
429By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call).
430
431## Uninteresting Calls ##
432A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called.
433
434In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure.
435
436# What Now? #
437Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.
438
439Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_6_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_6/FrequentlyAskedQuestions.md
r0r249096
1
2
3Please send your questions to the
4[googlemock](http://groups.google.com/group/googlemock) discussion
5group. If you need help with compiler errors, make sure you have
6tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.
7
8## When I call a method on my mock object, the method for the real object is invoked instead.  What's the problem? ##
9
10In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods).
11
12## I wrote some matchers.  After I upgraded to a new version of Google Mock, they no longer compile.  What's going on? ##
13
14After version 1.4.0 of Google Mock was released, we had an idea on how
15to make it easier to write matchers that can generate informative
16messages efficiently.  We experimented with this idea and liked what
17we saw.  Therefore we decided to implement it.
18
19Unfortunately, this means that if you have defined your own matchers
20by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
21your definitions will no longer compile.  Matchers defined using the
22`MATCHER*` family of macros are not affected.
23
24Sorry for the hassle if your matchers are affected.  We believe it's
25in everyone's long-term interest to make this change sooner than
26later.  Fortunately, it's usually not hard to migrate an existing
27matcher to the new API.  Here's what you need to do:
28
29If you wrote your matcher like this:
30```
31// Old matcher definition that doesn't work with the latest
32// Google Mock.
33using ::testing::MatcherInterface;
34...
35class MyWonderfulMatcher : public MatcherInterface<MyType> {
36 public:
37  ...
38  virtual bool Matches(MyType value) const {
39    // Returns true if value matches.
40    return value.GetFoo() > 5;
41  }
42  ...
43};
44```
45
46you'll need to change it to:
47```
48// New matcher definition that works with the latest Google Mock.
49using ::testing::MatcherInterface;
50using ::testing::MatchResultListener;
51...
52class MyWonderfulMatcher : public MatcherInterface<MyType> {
53 public:
54  ...
55  virtual bool MatchAndExplain(MyType value,
56                               MatchResultListener* listener) const {
57    // Returns true if value matches.
58    return value.GetFoo() > 5;
59  }
60  ...
61};
62```
63(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
64argument of type `MatchResultListener*`.)
65
66If you were also using `ExplainMatchResultTo()` to improve the matcher
67message:
68```
69// Old matcher definition that doesn't work with the lastest
70// Google Mock.
71using ::testing::MatcherInterface;
72...
73class MyWonderfulMatcher : public MatcherInterface<MyType> {
74 public:
75  ...
76  virtual bool Matches(MyType value) const {
77    // Returns true if value matches.
78    return value.GetFoo() > 5;
79  }
80
81  virtual void ExplainMatchResultTo(MyType value,
82                                    ::std::ostream* os) const {
83    // Prints some helpful information to os to help
84    // a user understand why value matches (or doesn't match).
85    *os << "the Foo property is " << value.GetFoo();
86  }
87  ...
88};
89```
90
91you should move the logic of `ExplainMatchResultTo()` into
92`MatchAndExplain()`, using the `MatchResultListener` argument where
93the `::std::ostream` was used:
94```
95// New matcher definition that works with the latest Google Mock.
96using ::testing::MatcherInterface;
97using ::testing::MatchResultListener;
98...
99class MyWonderfulMatcher : public MatcherInterface<MyType> {
100 public:
101  ...
102  virtual bool MatchAndExplain(MyType value,
103                               MatchResultListener* listener) const {
104    // Returns true if value matches.
105    *listener << "the Foo property is " << value.GetFoo();
106    return value.GetFoo() > 5;
107  }
108  ...
109};
110```
111
112If your matcher is defined using `MakePolymorphicMatcher()`:
113```
114// Old matcher definition that doesn't work with the latest
115// Google Mock.
116using ::testing::MakePolymorphicMatcher;
117...
118class MyGreatMatcher {
119 public:
120  ...
121  bool Matches(MyType value) const {
122    // Returns true if value matches.
123    return value.GetBar() < 42;
124  }
125  ...
126};
127... MakePolymorphicMatcher(MyGreatMatcher()) ...
128```
129
130you should rename the `Matches()` method to `MatchAndExplain()` and
131add a `MatchResultListener*` argument (the same as what you need to do
132for matchers defined by implementing `MatcherInterface`):
133```
134// New matcher definition that works with the latest Google Mock.
135using ::testing::MakePolymorphicMatcher;
136using ::testing::MatchResultListener;
137...
138class MyGreatMatcher {
139 public:
140  ...
141  bool MatchAndExplain(MyType value,
142                       MatchResultListener* listener) const {
143    // Returns true if value matches.
144    return value.GetBar() < 42;
145  }
146  ...
147};
148... MakePolymorphicMatcher(MyGreatMatcher()) ...
149```
150
151If your polymorphic matcher uses `ExplainMatchResultTo()` for better
152failure messages:
153```
154// Old matcher definition that doesn't work with the latest
155// Google Mock.
156using ::testing::MakePolymorphicMatcher;
157...
158class MyGreatMatcher {
159 public:
160  ...
161  bool Matches(MyType value) const {
162    // Returns true if value matches.
163    return value.GetBar() < 42;
164  }
165  ...
166};
167void ExplainMatchResultTo(const MyGreatMatcher& matcher,
168                          MyType value,
169                          ::std::ostream* os) {
170  // Prints some helpful information to os to help
171  // a user understand why value matches (or doesn't match).
172  *os << "the Bar property is " << value.GetBar();
173}
174... MakePolymorphicMatcher(MyGreatMatcher()) ...
175```
176
177you'll need to move the logic inside `ExplainMatchResultTo()` to
178`MatchAndExplain()`:
179```
180// New matcher definition that works with the latest Google Mock.
181using ::testing::MakePolymorphicMatcher;
182using ::testing::MatchResultListener;
183...
184class MyGreatMatcher {
185 public:
186  ...
187  bool MatchAndExplain(MyType value,
188                       MatchResultListener* listener) const {
189    // Returns true if value matches.
190    *listener << "the Bar property is " << value.GetBar();
191    return value.GetBar() < 42;
192  }
193  ...
194};
195... MakePolymorphicMatcher(MyGreatMatcher()) ...
196```
197
198For more information, you can read these
199[two](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Monomorphic_Matchers)
200[recipes](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Matchers)
201from the cookbook.  As always, you
202are welcome to post questions on `googlemock@googlegroups.com` if you
203need any help.
204
205## When using Google Mock, do I have to use Google Test as the testing framework?  I have my favorite testing framework and don't want to switch. ##
206
207Google Mock works out of the box with Google Test.  However, it's easy
208to configure it to work with any testing framework of your choice.
209[Here](http://code.google.com/p/googlemock/wiki/V1_6_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how.
210
211## How am I supposed to make sense of these horrible template errors? ##
212
213If you are confused by the compiler errors gcc threw at you,
214try consulting the _Google Mock Doctor_ tool first.  What it does is to
215scan stdin for gcc error messages, and spit out diagnoses on the
216problems (we call them diseases) your code has.
217
218To "install", run command:
219```
220alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
221```
222
223To use it, do:
224```
225<your-favorite-build-command> <your-test> 2>&1 | gmd
226```
227
228For example:
229```
230make my_test 2>&1 | gmd
231```
232
233Or you can run `gmd` and copy-n-paste gcc's error messages to it.
234
235## Can I mock a variadic function? ##
236
237You cannot mock a variadic function (i.e. a function taking ellipsis
238(`...`) arguments) directly in Google Mock.
239
240The problem is that in general, there is _no way_ for a mock object to
241know how many arguments are passed to the variadic method, and what
242the arguments' types are.  Only the _author of the base class_ knows
243the protocol, and we cannot look into his head.
244
245Therefore, to mock such a function, the _user_ must teach the mock
246object how to figure out the number of arguments and their types.  One
247way to do it is to provide overloaded versions of the function.
248
249Ellipsis arguments are inherited from C and not really a C++ feature.
250They are unsafe to use and don't work with arguments that have
251constructors or destructors.  Therefore we recommend to avoid them in
252C++ as much as possible.
253
254## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter.  Why? ##
255
256If you compile this using Microsoft Visual C++ 2005 SP1:
257```
258class Foo {
259  ...
260  virtual void Bar(const int i) = 0;
261};
262
263class MockFoo : public Foo {
264  ...
265  MOCK_METHOD1(Bar, void(const int i));
266};
267```
268You may get the following warning:
269```
270warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
271```
272
273This is a MSVC bug.  The same code compiles fine with gcc ,for
274example.  If you use Visual C++ 2008 SP1, you would get the warning:
275```
276warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
277```
278
279In C++, if you _declare_ a function with a `const` parameter, the
280`const` modifier is _ignored_.  Therefore, the `Foo` base class above
281is equivalent to:
282```
283class Foo {
284  ...
285  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
286};
287```
288
289In fact, you can _declare_ Bar() with an `int` parameter, and _define_
290it with a `const int` parameter.  The compiler will still match them
291up.
292
293Since making a parameter `const` is meaningless in the method
294_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
295That should workaround the VC bug.
296
297Note that we are talking about the _top-level_ `const` modifier here.
298If the function parameter is passed by pointer or reference, declaring
299the _pointee_ or _referee_ as `const` is still meaningful.  For
300example, the following two declarations are _not_ equivalent:
301```
302void Bar(int* p);        // Neither p nor *p is const.
303void Bar(const int* p);  // p is not const, but *p is.
304```
305
306## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it.  What can I do? ##
307
308We've noticed that when the `/clr` compiler flag is used, Visual C++
309uses 5~6 times as much memory when compiling a mock class.  We suggest
310to avoid `/clr` when compiling native C++ mocks.
311
312## I can't figure out why Google Mock thinks my expectations are not satisfied.  What should I do? ##
313
314You might want to run your test with
315`--gmock_verbose=info`.  This flag lets Google Mock print a trace
316of every mock function call it receives.  By studying the trace,
317you'll gain insights on why the expectations you set are not met.
318
319## How can I assert that a function is NEVER called? ##
320
321```
322EXPECT_CALL(foo, Bar(_))
323    .Times(0);
324```
325
326## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied.  Isn't this redundant? ##
327
328When Google Mock detects a failure, it prints relevant information
329(the mock function arguments, the state of relevant expectations, and
330etc) to help the user debug.  If another failure is detected, Google
331Mock will do the same, including printing the state of relevant
332expectations.
333
334Sometimes an expectation's state didn't change between two failures,
335and you'll see the same description of the state twice.  They are
336however _not_ redundant, as they refer to _different points in time_.
337The fact they are the same _is_ interesting information.
338
339## I get a heap check failure when using a mock object, but using a real object is fine.  What can be wrong? ##
340
341Does the class (hopefully a pure interface) you are mocking have a
342virtual destructor?
343
344Whenever you derive from a base class, make sure its destructor is
345virtual.  Otherwise Bad Things will happen.  Consider the following
346code:
347
348```
349class Base {
350 public:
351  // Not virtual, but should be.
352  ~Base() { ... }
353  ...
354};
355
356class Derived : public Base {
357 public:
358  ...
359 private:
360  std::string value_;
361};
362
363...
364  Base* p = new Derived;
365  ...
366  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not
367             // - value_ is leaked.
368```
369
370By changing `~Base()` to virtual, `~Derived()` will be correctly
371called when `delete p` is executed, and the heap checker
372will be happy.
373
374## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##
375
376When people complain about this, often they are referring to code like:
377
378```
379// foo.Bar() should be called twice, return 1 the first time, and return
380// 2 the second time.  However, I have to write the expectations in the
381// reverse order.  This sucks big time!!!
382EXPECT_CALL(foo, Bar())
383    .WillOnce(Return(2))
384    .RetiresOnSaturation();
385EXPECT_CALL(foo, Bar())
386    .WillOnce(Return(1))
387    .RetiresOnSaturation();
388```
389
390The problem is that they didn't pick the **best** way to express the test's
391intent.
392
393By default, expectations don't have to be matched in _any_ particular
394order.  If you want them to match in a certain order, you need to be
395explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
396easy to accidentally over-specify your tests, and we want to make it
397harder to do so.
398
399There are two better ways to write the test spec.  You could either
400put the expectations in sequence:
401
402```
403// foo.Bar() should be called twice, return 1 the first time, and return
404// 2 the second time.  Using a sequence, we can write the expectations
405// in their natural order.
406{
407  InSequence s;
408  EXPECT_CALL(foo, Bar())
409      .WillOnce(Return(1))
410      .RetiresOnSaturation();
411  EXPECT_CALL(foo, Bar())
412      .WillOnce(Return(2))
413      .RetiresOnSaturation();
414}
415```
416
417or you can put the sequence of actions in the same expectation:
418
419```
420// foo.Bar() should be called twice, return 1 the first time, and return
421// 2 the second time.
422EXPECT_CALL(foo, Bar())
423    .WillOnce(Return(1))
424    .WillOnce(Return(2))
425    .RetiresOnSaturation();
426```
427
428Back to the original questions: why does Google Mock search the
429expectations (and `ON_CALL`s) from back to front?  Because this
430allows a user to set up a mock's behavior for the common case early
431(e.g. in the mock's constructor or the test fixture's set-up phase)
432and customize it with more specific rules later.  If Google Mock
433searches from front to back, this very useful pattern won't be
434possible.
435
436## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL.  Would it be reasonable not to show the warning in this case? ##
437
438When choosing between being neat and being safe, we lean toward the
439latter.  So the answer is that we think it's better to show the
440warning.
441
442Often people write `ON_CALL`s in the mock object's
443constructor or `SetUp()`, as the default behavior rarely changes from
444test to test.  Then in the test body they set the expectations, which
445are often different for each test.  Having an `ON_CALL` in the set-up
446part of a test doesn't mean that the calls are expected.  If there's
447no `EXPECT_CALL` and the method is called, it's possibly an error.  If
448we quietly let the call go through without notifying the user, bugs
449may creep in unnoticed.
450
451If, however, you are sure that the calls are OK, you can write
452
453```
454EXPECT_CALL(foo, Bar(_))
455    .WillRepeatedly(...);
456```
457
458instead of
459
460```
461ON_CALL(foo, Bar(_))
462    .WillByDefault(...);
463```
464
465This tells Google Mock that you do expect the calls and no warning should be
466printed.
467
468Also, you can control the verbosity using the `--gmock_verbose` flag.
469If you find the output too noisy when debugging, just choose a less
470verbose level.
471
472## How can I delete the mock function's argument in an action? ##
473
474If you find yourself needing to perform some action that's not
475supported by Google Mock directly, remember that you can define your own
476actions using
477[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Actions) or
478[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Actions),
479or you can write a stub function and invoke it using
480[Invoke()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Functions_Methods_Functors).
481
482## MOCK\_METHODn()'s second argument looks funny.  Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##
483
484What?!  I think it's beautiful. :-)
485
486While which syntax looks more natural is a subjective matter to some
487extent, Google Mock's syntax was chosen for several practical advantages it
488has.
489
490Try to mock a function that takes a map as an argument:
491```
492virtual int GetSize(const map<int, std::string>& m);
493```
494
495Using the proposed syntax, it would be:
496```
497MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
498```
499
500Guess what?  You'll get a compiler error as the compiler thinks that
501`const map<int, std::string>& m` are **two**, not one, arguments. To work
502around this you can use `typedef` to give the map type a name, but
503that gets in the way of your work.  Google Mock's syntax avoids this
504problem as the function's argument types are protected inside a pair
505of parentheses:
506```
507// This compiles fine.
508MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
509```
510
511You still need a `typedef` if the return type contains an unprotected
512comma, but that's much rarer.
513
514Other advantages include:
515  1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
516  1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it.  The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively.  Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
517  1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features.  We'd as well stick to the same syntax in `MOCK_METHOD*`!
518
519## My code calls a static/global function.  Can I mock it? ##
520
521You can, but you need to make some changes.
522
523In general, if you find yourself needing to mock a static function,
524it's a sign that your modules are too tightly coupled (and less
525flexible, less reusable, less testable, etc).  You are probably better
526off defining a small interface and call the function through that
527interface, which then can be easily mocked.  It's a bit of work
528initially, but usually pays for itself quickly.
529
530This Google Testing Blog
531[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
532says it excellently.  Check it out.
533
534## My mock object needs to do complex stuff.  It's a lot of pain to specify the actions.  Google Mock sucks! ##
535
536I know it's not a question, but you get an answer for free any way. :-)
537
538With Google Mock, you can create mocks in C++ easily.  And people might be
539tempted to use them everywhere. Sometimes they work great, and
540sometimes you may find them, well, a pain to use. So, what's wrong in
541the latter case?
542
543When you write a test without using mocks, you exercise the code and
544assert that it returns the correct value or that the system is in an
545expected state.  This is sometimes called "state-based testing".
546
547Mocks are great for what some call "interaction-based" testing:
548instead of checking the system state at the very end, mock objects
549verify that they are invoked the right way and report an error as soon
550as it arises, giving you a handle on the precise context in which the
551error was triggered.  This is often more effective and economical to
552do than state-based testing.
553
554If you are doing state-based testing and using a test double just to
555simulate the real object, you are probably better off using a fake.
556Using a mock in this case causes pain, as it's not a strong point for
557mocks to perform complex actions.  If you experience this and think
558that mocks suck, you are just not using the right tool for your
559problem. Or, you might be trying to solve the wrong problem. :-)
560
561## I got a warning "Uninteresting function call encountered - default action taken.."  Should I panic? ##
562
563By all means, NO!  It's just an FYI.
564
565What it means is that you have a mock function, you haven't set any
566expectations on it (by Google Mock's rule this means that you are not
567interested in calls to this function and therefore it can be called
568any number of times), and it is called.  That's OK - you didn't say
569it's not OK to call the function!
570
571What if you actually meant to disallow this function to be called, but
572forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
573one can argue that it's the user's fault, Google Mock tries to be nice and
574prints you a note.
575
576So, when you see the message and believe that there shouldn't be any
577uninteresting calls, you should investigate what's going on.  To make
578your life easier, Google Mock prints the function name and arguments
579when an uninteresting call is encountered.
580
581## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##
582
583Either way is fine - you want to choose the one that's more convenient
584for your circumstance.
585
586Usually, if your action is for a particular function type, defining it
587using `Invoke()` should be easier; if your action can be used in
588functions of different types (e.g. if you are defining
589`Return(value)`), `MakePolymorphicAction()` is
590easiest.  Sometimes you want precise control on what types of
591functions the action can be used in, and implementing
592`ActionInterface` is the way to go here. See the implementation of
593`Return()` in `include/gmock/gmock-actions.h` for an example.
594
595## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified".  What does it mean? ##
596
597You got this error as Google Mock has no idea what value it should return
598when the mock method is called.  `SetArgPointee()` says what the
599side effect is, but doesn't say what the return value should be.  You
600need `DoAll()` to chain a `SetArgPointee()` with a `Return()`.
601
602See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Side_Effects) for more details and an example.
603
604
605## My question is not in your FAQ! ##
606
607If you cannot find the answer to your question in this FAQ, there are
608some other resources you can use:
609
610  1. read other [wiki pages](http://code.google.com/p/googlemock/w/list),
611  1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
612  1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).
613
614Please note that creating an issue in the
615[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_
616a good way to get your answer, as it is monitored infrequently by a
617very small number of people.
618
619When asking a question, it's helpful to provide as much of the
620following information as possible (people cannot help you if there's
621not enough information in your question):
622
623  * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
624  * your operating system,
625  * the name and version of your compiler,
626  * the complete command line flags you give to your compiler,
627  * the complete compiler error messages (if the question is about compilation),
628  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_7/CheatSheet.md
r0r249096
1
2
3# Defining a Mock Class #
4
5## Mocking a Normal Class ##
6
7Given
8```
9class Foo {
10  ...
11  virtual ~Foo();
12  virtual int GetSize() const = 0;
13  virtual string Describe(const char* name) = 0;
14  virtual string Describe(int type) = 0;
15  virtual bool Process(Bar elem, int count) = 0;
16};
17```
18(note that `~Foo()` **must** be virtual) we can define its mock as
19```
20#include "gmock/gmock.h"
21
22class MockFoo : public Foo {
23  MOCK_CONST_METHOD0(GetSize, int());
24  MOCK_METHOD1(Describe, string(const char* name));
25  MOCK_METHOD1(Describe, string(int type));
26  MOCK_METHOD2(Process, bool(Bar elem, int count));
27};
28```
29
30To create a "nice" mock object which ignores all uninteresting calls,
31or a "strict" mock object, which treats them as failures:
32```
33NiceMock<MockFoo> nice_foo;     // The type is a subclass of MockFoo.
34StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
35```
36
37## Mocking a Class Template ##
38
39To mock
40```
41template <typename Elem>
42class StackInterface {
43 public:
44  ...
45  virtual ~StackInterface();
46  virtual int GetSize() const = 0;
47  virtual void Push(const Elem& x) = 0;
48};
49```
50(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros:
51```
52template <typename Elem>
53class MockStack : public StackInterface<Elem> {
54 public:
55  ...
56  MOCK_CONST_METHOD0_T(GetSize, int());
57  MOCK_METHOD1_T(Push, void(const Elem& x));
58};
59```
60
61## Specifying Calling Conventions for Mock Functions ##
62
63If your mock function doesn't use the default calling convention, you
64can specify it by appending `_WITH_CALLTYPE` to any of the macros
65described in the previous two sections and supplying the calling
66convention as the first argument to the macro. For example,
67```
68  MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n));
69  MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y));
70```
71where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
72
73# Using Mocks in Tests #
74
75The typical flow is:
76  1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted.
77  1. Create the mock objects.
78  1. Optionally, set the default actions of the mock objects.
79  1. Set your expectations on the mock objects (How will they be called? What wil they do?).
80  1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions.
81  1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied.
82
83Here is an example:
84```
85using ::testing::Return;                            // #1
86
87TEST(BarTest, DoesThis) {
88  MockFoo foo;                                    // #2
89
90  ON_CALL(foo, GetSize())                         // #3
91      .WillByDefault(Return(1));
92  // ... other default actions ...
93
94  EXPECT_CALL(foo, Describe(5))                   // #4
95      .Times(3)
96      .WillRepeatedly(Return("Category 5"));
97  // ... other expectations ...
98
99  EXPECT_EQ("good", MyProductionFunction(&foo));  // #5
100}                                                 // #6
101```
102
103# Setting Default Actions #
104
105Google Mock has a **built-in default action** for any function that
106returns `void`, `bool`, a numeric value, or a pointer.
107
108To customize the default action for functions with return type `T` globally:
109```
110using ::testing::DefaultValue;
111
112DefaultValue<T>::Set(value);  // Sets the default value to be returned.
113// ... use the mocks ...
114DefaultValue<T>::Clear();     // Resets the default value.
115```
116
117To customize the default action for a particular method, use `ON_CALL()`:
118```
119ON_CALL(mock_object, method(matchers))
120    .With(multi_argument_matcher)  ?
121    .WillByDefault(action);
122```
123
124# Setting Expectations #
125
126`EXPECT_CALL()` sets **expectations** on a mock method (How will it be
127called? What will it do?):
128```
129EXPECT_CALL(mock_object, method(matchers))
130    .With(multi_argument_matcher)  ?
131    .Times(cardinality)            ?
132    .InSequence(sequences)         *
133    .After(expectations)           *
134    .WillOnce(action)              *
135    .WillRepeatedly(action)        ?
136    .RetiresOnSaturation();        ?
137```
138
139If `Times()` is omitted, the cardinality is assumed to be:
140
141  * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
142  * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or
143  * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0.
144
145A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time.
146
147# Matchers #
148
149A **matcher** matches a _single_ argument.  You can use it inside
150`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value
151directly:
152
153| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. |
154|:------------------------------|:----------------------------------------|
155| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. |
156
157Built-in matchers (where `argument` is the function argument) are
158divided into several categories:
159
160## Wildcard ##
161|`_`|`argument` can be any value of the correct type.|
162|:--|:-----------------------------------------------|
163|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`.     |
164
165## Generic Comparison ##
166
167|`Eq(value)` or `value`|`argument == value`|
168|:---------------------|:------------------|
169|`Ge(value)`           |`argument >= value`|
170|`Gt(value)`           |`argument > value` |
171|`Le(value)`           |`argument <= value`|
172|`Lt(value)`           |`argument < value` |
173|`Ne(value)`           |`argument != value`|
174|`IsNull()`            |`argument` is a `NULL` pointer (raw or smart).|
175|`NotNull()`           |`argument` is a non-null pointer (raw or smart).|
176|`Ref(variable)`       |`argument` is a reference to `variable`.|
177|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|
178
179Except `Ref()`, these matchers make a _copy_ of `value` in case it's
180modified or destructed later. If the compiler complains that `value`
181doesn't have a public copy constructor, try wrap it in `ByRef()`,
182e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure
183`non_copyable_value` is not changed afterwards, or the meaning of your
184matcher will be changed.
185
186## Floating-Point Matchers ##
187
188|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
189|:-------------------|:----------------------------------------------------------------------------------------------|
190|`FloatEq(a_float)`  |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal.  |
191|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal.  |
192|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal.    |
193
194The above matchers use ULP-based comparison (the same as used in
195[Google Test](http://code.google.com/p/googletest/)). They
196automatically pick a reasonable error bound based on the absolute
197value of the expected value.  `DoubleEq()` and `FloatEq()` conform to
198the IEEE standard, which requires comparing two NaNs for equality to
199return false. The `NanSensitive*` version instead treats two NaNs as
200equal, which is often what a user wants.
201
202|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.|
203|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------|
204|`FloatNear(a_float, max_abs_error)`  |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal.  |
205|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal.  |
206|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal.    |
207
208## String Matchers ##
209
210The `argument` can be either a C string or a C++ string object:
211
212|`ContainsRegex(string)`|`argument` matches the given regular expression.|
213|:----------------------|:-----------------------------------------------|
214|`EndsWith(suffix)`     |`argument` ends with string `suffix`.           |
215|`HasSubstr(string)`    |`argument` contains `string` as a sub-string.   |
216|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.|
217|`StartsWith(prefix)`   |`argument` starts with string `prefix`.         |
218|`StrCaseEq(string)`    |`argument` is equal to `string`, ignoring case. |
219|`StrCaseNe(string)`    |`argument` is not equal to `string`, ignoring case.|
220|`StrEq(string)`        |`argument` is equal to `string`.                |
221|`StrNe(string)`        |`argument` is not equal to `string`.            |
222
223`ContainsRegex()` and `MatchesRegex()` use the regular expression
224syntax defined
225[here](http://code.google.com/p/googletest/wiki/AdvancedGuide#Regular_Expression_Syntax).
226`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
227strings as well.
228
229## Container Matchers ##
230
231Most STL-style containers support `==`, so you can use
232`Eq(expected_container)` or simply `expected_container` to match a
233container exactly.   If you want to write the elements in-line,
234match them more flexibly, or get more informative messages, you can use:
235
236| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
237|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------|
238| `Contains(e)`            | `argument` contains an element that matches `e`, which can be either a value or a matcher.                                       |
239| `Each(e)`                | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher.                           |
240| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. |
241| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. |
242| `IsEmpty()`              | `argument` is an empty container (`container.empty()`).                                                                          |
243| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
244| `SizeIs(m)`              | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`.                                           |
245| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. |
246| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. |
247| `WhenSorted(m)`          | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(UnorderedElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. |
248| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. |
249
250Notes:
251
252  * These matchers can also match:
253    1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and
254    1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)).
255  * The array being matched may be multi-dimensional (i.e. its elements can be arrays).
256  * `m` in `Pointwise(m, ...)` should be a matcher for `std::tr1::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write:
257
258```
259using ::std::tr1::get;
260MATCHER(FooEq, "") {
261  return get<0>(arg).Equals(get<1>(arg));
262}
263...
264EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
265```
266
267## Member Matchers ##
268
269|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
270|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------|
271|`Key(e)`                 |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
272|`Pair(m1, m2)`           |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.                                                |
273|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
274
275## Matching the Result of a Function or Functor ##
276
277|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
278|:---------------|:---------------------------------------------------------------------|
279
280## Pointer Matchers ##
281
282|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.|
283|:-----------|:-----------------------------------------------------------------------------------------------|
284
285## Multiargument Matchers ##
286
287Technically, all matchers match a _single_ value. A "multi-argument"
288matcher is just one that matches a _tuple_. The following matchers can
289be used to match a tuple `(x, y)`:
290
291|`Eq()`|`x == y`|
292|:-----|:-------|
293|`Ge()`|`x >= y`|
294|`Gt()`|`x > y` |
295|`Le()`|`x <= y`|
296|`Lt()`|`x < y` |
297|`Ne()`|`x != y`|
298
299You can use the following selectors to pick a subset of the arguments
300(or reorder them) to participate in the matching:
301
302|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.|
303|:-----------|:-------------------------------------------------------------------|
304|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.|
305
306## Composite Matchers ##
307
308You can make a matcher from one or more other matchers:
309
310|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.|
311|:-----------------------|:---------------------------------------------------|
312|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.|
313|`Not(m)`                |`argument` doesn't match matcher `m`.               |
314
315## Adapters for Matchers ##
316
317|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.|
318|:------------------|:--------------------------------------|
319|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. |
320|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.|
321
322## Matchers as Predicates ##
323
324|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.|
325|:------------------|:---------------------------------------------------------------------------------------------|
326|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`.       |
327|`Value(value, m)`  |evaluates to `true` if `value` matches `m`.                                                   |
328
329## Defining Matchers ##
330
331| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
332|:-------------------------------------------------|:------------------------------------------------------|
333| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
334| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
335
336**Notes:**
337
338  1. The `MATCHER*` macros cannot be used inside a function or class.
339  1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters).
340  1. You can use `PrintToString(x)` to convert a value `x` of any type to a string.
341
342## Matchers as Test Assertions ##
343
344|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/Primer#Assertions) if the value of `expression` doesn't match matcher `m`.|
345|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------|
346|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.                                                          |
347
348# Actions #
349
350**Actions** specify what a mock function should do when invoked.
351
352## Returning a Value ##
353
354|`Return()`|Return from a `void` mock function.|
355|:---------|:----------------------------------|
356|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.|
357|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
358|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
359|`ReturnNull()`|Return a null pointer.             |
360|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
361|`ReturnRef(variable)`|Return a reference to `variable`.  |
362|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.|
363
364## Side Effects ##
365
366|`Assign(&variable, value)`|Assign `value` to variable.|
367|:-------------------------|:--------------------------|
368| `DeleteArg<N>()`         | Delete the `N`-th (0-based) argument, which must be a pointer. |
369| `SaveArg<N>(pointer)`    | Save the `N`-th (0-based) argument to `*pointer`. |
370| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
371| `SetArgReferee<N>(value)` |   Assign value to the variable referenced by the `N`-th (0-based) argument. |
372|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
373|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.|
374|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
375|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
376|`Throw(exception)`        |Throws the given exception, which can be any copyable value. Available since v1.1.0.|
377
378## Using a Function or a Functor as an Action ##
379
380|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
381|:----------|:-----------------------------------------------------------------------------------------------------------------|
382|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.                                  |
383|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.                       |
384|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.                                                        |
385|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|
386
387The return value of the invoked function is used as the return value
388of the action.
389
390When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
391```
392  double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
393  ...
394  EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
395```
396
397In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example,
398```
399  InvokeArgument<2>(5, string("Hi"), ByRef(foo))
400```
401calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference.
402
403## Default Action ##
404
405|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).|
406|:------------|:--------------------------------------------------------------------|
407
408**Note:** due to technical reasons, `DoDefault()` cannot be used inside  a composite action - trying to do so will result in a run-time error.
409
410## Composite Actions ##
411
412|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
413|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------|
414|`IgnoreResult(a)`       |Perform action `a` and ignore its result. `a` must not return void.                                                           |
415|`WithArg<N>(a)`         |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it.                                         |
416|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it.                                      |
417|`WithoutArgs(a)`        |Perform action `a` without any arguments.                                                                                     |
418
419## Defining Actions ##
420
421| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
422|:--------------------------------------|:---------------------------------------------------------------------------------------|
423| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
424| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`.   |
425
426The `ACTION*` macros cannot be used inside a function or class.
427
428# Cardinalities #
429
430These are used in `Times()` to specify how many times a mock function will be called:
431
432|`AnyNumber()`|The function can be called any number of times.|
433|:------------|:----------------------------------------------|
434|`AtLeast(n)` |The call is expected at least `n` times.       |
435|`AtMost(n)`  |The call is expected at most `n` times.        |
436|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.|
437|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.|
438
439# Expectation Order #
440
441By default, the expectations can be matched in _any_ order.  If some
442or all expectations must be matched in a given order, there are two
443ways to specify it.  They can be used either independently or
444together.
445
446## The After Clause ##
447
448```
449using ::testing::Expectation;
450...
451Expectation init_x = EXPECT_CALL(foo, InitX());
452Expectation init_y = EXPECT_CALL(foo, InitY());
453EXPECT_CALL(foo, Bar())
454    .After(init_x, init_y);
455```
456says that `Bar()` can be called only after both `InitX()` and
457`InitY()` have been called.
458
459If you don't know how many pre-requisites an expectation has when you
460write it, you can use an `ExpectationSet` to collect them:
461
462```
463using ::testing::ExpectationSet;
464...
465ExpectationSet all_inits;
466for (int i = 0; i < element_count; i++) {
467  all_inits += EXPECT_CALL(foo, InitElement(i));
468}
469EXPECT_CALL(foo, Bar())
470    .After(all_inits);
471```
472says that `Bar()` can be called only after all elements have been
473initialized (but we don't care about which elements get initialized
474before the others).
475
476Modifying an `ExpectationSet` after using it in an `.After()` doesn't
477affect the meaning of the `.After()`.
478
479## Sequences ##
480
481When you have a long chain of sequential expectations, it's easier to
482specify the order using **sequences**, which don't require you to given
483each expectation in the chain a different name.  <i>All expected<br>
484calls</i> in the same sequence must occur in the order they are
485specified.
486
487```
488using ::testing::Sequence;
489Sequence s1, s2;
490...
491EXPECT_CALL(foo, Reset())
492    .InSequence(s1, s2)
493    .WillOnce(Return(true));
494EXPECT_CALL(foo, GetSize())
495    .InSequence(s1)
496    .WillOnce(Return(1));
497EXPECT_CALL(foo, Describe(A<const char*>()))
498    .InSequence(s2)
499    .WillOnce(Return("dummy"));
500```
501says that `Reset()` must be called before _both_ `GetSize()` _and_
502`Describe()`, and the latter two can occur in any order.
503
504To put many expectations in a sequence conveniently:
505```
506using ::testing::InSequence;
507{
508  InSequence dummy;
509
510  EXPECT_CALL(...)...;
511  EXPECT_CALL(...)...;
512  ...
513  EXPECT_CALL(...)...;
514}
515```
516says that all expected calls in the scope of `dummy` must occur in
517strict order. The name `dummy` is irrelevant.)
518
519# Verifying and Resetting a Mock #
520
521Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier:
522```
523using ::testing::Mock;
524...
525// Verifies and removes the expectations on mock_obj;
526// returns true iff successful.
527Mock::VerifyAndClearExpectations(&mock_obj);
528...
529// Verifies and removes the expectations on mock_obj;
530// also removes the default actions set by ON_CALL();
531// returns true iff successful.
532Mock::VerifyAndClear(&mock_obj);
533```
534
535You can also tell Google Mock that a mock object can be leaked and doesn't
536need to be verified:
537```
538Mock::AllowLeak(&mock_obj);
539```
540
541# Mock Classes #
542
543Google Mock defines a convenient mock class template
544```
545class MockFunction<R(A1, ..., An)> {
546 public:
547  MOCK_METHODn(Call, R(A1, ..., An));
548};
549```
550See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Check_Points) for one application of it.
551
552# Flags #
553
554| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
555|:-------------------------------|:----------------------------------------------|
556| `--gmock_verbose=LEVEL`        | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_7/CookBook.md
r0r249096
1
2
3You can find recipes for using Google Mock here. If you haven't yet,
4please read the [ForDummies](V1_7_ForDummies.md) document first to make sure you understand
5the basics.
6
7**Note:** Google Mock lives in the `testing` name space. For
8readability, it is recommended to write `using ::testing::Foo;` once in
9your file before using the name `Foo` defined by Google Mock. We omit
10such `using` statements in this page for brevity, but you should do it
11in your own code.
12
13# Creating Mock Classes #
14
15## Mocking Private or Protected Methods ##
16
17You must always put a mock method definition (`MOCK_METHOD*`) in a
18`public:` section of the mock class, regardless of the method being
19mocked being `public`, `protected`, or `private` in the base class.
20This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function
21from outside of the mock class.  (Yes, C++ allows a subclass to change
22the access level of a virtual function in the base class.)  Example:
23
24```
25class Foo {
26 public:
27  ...
28  virtual bool Transform(Gadget* g) = 0;
29
30 protected:
31  virtual void Resume();
32
33 private:
34  virtual int GetTimeOut();
35};
36
37class MockFoo : public Foo {
38 public:
39  ...
40  MOCK_METHOD1(Transform, bool(Gadget* g));
41
42  // The following must be in the public section, even though the
43  // methods are protected or private in the base class.
44  MOCK_METHOD0(Resume, void());
45  MOCK_METHOD0(GetTimeOut, int());
46};
47```
48
49## Mocking Overloaded Methods ##
50
51You can mock overloaded functions as usual. No special attention is required:
52
53```
54class Foo {
55  ...
56
57  // Must be virtual as we'll inherit from Foo.
58  virtual ~Foo();
59
60  // Overloaded on the types and/or numbers of arguments.
61  virtual int Add(Element x);
62  virtual int Add(int times, Element x);
63
64  // Overloaded on the const-ness of this object.
65  virtual Bar& GetBar();
66  virtual const Bar& GetBar() const;
67};
68
69class MockFoo : public Foo {
70  ...
71  MOCK_METHOD1(Add, int(Element x));
72  MOCK_METHOD2(Add, int(int times, Element x);
73
74  MOCK_METHOD0(GetBar, Bar&());
75  MOCK_CONST_METHOD0(GetBar, const Bar&());
76};
77```
78
79**Note:** if you don't mock all versions of the overloaded method, the
80compiler will give you a warning about some methods in the base class
81being hidden. To fix that, use `using` to bring them in scope:
82
83```
84class MockFoo : public Foo {
85  ...
86  using Foo::Add;
87  MOCK_METHOD1(Add, int(Element x));
88  // We don't want to mock int Add(int times, Element x);
89  ...
90};
91```
92
93## Mocking Class Templates ##
94
95To mock a class template, append `_T` to the `MOCK_*` macros:
96
97```
98template <typename Elem>
99class StackInterface {
100  ...
101  // Must be virtual as we'll inherit from StackInterface.
102  virtual ~StackInterface();
103
104  virtual int GetSize() const = 0;
105  virtual void Push(const Elem& x) = 0;
106};
107
108template <typename Elem>
109class MockStack : public StackInterface<Elem> {
110  ...
111  MOCK_CONST_METHOD0_T(GetSize, int());
112  MOCK_METHOD1_T(Push, void(const Elem& x));
113};
114```
115
116## Mocking Nonvirtual Methods ##
117
118Google Mock can mock non-virtual functions to be used in what we call _hi-perf
119dependency injection_.
120
121In this case, instead of sharing a common base class with the real
122class, your mock class will be _unrelated_ to the real class, but
123contain methods with the same signatures.  The syntax for mocking
124non-virtual methods is the _same_ as mocking virtual methods:
125
126```
127// A simple packet stream class.  None of its members is virtual.
128class ConcretePacketStream {
129 public:
130  void AppendPacket(Packet* new_packet);
131  const Packet* GetPacket(size_t packet_number) const;
132  size_t NumberOfPackets() const;
133  ...
134};
135
136// A mock packet stream class.  It inherits from no other, but defines
137// GetPacket() and NumberOfPackets().
138class MockPacketStream {
139 public:
140  MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
141  MOCK_CONST_METHOD0(NumberOfPackets, size_t());
142  ...
143};
144```
145
146Note that the mock class doesn't define `AppendPacket()`, unlike the
147real class. That's fine as long as the test doesn't need to call it.
148
149Next, you need a way to say that you want to use
150`ConcretePacketStream` in production code, and use `MockPacketStream`
151in tests.  Since the functions are not virtual and the two classes are
152unrelated, you must specify your choice at _compile time_ (as opposed
153to run time).
154
155One way to do it is to templatize your code that needs to use a packet
156stream.  More specifically, you will give your code a template type
157argument for the type of the packet stream.  In production, you will
158instantiate your template with `ConcretePacketStream` as the type
159argument.  In tests, you will instantiate the same template with
160`MockPacketStream`.  For example, you may write:
161
162```
163template <class PacketStream>
164void CreateConnection(PacketStream* stream) { ... }
165
166template <class PacketStream>
167class PacketReader {
168 public:
169  void ReadPackets(PacketStream* stream, size_t packet_num);
170};
171```
172
173Then you can use `CreateConnection<ConcretePacketStream>()` and
174`PacketReader<ConcretePacketStream>` in production code, and use
175`CreateConnection<MockPacketStream>()` and
176`PacketReader<MockPacketStream>` in tests.
177
178```
179  MockPacketStream mock_stream;
180  EXPECT_CALL(mock_stream, ...)...;
181  .. set more expectations on mock_stream ...
182  PacketReader<MockPacketStream> reader(&mock_stream);
183  ... exercise reader ...
184```
185
186## Mocking Free Functions ##
187
188It's possible to use Google Mock to mock a free function (i.e. a
189C-style function or a static method).  You just need to rewrite your
190code to use an interface (abstract class).
191
192Instead of calling a free function (say, `OpenFile`) directly,
193introduce an interface for it and have a concrete subclass that calls
194the free function:
195
196```
197class FileInterface {
198 public:
199  ...
200  virtual bool Open(const char* path, const char* mode) = 0;
201};
202
203class File : public FileInterface {
204 public:
205  ...
206  virtual bool Open(const char* path, const char* mode) {
207    return OpenFile(path, mode);
208  }
209};
210```
211
212Your code should talk to `FileInterface` to open a file.  Now it's
213easy to mock out the function.
214
215This may seem much hassle, but in practice you often have multiple
216related functions that you can put in the same interface, so the
217per-function syntactic overhead will be much lower.
218
219If you are concerned about the performance overhead incurred by
220virtual functions, and profiling confirms your concern, you can
221combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md).
222
223## The Nice, the Strict, and the Naggy ##
224
225If a mock method has no `EXPECT_CALL` spec but is called, Google Mock
226will print a warning about the "uninteresting call". The rationale is:
227
228  * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called.
229  * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning.
230
231However, sometimes you may want to suppress all "uninteresting call"
232warnings, while sometimes you may want the opposite, i.e. to treat all
233of them as errors. Google Mock lets you make the decision on a
234per-mock-object basis.
235
236Suppose your test uses a mock class `MockFoo`:
237
238```
239TEST(...) {
240  MockFoo mock_foo;
241  EXPECT_CALL(mock_foo, DoThis());
242  ... code that uses mock_foo ...
243}
244```
245
246If a method of `mock_foo` other than `DoThis()` is called, it will be
247reported by Google Mock as a warning. However, if you rewrite your
248test to use `NiceMock<MockFoo>` instead, the warning will be gone,
249resulting in a cleaner test output:
250
251```
252using ::testing::NiceMock;
253
254TEST(...) {
255  NiceMock<MockFoo> mock_foo;
256  EXPECT_CALL(mock_foo, DoThis());
257  ... code that uses mock_foo ...
258}
259```
260
261`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used
262wherever `MockFoo` is accepted.
263
264It also works if `MockFoo`'s constructor takes some arguments, as
265`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:
266
267```
268using ::testing::NiceMock;
269
270TEST(...) {
271  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
272  EXPECT_CALL(mock_foo, DoThis());
273  ... code that uses mock_foo ...
274}
275```
276
277The usage of `StrictMock` is similar, except that it makes all
278uninteresting calls failures:
279
280```
281using ::testing::StrictMock;
282
283TEST(...) {
284  StrictMock<MockFoo> mock_foo;
285  EXPECT_CALL(mock_foo, DoThis());
286  ... code that uses mock_foo ...
287
288  // The test will fail if a method of mock_foo other than DoThis()
289  // is called.
290}
291```
292
293There are some caveats though (I don't like them just as much as the
294next guy, but sadly they are side effects of C++'s limitations):
295
296  1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported.
297  1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
298  1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict.  This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual.  In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class.  This rule is required for safety.  Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.)
299
300Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort.
301
302## Simplifying the Interface without Breaking Existing Code ##
303
304Sometimes a method has a long list of arguments that is mostly
305uninteresting. For example,
306
307```
308class LogSink {
309 public:
310  ...
311  virtual void send(LogSeverity severity, const char* full_filename,
312                    const char* base_filename, int line,
313                    const struct tm* tm_time,
314                    const char* message, size_t message_len) = 0;
315};
316```
317
318This method's argument list is lengthy and hard to work with (let's
319say that the `message` argument is not even 0-terminated). If we mock
320it as is, using the mock will be awkward. If, however, we try to
321simplify this interface, we'll need to fix all clients depending on
322it, which is often infeasible.
323
324The trick is to re-dispatch the method in the mock class:
325
326```
327class ScopedMockLog : public LogSink {
328 public:
329  ...
330  virtual void send(LogSeverity severity, const char* full_filename,
331                    const char* base_filename, int line, const tm* tm_time,
332                    const char* message, size_t message_len) {
333    // We are only interested in the log severity, full file name, and
334    // log message.
335    Log(severity, full_filename, std::string(message, message_len));
336  }
337
338  // Implements the mock method:
339  //
340  //   void Log(LogSeverity severity,
341  //            const string& file_path,
342  //            const string& message);
343  MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
344                         const string& message));
345};
346```
347
348By defining a new mock method with a trimmed argument list, we make
349the mock class much more user-friendly.
350
351## Alternative to Mocking Concrete Classes ##
352
353Often you may find yourself using classes that don't implement
354interfaces. In order to test your code that uses such a class (let's
355call it `Concrete`), you may be tempted to make the methods of
356`Concrete` virtual and then mock it.
357
358Try not to do that.
359
360Making a non-virtual function virtual is a big decision. It creates an
361extension point where subclasses can tweak your class' behavior. This
362weakens your control on the class because now it's harder to maintain
363the class' invariants. You should make a function virtual only when
364there is a valid reason for a subclass to override it.
365
366Mocking concrete classes directly is problematic as it creates a tight
367coupling between the class and the tests - any small change in the
368class may invalidate your tests and make test maintenance a pain.
369
370To avoid such problems, many programmers have been practicing "coding
371to interfaces": instead of talking to the `Concrete` class, your code
372would define an interface and talk to it. Then you implement that
373interface as an adaptor on top of `Concrete`. In tests, you can easily
374mock that interface to observe how your code is doing.
375
376This technique incurs some overhead:
377
378  * You pay the cost of virtual function calls (usually not a problem).
379  * There is more abstraction for the programmers to learn.
380
381However, it can also bring significant benefits in addition to better
382testability:
383
384  * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive.
385  * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change.
386
387Some people worry that if everyone is practicing this technique, they
388will end up writing lots of redundant code. This concern is totally
389understandable. However, there are two reasons why it may not be the
390case:
391
392  * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code.
393  * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it.
394
395You need to weigh the pros and cons carefully for your particular
396problem, but I'd like to assure you that the Java community has been
397practicing this for a long time and it's a proven effective technique
398applicable in a wide variety of situations. :-)
399
400## Delegating Calls to a Fake ##
401
402Some times you have a non-trivial fake implementation of an
403interface. For example:
404
405```
406class Foo {
407 public:
408  virtual ~Foo() {}
409  virtual char DoThis(int n) = 0;
410  virtual void DoThat(const char* s, int* p) = 0;
411};
412
413class FakeFoo : public Foo {
414 public:
415  virtual char DoThis(int n) {
416    return (n > 0) ? '+' :
417        (n < 0) ? '-' : '0';
418  }
419
420  virtual void DoThat(const char* s, int* p) {
421    *p = strlen(s);
422  }
423};
424```
425
426Now you want to mock this interface such that you can set expectations
427on it. However, you also want to use `FakeFoo` for the default
428behavior, as duplicating it in the mock object is, well, a lot of
429work.
430
431When you define the mock class using Google Mock, you can have it
432delegate its default action to a fake class you already have, using
433this pattern:
434
435```
436using ::testing::_;
437using ::testing::Invoke;
438
439class MockFoo : public Foo {
440 public:
441  // Normal mock method definitions using Google Mock.
442  MOCK_METHOD1(DoThis, char(int n));
443  MOCK_METHOD2(DoThat, void(const char* s, int* p));
444
445  // Delegates the default actions of the methods to a FakeFoo object.
446  // This must be called *before* the custom ON_CALL() statements.
447  void DelegateToFake() {
448    ON_CALL(*this, DoThis(_))
449        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
450    ON_CALL(*this, DoThat(_, _))
451        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
452  }
453 private:
454  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
455};
456```
457
458With that, you can use `MockFoo` in your tests as usual. Just remember
459that if you don't explicitly set an action in an `ON_CALL()` or
460`EXPECT_CALL()`, the fake will be called upon to do it:
461
462```
463using ::testing::_;
464
465TEST(AbcTest, Xyz) {
466  MockFoo foo;
467  foo.DelegateToFake(); // Enables the fake for delegation.
468
469  // Put your ON_CALL(foo, ...)s here, if any.
470
471  // No action specified, meaning to use the default action.
472  EXPECT_CALL(foo, DoThis(5));
473  EXPECT_CALL(foo, DoThat(_, _));
474
475  int n = 0;
476  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
477  foo.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
478  EXPECT_EQ(2, n);
479}
480```
481
482**Some tips:**
483
484  * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
485  * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use.
486  * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double) const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()` method.).
487  * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code.
488
489Regarding the tip on mixing a mock and a fake, here's an example on
490why it may be a bad sign: Suppose you have a class `System` for
491low-level system operations. In particular, it does file and I/O
492operations. And suppose you want to test how your code uses `System`
493to do I/O, and you just want the file operations to work normally. If
494you mock out the entire `System` class, you'll have to provide a fake
495implementation for the file operation part, which suggests that
496`System` is taking on too many roles.
497
498Instead, you can define a `FileOps` interface and an `IOOps` interface
499and split `System`'s functionalities into the two. Then you can mock
500`IOOps` without mocking `FileOps`.
501
502## Delegating Calls to a Real Object ##
503
504When using testing doubles (mocks, fakes, stubs, and etc), sometimes
505their behaviors will differ from those of the real objects. This
506difference could be either intentional (as in simulating an error such
507that you can test the error handling code) or unintentional. If your
508mocks have different behaviors than the real objects by mistake, you
509could end up with code that passes the tests but fails in production.
510
511You can use the _delegating-to-real_ technique to ensure that your
512mock has the same behavior as the real object while retaining the
513ability to validate calls. This technique is very similar to the
514delegating-to-fake technique, the difference being that we use a real
515object instead of a fake. Here's an example:
516
517```
518using ::testing::_;
519using ::testing::AtLeast;
520using ::testing::Invoke;
521
522class MockFoo : public Foo {
523 public:
524  MockFoo() {
525    // By default, all calls are delegated to the real object.
526    ON_CALL(*this, DoThis())
527        .WillByDefault(Invoke(&real_, &Foo::DoThis));
528    ON_CALL(*this, DoThat(_))
529        .WillByDefault(Invoke(&real_, &Foo::DoThat));
530    ...
531  }
532  MOCK_METHOD0(DoThis, ...);
533  MOCK_METHOD1(DoThat, ...);
534  ...
535 private:
536  Foo real_;
537};
538...
539
540  MockFoo mock;
541
542  EXPECT_CALL(mock, DoThis())
543      .Times(3);
544  EXPECT_CALL(mock, DoThat("Hi"))
545      .Times(AtLeast(1));
546  ... use mock in test ...
547```
548
549With this, Google Mock will verify that your code made the right calls
550(with the right arguments, in the right order, called the right number
551of times, etc), and a real object will answer the calls (so the
552behavior will be the same as in production). This gives you the best
553of both worlds.
554
555## Delegating Calls to a Parent Class ##
556
557Ideally, you should code to interfaces, whose methods are all pure
558virtual. In reality, sometimes you do need to mock a virtual method
559that is not pure (i.e, it already has an implementation). For example:
560
561```
562class Foo {
563 public:
564  virtual ~Foo();
565
566  virtual void Pure(int n) = 0;
567  virtual int Concrete(const char* str) { ... }
568};
569
570class MockFoo : public Foo {
571 public:
572  // Mocking a pure method.
573  MOCK_METHOD1(Pure, void(int n));
574  // Mocking a concrete method.  Foo::Concrete() is shadowed.
575  MOCK_METHOD1(Concrete, int(const char* str));
576};
577```
578
579Sometimes you may want to call `Foo::Concrete()` instead of
580`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub
581action, or perhaps your test doesn't need to mock `Concrete()` at all
582(but it would be oh-so painful to have to define a new mock class
583whenever you don't need to mock one of its methods).
584
585The trick is to leave a back door in your mock class for accessing the
586real methods in the base class:
587
588```
589class MockFoo : public Foo {
590 public:
591  // Mocking a pure method.
592  MOCK_METHOD1(Pure, void(int n));
593  // Mocking a concrete method.  Foo::Concrete() is shadowed.
594  MOCK_METHOD1(Concrete, int(const char* str));
595
596  // Use this to call Concrete() defined in Foo.
597  int FooConcrete(const char* str) { return Foo::Concrete(str); }
598};
599```
600
601Now, you can call `Foo::Concrete()` inside an action by:
602
603```
604using ::testing::_;
605using ::testing::Invoke;
606...
607  EXPECT_CALL(foo, Concrete(_))
608      .WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
609```
610
611or tell the mock object that you don't want to mock `Concrete()`:
612
613```
614using ::testing::Invoke;
615...
616  ON_CALL(foo, Concrete(_))
617      .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
618```
619
620(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do
621that, `MockFoo::Concrete()` will be called (and cause an infinite
622recursion) since `Foo::Concrete()` is virtual. That's just how C++
623works.)
624
625# Using Matchers #
626
627## Matching Argument Values Exactly ##
628
629You can specify exactly which arguments a mock method is expecting:
630
631```
632using ::testing::Return;
633...
634  EXPECT_CALL(foo, DoThis(5))
635      .WillOnce(Return('a'));
636  EXPECT_CALL(foo, DoThat("Hello", bar));
637```
638
639## Using Simple Matchers ##
640
641You can use matchers to match arguments that have a certain property:
642
643```
644using ::testing::Ge;
645using ::testing::NotNull;
646using ::testing::Return;
647...
648  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
649      .WillOnce(Return('a'));
650  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
651  // The second argument must not be NULL.
652```
653
654A frequently used matcher is `_`, which matches anything:
655
656```
657using ::testing::_;
658using ::testing::NotNull;
659...
660  EXPECT_CALL(foo, DoThat(_, NotNull()));
661```
662
663## Combining Matchers ##
664
665You can build complex matchers from existing ones using `AllOf()`,
666`AnyOf()`, and `Not()`:
667
668```
669using ::testing::AllOf;
670using ::testing::Gt;
671using ::testing::HasSubstr;
672using ::testing::Ne;
673using ::testing::Not;
674...
675  // The argument must be > 5 and != 10.
676  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
677                                Ne(10))));
678
679  // The first argument must not contain sub-string "blah".
680  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
681                          NULL));
682```
683
684## Casting Matchers ##
685
686Google Mock matchers are statically typed, meaning that the compiler
687can catch your mistake if you use a matcher of the wrong type (for
688example, if you use `Eq(5)` to match a `string` argument). Good for
689you!
690
691Sometimes, however, you know what you're doing and want the compiler
692to give you some slack. One example is that you have a matcher for
693`long` and the argument you want to match is `int`. While the two
694types aren't exactly the same, there is nothing really wrong with
695using a `Matcher<long>` to match an `int` - after all, we can first
696convert the `int` argument to a `long` before giving it to the
697matcher.
698
699To support this need, Google Mock gives you the
700`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type
701`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the
702type `m` accepts):
703
704  1. Type `T` can be implicitly cast to type `U`;
705  1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and
706  1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value).
707
708The code won't compile if any of these conditions isn't met.
709
710Here's one example:
711
712```
713using ::testing::SafeMatcherCast;
714
715// A base class and a child class.
716class Base { ... };
717class Derived : public Base { ... };
718
719class MockFoo : public Foo {
720 public:
721  MOCK_METHOD1(DoThis, void(Derived* derived));
722};
723...
724
725  MockFoo foo;
726  // m is a Matcher<Base*> we got from somewhere.
727  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
728```
729
730If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar
731function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works
732as long as you can `static_cast` type `T` to type `U`.
733
734`MatcherCast` essentially lets you bypass C++'s type system
735(`static_cast` isn't always safe as it could throw away information,
736for example), so be careful not to misuse/abuse it.
737
738## Selecting Between Overloaded Functions ##
739
740If you expect an overloaded function to be called, the compiler may
741need some help on which overloaded version it is.
742
743To disambiguate functions overloaded on the const-ness of this object,
744use the `Const()` argument wrapper.
745
746```
747using ::testing::ReturnRef;
748
749class MockFoo : public Foo {
750  ...
751  MOCK_METHOD0(GetBar, Bar&());
752  MOCK_CONST_METHOD0(GetBar, const Bar&());
753};
754...
755
756  MockFoo foo;
757  Bar bar1, bar2;
758  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
759      .WillOnce(ReturnRef(bar1));
760  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
761      .WillOnce(ReturnRef(bar2));
762```
763
764(`Const()` is defined by Google Mock and returns a `const` reference
765to its argument.)
766
767To disambiguate overloaded functions with the same number of arguments
768but different argument types, you may need to specify the exact type
769of a matcher, either by wrapping your matcher in `Matcher<type>()`, or
770using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`,
771etc):
772
773```
774using ::testing::An;
775using ::testing::Lt;
776using ::testing::Matcher;
777using ::testing::TypedEq;
778
779class MockPrinter : public Printer {
780 public:
781  MOCK_METHOD1(Print, void(int n));
782  MOCK_METHOD1(Print, void(char c));
783};
784
785TEST(PrinterTest, Print) {
786  MockPrinter printer;
787
788  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
789  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
790  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);
791
792  printer.Print(3);
793  printer.Print(6);
794  printer.Print('a');
795}
796```
797
798## Performing Different Actions Based on the Arguments ##
799
800When a mock method is called, the _last_ matching expectation that's
801still active will be selected (think "newer overrides older"). So, you
802can make a method do different things depending on its argument values
803like this:
804
805```
806using ::testing::_;
807using ::testing::Lt;
808using ::testing::Return;
809...
810  // The default case.
811  EXPECT_CALL(foo, DoThis(_))
812      .WillRepeatedly(Return('b'));
813
814  // The more specific case.
815  EXPECT_CALL(foo, DoThis(Lt(5)))
816      .WillRepeatedly(Return('a'));
817```
818
819Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will
820be returned; otherwise `'b'` will be returned.
821
822## Matching Multiple Arguments as a Whole ##
823
824Sometimes it's not enough to match the arguments individually. For
825example, we may want to say that the first argument must be less than
826the second argument. The `With()` clause allows us to match
827all arguments of a mock function as a whole. For example,
828
829```
830using ::testing::_;
831using ::testing::Lt;
832using ::testing::Ne;
833...
834  EXPECT_CALL(foo, InRange(Ne(0), _))
835      .With(Lt());
836```
837
838says that the first argument of `InRange()` must not be 0, and must be
839less than the second argument.
840
841The expression inside `With()` must be a matcher of type
842`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the
843types of the function arguments.
844
845You can also write `AllArgs(m)` instead of `m` inside `.With()`. The
846two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable
847than `.With(Lt())`.
848
849You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments
850(as a tuple) against `m`. For example,
851
852```
853using ::testing::_;
854using ::testing::AllOf;
855using ::testing::Args;
856using ::testing::Lt;
857...
858  EXPECT_CALL(foo, Blah(_, _, _))
859      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
860```
861
862says that `Blah()` will be called with arguments `x`, `y`, and `z` where
863`x < y < z`.
864
865As a convenience and example, Google Mock provides some matchers for
8662-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_7_CheatSheet.md) for
867the complete list.
868
869Note that if you want to pass the arguments to a predicate of your own
870(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be
871written to take a `tr1::tuple` as its argument; Google Mock will pass the `n`
872selected arguments as _one_ single tuple to the predicate.
873
874## Using Matchers as Predicates ##
875
876Have you noticed that a matcher is just a fancy predicate that also
877knows how to describe itself? Many existing algorithms take predicates
878as arguments (e.g. those defined in STL's `<algorithm>` header), and
879it would be a shame if Google Mock matchers are not allowed to
880participate.
881
882Luckily, you can use a matcher where a unary predicate functor is
883expected by wrapping it inside the `Matches()` function. For example,
884
885```
886#include <algorithm>
887#include <vector>
888
889std::vector<int> v;
890...
891// How many elements in v are >= 10?
892const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
893```
894
895Since you can build complex matchers from simpler ones easily using
896Google Mock, this gives you a way to conveniently construct composite
897predicates (doing the same using STL's `<functional>` header is just
898painful). For example, here's a predicate that's satisfied by any
899number that is >= 0, <= 100, and != 50:
900
901```
902Matches(AllOf(Ge(0), Le(100), Ne(50)))
903```
904
905## Using Matchers in Google Test Assertions ##
906
907Since matchers are basically predicates that also know how to describe
908themselves, there is a way to take advantage of them in
909[Google Test](http://code.google.com/p/googletest/) assertions. It's
910called `ASSERT_THAT` and `EXPECT_THAT`:
911
912```
913  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
914  EXPECT_THAT(value, matcher);  // The non-fatal version.
915```
916
917For example, in a Google Test test you can write:
918
919```
920#include "gmock/gmock.h"
921
922using ::testing::AllOf;
923using ::testing::Ge;
924using ::testing::Le;
925using ::testing::MatchesRegex;
926using ::testing::StartsWith;
927...
928
929  EXPECT_THAT(Foo(), StartsWith("Hello"));
930  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
931  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
932```
933
934which (as you can probably guess) executes `Foo()`, `Bar()`, and
935`Baz()`, and verifies that:
936
937  * `Foo()` returns a string that starts with `"Hello"`.
938  * `Bar()` returns a string that matches regular expression `"Line \\d+"`.
939  * `Baz()` returns a number in the range [5, 10].
940
941The nice thing about these macros is that _they read like
942English_. They generate informative messages too. For example, if the
943first `EXPECT_THAT()` above fails, the message will be something like:
944
945```
946Value of: Foo()
947  Actual: "Hi, world!"
948Expected: starts with "Hello"
949```
950
951**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the
952[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds
953`assertThat()` to JUnit.
954
955## Using Predicates as Matchers ##
956
957Google Mock provides a built-in set of matchers. In case you find them
958lacking, you can use an arbitray unary predicate function or functor
959as a matcher - as long as the predicate accepts a value of the type
960you want. You do this by wrapping the predicate inside the `Truly()`
961function, for example:
962
963```
964using ::testing::Truly;
965
966int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
967...
968
969  // Bar() must be called with an even number.
970  EXPECT_CALL(foo, Bar(Truly(IsEven)));
971```
972
973Note that the predicate function / functor doesn't have to return
974`bool`. It works as long as the return value can be used as the
975condition in statement `if (condition) ...`.
976
977## Matching Arguments that Are Not Copyable ##
978
979When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves
980away a copy of `bar`. When `Foo()` is called later, Google Mock
981compares the argument to `Foo()` with the saved copy of `bar`. This
982way, you don't need to worry about `bar` being modified or destroyed
983after the `EXPECT_CALL()` is executed. The same is true when you use
984matchers like `Eq(bar)`, `Le(bar)`, and so on.
985
986But what if `bar` cannot be copied (i.e. has no copy constructor)? You
987could define your own matcher function and use it with `Truly()`, as
988the previous couple of recipes have shown. Or, you may be able to get
989away from it if you can guarantee that `bar` won't be changed after
990the `EXPECT_CALL()` is executed. Just tell Google Mock that it should
991save a reference to `bar`, instead of a copy of it. Here's how:
992
993```
994using ::testing::Eq;
995using ::testing::ByRef;
996using ::testing::Lt;
997...
998  // Expects that Foo()'s argument == bar.
999  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
1000
1001  // Expects that Foo()'s argument < bar.
1002  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
1003```
1004
1005Remember: if you do this, don't change `bar` after the
1006`EXPECT_CALL()`, or the result is undefined.
1007
1008## Validating a Member of an Object ##
1009
1010Often a mock function takes a reference to object as an argument. When
1011matching the argument, you may not want to compare the entire object
1012against a fixed object, as that may be over-specification. Instead,
1013you may need to validate a certain member variable or the result of a
1014certain getter method of the object. You can do this with `Field()`
1015and `Property()`. More specifically,
1016
1017```
1018Field(&Foo::bar, m)
1019```
1020
1021is a matcher that matches a `Foo` object whose `bar` member variable
1022satisfies matcher `m`.
1023
1024```
1025Property(&Foo::baz, m)
1026```
1027
1028is a matcher that matches a `Foo` object whose `baz()` method returns
1029a value that satisfies matcher `m`.
1030
1031For example:
1032
1033> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
1034|:-----------------------------|:-----------------------------------|
1035> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
1036
1037Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no
1038argument and be declared as `const`.
1039
1040BTW, `Field()` and `Property()` can also match plain pointers to
1041objects. For instance,
1042
1043```
1044Field(&Foo::number, Ge(3))
1045```
1046
1047matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`,
1048the match will always fail regardless of the inner matcher.
1049
1050What if you want to validate more than one members at the same time?
1051Remember that there is `AllOf()`.
1052
1053## Validating the Value Pointed to by a Pointer Argument ##
1054
1055C++ functions often take pointers as arguments. You can use matchers
1056like `IsNull()`, `NotNull()`, and other comparison matchers to match a
1057pointer, but what if you want to make sure the value _pointed to_ by
1058the pointer, instead of the pointer itself, has a certain property?
1059Well, you can use the `Pointee(m)` matcher.
1060
1061`Pointee(m)` matches a pointer iff `m` matches the value the pointer
1062points to. For example:
1063
1064```
1065using ::testing::Ge;
1066using ::testing::Pointee;
1067...
1068  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
1069```
1070
1071expects `foo.Bar()` to be called with a pointer that points to a value
1072greater than or equal to 3.
1073
1074One nice thing about `Pointee()` is that it treats a `NULL` pointer as
1075a match failure, so you can write `Pointee(m)` instead of
1076
1077```
1078  AllOf(NotNull(), Pointee(m))
1079```
1080
1081without worrying that a `NULL` pointer will crash your test.
1082
1083Also, did we tell you that `Pointee()` works with both raw pointers
1084**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and
1085etc)?
1086
1087What if you have a pointer to pointer? You guessed it - you can use
1088nested `Pointee()` to probe deeper inside the value. For example,
1089`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer
1090that points to a number less than 3 (what a mouthful...).
1091
1092## Testing a Certain Property of an Object ##
1093
1094Sometimes you want to specify that an object argument has a certain
1095property, but there is no existing matcher that does this. If you want
1096good error messages, you should define a matcher. If you want to do it
1097quick and dirty, you could get away with writing an ordinary function.
1098
1099Let's say you have a mock function that takes an object of type `Foo`,
1100which has an `int bar()` method and an `int baz()` method, and you
1101want to constrain that the argument's `bar()` value plus its `baz()`
1102value is a given number. Here's how you can define a matcher to do it:
1103
1104```
1105using ::testing::MatcherInterface;
1106using ::testing::MatchResultListener;
1107
1108class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
1109 public:
1110  explicit BarPlusBazEqMatcher(int expected_sum)
1111      : expected_sum_(expected_sum) {}
1112
1113  virtual bool MatchAndExplain(const Foo& foo,
1114                               MatchResultListener* listener) const {
1115    return (foo.bar() + foo.baz()) == expected_sum_;
1116  }
1117
1118  virtual void DescribeTo(::std::ostream* os) const {
1119    *os << "bar() + baz() equals " << expected_sum_;
1120  }
1121
1122  virtual void DescribeNegationTo(::std::ostream* os) const {
1123    *os << "bar() + baz() does not equal " << expected_sum_;
1124  }
1125 private:
1126  const int expected_sum_;
1127};
1128
1129inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
1130  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
1131}
1132
1133...
1134
1135  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
1136```
1137
1138## Matching Containers ##
1139
1140Sometimes an STL container (e.g. list, vector, map, ...) is passed to
1141a mock function and you may want to validate it. Since most STL
1142containers support the `==` operator, you can write
1143`Eq(expected_container)` or simply `expected_container` to match a
1144container exactly.
1145
1146Sometimes, though, you may want to be more flexible (for example, the
1147first element must be an exact match, but the second element can be
1148any positive number, and so on). Also, containers used in tests often
1149have a small number of elements, and having to define the expected
1150container out-of-line is a bit of a hassle.
1151
1152You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in
1153such cases:
1154
1155```
1156using ::testing::_;
1157using ::testing::ElementsAre;
1158using ::testing::Gt;
1159...
1160
1161  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
1162...
1163
1164  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
1165```
1166
1167The above matcher says that the container must have 4 elements, which
1168must be 1, greater than 0, anything, and 5 respectively.
1169
1170If you instead write:
1171
1172```
1173using ::testing::_;
1174using ::testing::Gt;
1175using ::testing::UnorderedElementsAre;
1176...
1177
1178  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
1179...
1180
1181  EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5)));
1182```
1183
1184It means that the container must have 4 elements, which under some
1185permutation must be 1, greater than 0, anything, and 5 respectively.
1186
1187`ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0
1188to 10 arguments. If more are needed, you can place them in a C-style
1189array and use `ElementsAreArray()` or `UnorderedElementsAreArray()`
1190instead:
1191
1192```
1193using ::testing::ElementsAreArray;
1194...
1195
1196  // ElementsAreArray accepts an array of element values.
1197  const int expected_vector1[] = { 1, 5, 2, 4, ... };
1198  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));
1199
1200  // Or, an array of element matchers.
1201  Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
1202  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
1203```
1204
1205In case the array needs to be dynamically created (and therefore the
1206array size cannot be inferred by the compiler), you can give
1207`ElementsAreArray()` an additional argument to specify the array size:
1208
1209```
1210using ::testing::ElementsAreArray;
1211...
1212  int* const expected_vector3 = new int[count];
1213  ... fill expected_vector3 with values ...
1214  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
1215```
1216
1217**Tips:**
1218
1219  * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern.
1220  * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers.
1221  * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`.
1222  * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`).
1223
1224## Sharing Matchers ##
1225
1226Under the hood, a Google Mock matcher object consists of a pointer to
1227a ref-counted implementation object. Copying matchers is allowed and
1228very efficient, as only the pointer is copied. When the last matcher
1229that references the implementation object dies, the implementation
1230object will be deleted.
1231
1232Therefore, if you have some complex matcher that you want to use again
1233and again, there is no need to build it everytime. Just assign it to a
1234matcher variable and use that variable repeatedly! For example,
1235
1236```
1237  Matcher<int> in_range = AllOf(Gt(5), Le(10));
1238  ... use in_range as a matcher in multiple EXPECT_CALLs ...
1239```
1240
1241# Setting Expectations #
1242
1243## Knowing When to Expect ##
1244
1245`ON_CALL` is likely the single most under-utilized construct in Google Mock.
1246
1247There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too).
1248
1249Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints.
1250
1251This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests?
1252
1253The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed.
1254
1255Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself.
1256
1257So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them).
1258
1259## Ignoring Uninteresting Calls ##
1260
1261If you are not interested in how a mock method is called, just don't
1262say anything about it. In this case, if the method is ever called,
1263Google Mock will perform its default action to allow the test program
1264to continue. If you are not happy with the default action taken by
1265Google Mock, you can override it using `DefaultValue<T>::Set()`
1266(described later in this document) or `ON_CALL()`.
1267
1268Please note that once you expressed interest in a particular mock
1269method (via `EXPECT_CALL()`), all invocations to it must match some
1270expectation. If this function is called but the arguments don't match
1271any `EXPECT_CALL()` statement, it will be an error.
1272
1273## Disallowing Unexpected Calls ##
1274
1275If a mock method shouldn't be called at all, explicitly say so:
1276
1277```
1278using ::testing::_;
1279...
1280  EXPECT_CALL(foo, Bar(_))
1281      .Times(0);
1282```
1283
1284If some calls to the method are allowed, but the rest are not, just
1285list all the expected calls:
1286
1287```
1288using ::testing::AnyNumber;
1289using ::testing::Gt;
1290...
1291  EXPECT_CALL(foo, Bar(5));
1292  EXPECT_CALL(foo, Bar(Gt(10)))
1293      .Times(AnyNumber());
1294```
1295
1296A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()`
1297statements will be an error.
1298
1299## Expecting Ordered Calls ##
1300
1301Although an `EXPECT_CALL()` statement defined earlier takes precedence
1302when Google Mock tries to match a function call with an expectation,
1303by default calls don't have to happen in the order `EXPECT_CALL()`
1304statements are written. For example, if the arguments match the
1305matchers in the third `EXPECT_CALL()`, but not those in the first two,
1306then the third expectation will be used.
1307
1308If you would rather have all calls occur in the order of the
1309expectations, put the `EXPECT_CALL()` statements in a block where you
1310define a variable of type `InSequence`:
1311
1312```
1313  using ::testing::_;
1314  using ::testing::InSequence;
1315
1316  {
1317    InSequence s;
1318
1319    EXPECT_CALL(foo, DoThis(5));
1320    EXPECT_CALL(bar, DoThat(_))
1321        .Times(2);
1322    EXPECT_CALL(foo, DoThis(6));
1323  }
1324```
1325
1326In this example, we expect a call to `foo.DoThis(5)`, followed by two
1327calls to `bar.DoThat()` where the argument can be anything, which are
1328in turn followed by a call to `foo.DoThis(6)`. If a call occurred
1329out-of-order, Google Mock will report an error.
1330
1331## Expecting Partially Ordered Calls ##
1332
1333Sometimes requiring everything to occur in a predetermined order can
1334lead to brittle tests. For example, we may care about `A` occurring
1335before both `B` and `C`, but aren't interested in the relative order
1336of `B` and `C`. In this case, the test should reflect our real intent,
1337instead of being overly constraining.
1338
1339Google Mock allows you to impose an arbitrary DAG (directed acyclic
1340graph) on the calls. One way to express the DAG is to use the
1341[After](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#The_After_Clause) clause of `EXPECT_CALL`.
1342
1343Another way is via the `InSequence()` clause (not the same as the
1344`InSequence` class), which we borrowed from jMock 2. It's less
1345flexible than `After()`, but more convenient when you have long chains
1346of sequential calls, as it doesn't require you to come up with
1347different names for the expectations in the chains.  Here's how it
1348works:
1349
1350If we view `EXPECT_CALL()` statements as nodes in a graph, and add an
1351edge from node A to node B wherever A must occur before B, we can get
1352a DAG. We use the term "sequence" to mean a directed path in this
1353DAG. Now, if we decompose the DAG into sequences, we just need to know
1354which sequences each `EXPECT_CALL()` belongs to in order to be able to
1355reconstruct the orginal DAG.
1356
1357So, to specify the partial order on the expectations we need to do two
1358things: first to define some `Sequence` objects, and then for each
1359`EXPECT_CALL()` say which `Sequence` objects it is part
1360of. Expectations in the same sequence must occur in the order they are
1361written. For example,
1362
1363```
1364  using ::testing::Sequence;
1365
1366  Sequence s1, s2;
1367
1368  EXPECT_CALL(foo, A())
1369      .InSequence(s1, s2);
1370  EXPECT_CALL(bar, B())
1371      .InSequence(s1);
1372  EXPECT_CALL(bar, C())
1373      .InSequence(s2);
1374  EXPECT_CALL(foo, D())
1375      .InSequence(s2);
1376```
1377
1378specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A ->
1379C -> D`):
1380
1381```
1382       +---> B
1383       |
1384  A ---|
1385       |
1386       +---> C ---> D
1387```
1388
1389This means that A must occur before B and C, and C must occur before
1390D. There's no restriction about the order other than these.
1391
1392## Controlling When an Expectation Retires ##
1393
1394When a mock method is called, Google Mock only consider expectations
1395that are still active. An expectation is active when created, and
1396becomes inactive (aka _retires_) when a call that has to occur later
1397has occurred. For example, in
1398
1399```
1400  using ::testing::_;
1401  using ::testing::Sequence;
1402
1403  Sequence s1, s2;
1404
1405  EXPECT_CALL(log, Log(WARNING, _, "File too large."))     // #1
1406      .Times(AnyNumber())
1407      .InSequence(s1, s2);
1408  EXPECT_CALL(log, Log(WARNING, _, "Data set is empty."))  // #2
1409      .InSequence(s1);
1410  EXPECT_CALL(log, Log(WARNING, _, "User not found."))     // #3
1411      .InSequence(s2);
1412```
1413
1414as soon as either #2 or #3 is matched, #1 will retire. If a warning
1415`"File too large."` is logged after this, it will be an error.
1416
1417Note that an expectation doesn't retire automatically when it's
1418saturated. For example,
1419
1420```
1421using ::testing::_;
1422...
1423  EXPECT_CALL(log, Log(WARNING, _, _));                  // #1
1424  EXPECT_CALL(log, Log(WARNING, _, "File too large."));  // #2
1425```
1426
1427says that there will be exactly one warning with the message `"File
1428too large."`. If the second warning contains this message too, #2 will
1429match again and result in an upper-bound-violated error.
1430
1431If this is not what you want, you can ask an expectation to retire as
1432soon as it becomes saturated:
1433
1434```
1435using ::testing::_;
1436...
1437  EXPECT_CALL(log, Log(WARNING, _, _));                 // #1
1438  EXPECT_CALL(log, Log(WARNING, _, "File too large."))  // #2
1439      .RetiresOnSaturation();
1440```
1441
1442Here #2 can be used only once, so if you have two warnings with the
1443message `"File too large."`, the first will match #2 and the second
1444will match #1 - there will be no error.
1445
1446# Using Actions #
1447
1448## Returning References from Mock Methods ##
1449
1450If a mock function's return type is a reference, you need to use
1451`ReturnRef()` instead of `Return()` to return a result:
1452
1453```
1454using ::testing::ReturnRef;
1455
1456class MockFoo : public Foo {
1457 public:
1458  MOCK_METHOD0(GetBar, Bar&());
1459};
1460...
1461
1462  MockFoo foo;
1463  Bar bar;
1464  EXPECT_CALL(foo, GetBar())
1465      .WillOnce(ReturnRef(bar));
1466```
1467
1468## Returning Live Values from Mock Methods ##
1469
1470The `Return(x)` action saves a copy of `x` when the action is
1471_created_, and always returns the same value whenever it's
1472executed. Sometimes you may want to instead return the _live_ value of
1473`x` (i.e. its value at the time when the action is _executed_.).
1474
1475If the mock function's return type is a reference, you can do it using
1476`ReturnRef(x)`, as shown in the previous recipe ("Returning References
1477from Mock Methods"). However, Google Mock doesn't let you use
1478`ReturnRef()` in a mock function whose return type is not a reference,
1479as doing that usually indicates a user error. So, what shall you do?
1480
1481You may be tempted to try `ByRef()`:
1482
1483```
1484using testing::ByRef;
1485using testing::Return;
1486
1487class MockFoo : public Foo {
1488 public:
1489  MOCK_METHOD0(GetValue, int());
1490};
1491...
1492  int x = 0;
1493  MockFoo foo;
1494  EXPECT_CALL(foo, GetValue())
1495      .WillRepeatedly(Return(ByRef(x)));
1496  x = 42;
1497  EXPECT_EQ(42, foo.GetValue());
1498```
1499
1500Unfortunately, it doesn't work here. The above code will fail with error:
1501
1502```
1503Value of: foo.GetValue()
1504  Actual: 0
1505Expected: 42
1506```
1507
1508The reason is that `Return(value)` converts `value` to the actual
1509return type of the mock function at the time when the action is
1510_created_, not when it is _executed_. (This behavior was chosen for
1511the action to be safe when `value` is a proxy object that references
1512some temporary objects.) As a result, `ByRef(x)` is converted to an
1513`int` value (instead of a `const int&`) when the expectation is set,
1514and `Return(ByRef(x))` will always return 0.
1515
1516`ReturnPointee(pointer)` was provided to solve this problem
1517specifically. It returns the value pointed to by `pointer` at the time
1518the action is _executed_:
1519
1520```
1521using testing::ReturnPointee;
1522...
1523  int x = 0;
1524  MockFoo foo;
1525  EXPECT_CALL(foo, GetValue())
1526      .WillRepeatedly(ReturnPointee(&x));  // Note the & here.
1527  x = 42;
1528  EXPECT_EQ(42, foo.GetValue());  // This will succeed now.
1529```
1530
1531## Combining Actions ##
1532
1533Want to do more than one thing when a function is called? That's
1534fine. `DoAll()` allow you to do sequence of actions every time. Only
1535the return value of the last action in the sequence will be used.
1536
1537```
1538using ::testing::DoAll;
1539
1540class MockFoo : public Foo {
1541 public:
1542  MOCK_METHOD1(Bar, bool(int n));
1543};
1544...
1545
1546  EXPECT_CALL(foo, Bar(_))
1547      .WillOnce(DoAll(action_1,
1548                      action_2,
1549                      ...
1550                      action_n));
1551```
1552
1553## Mocking Side Effects ##
1554
1555Sometimes a method exhibits its effect not via returning a value but
1556via side effects. For example, it may change some global state or
1557modify an output argument. To mock side effects, in general you can
1558define your own action by implementing `::testing::ActionInterface`.
1559
1560If all you need to do is to change an output argument, the built-in
1561`SetArgPointee()` action is convenient:
1562
1563```
1564using ::testing::SetArgPointee;
1565
1566class MockMutator : public Mutator {
1567 public:
1568  MOCK_METHOD2(Mutate, void(bool mutate, int* value));
1569  ...
1570};
1571...
1572
1573  MockMutator mutator;
1574  EXPECT_CALL(mutator, Mutate(true, _))
1575      .WillOnce(SetArgPointee<1>(5));
1576```
1577
1578In this example, when `mutator.Mutate()` is called, we will assign 5
1579to the `int` variable pointed to by argument #1
1580(0-based).
1581
1582`SetArgPointee()` conveniently makes an internal copy of the
1583value you pass to it, removing the need to keep the value in scope and
1584alive. The implication however is that the value must have a copy
1585constructor and assignment operator.
1586
1587If the mock method also needs to return a value as well, you can chain
1588`SetArgPointee()` with `Return()` using `DoAll()`:
1589
1590```
1591using ::testing::_;
1592using ::testing::Return;
1593using ::testing::SetArgPointee;
1594
1595class MockMutator : public Mutator {
1596 public:
1597  ...
1598  MOCK_METHOD1(MutateInt, bool(int* value));
1599};
1600...
1601
1602  MockMutator mutator;
1603  EXPECT_CALL(mutator, MutateInt(_))
1604      .WillOnce(DoAll(SetArgPointee<0>(5),
1605                      Return(true)));
1606```
1607
1608If the output argument is an array, use the
1609`SetArrayArgument<N>(first, last)` action instead. It copies the
1610elements in source range `[first, last)` to the array pointed to by
1611the `N`-th (0-based) argument:
1612
1613```
1614using ::testing::NotNull;
1615using ::testing::SetArrayArgument;
1616
1617class MockArrayMutator : public ArrayMutator {
1618 public:
1619  MOCK_METHOD2(Mutate, void(int* values, int num_values));
1620  ...
1621};
1622...
1623
1624  MockArrayMutator mutator;
1625  int values[5] = { 1, 2, 3, 4, 5 };
1626  EXPECT_CALL(mutator, Mutate(NotNull(), 5))
1627      .WillOnce(SetArrayArgument<0>(values, values + 5));
1628```
1629
1630This also works when the argument is an output iterator:
1631
1632```
1633using ::testing::_;
1634using ::testing::SeArrayArgument;
1635
1636class MockRolodex : public Rolodex {
1637 public:
1638  MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
1639  ...
1640};
1641...
1642
1643  MockRolodex rolodex;
1644  vector<string> names;
1645  names.push_back("George");
1646  names.push_back("John");
1647  names.push_back("Thomas");
1648  EXPECT_CALL(rolodex, GetNames(_))
1649      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
1650```
1651
1652## Changing a Mock Object's Behavior Based on the State ##
1653
1654If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:
1655
1656```
1657using ::testing::InSequence;
1658using ::testing::Return;
1659
1660...
1661  {
1662    InSequence seq;
1663    EXPECT_CALL(my_mock, IsDirty())
1664        .WillRepeatedly(Return(true));
1665    EXPECT_CALL(my_mock, Flush());
1666    EXPECT_CALL(my_mock, IsDirty())
1667        .WillRepeatedly(Return(false));
1668  }
1669  my_mock.FlushIfDirty();
1670```
1671
1672This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards.
1673
1674If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
1675
1676```
1677using ::testing::_;
1678using ::testing::SaveArg;
1679using ::testing::Return;
1680
1681ACTION_P(ReturnPointee, p) { return *p; }
1682...
1683  int previous_value = 0;
1684  EXPECT_CALL(my_mock, GetPrevValue())
1685      .WillRepeatedly(ReturnPointee(&previous_value));
1686  EXPECT_CALL(my_mock, UpdateValue(_))
1687      .WillRepeatedly(SaveArg<0>(&previous_value));
1688  my_mock.DoSomethingToUpdateValue();
1689```
1690
1691Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call.
1692
1693## Setting the Default Value for a Return Type ##
1694
1695If a mock method's return type is a built-in C++ type or pointer, by
1696default it will return 0 when invoked. You only need to specify an
1697action if this default value doesn't work for you.
1698
1699Sometimes, you may want to change this default value, or you may want
1700to specify a default value for types Google Mock doesn't know
1701about. You can do this using the `::testing::DefaultValue` class
1702template:
1703
1704```
1705class MockFoo : public Foo {
1706 public:
1707  MOCK_METHOD0(CalculateBar, Bar());
1708};
1709...
1710
1711  Bar default_bar;
1712  // Sets the default return value for type Bar.
1713  DefaultValue<Bar>::Set(default_bar);
1714
1715  MockFoo foo;
1716
1717  // We don't need to specify an action here, as the default
1718  // return value works for us.
1719  EXPECT_CALL(foo, CalculateBar());
1720
1721  foo.CalculateBar();  // This should return default_bar.
1722
1723  // Unsets the default return value.
1724  DefaultValue<Bar>::Clear();
1725```
1726
1727Please note that changing the default value for a type can make you
1728tests hard to understand. We recommend you to use this feature
1729judiciously. For example, you may want to make sure the `Set()` and
1730`Clear()` calls are right next to the code that uses your mock.
1731
1732## Setting the Default Actions for a Mock Method ##
1733
1734You've learned how to change the default value of a given
1735type. However, this may be too coarse for your purpose: perhaps you
1736have two mock methods with the same return type and you want them to
1737have different behaviors. The `ON_CALL()` macro allows you to
1738customize your mock's behavior at the method level:
1739
1740```
1741using ::testing::_;
1742using ::testing::AnyNumber;
1743using ::testing::Gt;
1744using ::testing::Return;
1745...
1746  ON_CALL(foo, Sign(_))
1747      .WillByDefault(Return(-1));
1748  ON_CALL(foo, Sign(0))
1749      .WillByDefault(Return(0));
1750  ON_CALL(foo, Sign(Gt(0)))
1751      .WillByDefault(Return(1));
1752
1753  EXPECT_CALL(foo, Sign(_))
1754      .Times(AnyNumber());
1755
1756  foo.Sign(5);   // This should return 1.
1757  foo.Sign(-9);  // This should return -1.
1758  foo.Sign(0);   // This should return 0.
1759```
1760
1761As you may have guessed, when there are more than one `ON_CALL()`
1762statements, the news order take precedence over the older ones. In
1763other words, the **last** one that matches the function arguments will
1764be used. This matching order allows you to set up the common behavior
1765in a mock object's constructor or the test fixture's set-up phase and
1766specialize the mock's behavior later.
1767
1768## Using Functions/Methods/Functors as Actions ##
1769
1770If the built-in actions don't suit you, you can easily use an existing
1771function, method, or functor as an action:
1772
1773```
1774using ::testing::_;
1775using ::testing::Invoke;
1776
1777class MockFoo : public Foo {
1778 public:
1779  MOCK_METHOD2(Sum, int(int x, int y));
1780  MOCK_METHOD1(ComplexJob, bool(int x));
1781};
1782
1783int CalculateSum(int x, int y) { return x + y; }
1784
1785class Helper {
1786 public:
1787  bool ComplexJob(int x);
1788};
1789...
1790
1791  MockFoo foo;
1792  Helper helper;
1793  EXPECT_CALL(foo, Sum(_, _))
1794      .WillOnce(Invoke(CalculateSum));
1795  EXPECT_CALL(foo, ComplexJob(_))
1796      .WillOnce(Invoke(&helper, &Helper::ComplexJob));
1797
1798  foo.Sum(5, 6);       // Invokes CalculateSum(5, 6).
1799  foo.ComplexJob(10);  // Invokes helper.ComplexJob(10);
1800```
1801
1802The only requirement is that the type of the function, etc must be
1803_compatible_ with the signature of the mock function, meaning that the
1804latter's arguments can be implicitly converted to the corresponding
1805arguments of the former, and the former's return type can be
1806implicitly converted to that of the latter. So, you can invoke
1807something whose type is _not_ exactly the same as the mock function,
1808as long as it's safe to do so - nice, huh?
1809
1810## Invoking a Function/Method/Functor Without Arguments ##
1811
1812`Invoke()` is very useful for doing actions that are more complex. It
1813passes the mock function's arguments to the function or functor being
1814invoked such that the callee has the full context of the call to work
1815with. If the invoked function is not interested in some or all of the
1816arguments, it can simply ignore them.
1817
1818Yet, a common pattern is that a test author wants to invoke a function
1819without the arguments of the mock function. `Invoke()` allows her to
1820do that using a wrapper function that throws away the arguments before
1821invoking an underlining nullary function. Needless to say, this can be
1822tedious and obscures the intent of the test.
1823
1824`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except
1825that it doesn't pass the mock function's arguments to the
1826callee. Here's an example:
1827
1828```
1829using ::testing::_;
1830using ::testing::InvokeWithoutArgs;
1831
1832class MockFoo : public Foo {
1833 public:
1834  MOCK_METHOD1(ComplexJob, bool(int n));
1835};
1836
1837bool Job1() { ... }
1838...
1839
1840  MockFoo foo;
1841  EXPECT_CALL(foo, ComplexJob(_))
1842      .WillOnce(InvokeWithoutArgs(Job1));
1843
1844  foo.ComplexJob(10);  // Invokes Job1().
1845```
1846
1847## Invoking an Argument of the Mock Function ##
1848
1849Sometimes a mock function will receive a function pointer or a functor
1850(in other words, a "callable") as an argument, e.g.
1851
1852```
1853class MockFoo : public Foo {
1854 public:
1855  MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
1856};
1857```
1858
1859and you may want to invoke this callable argument:
1860
1861```
1862using ::testing::_;
1863...
1864  MockFoo foo;
1865  EXPECT_CALL(foo, DoThis(_, _))
1866      .WillOnce(...);
1867  // Will execute (*fp)(5), where fp is the
1868  // second argument DoThis() receives.
1869```
1870
1871Arghh, you need to refer to a mock function argument but C++ has no
1872lambda (yet), so you have to define your own action. :-( Or do you
1873really?
1874
1875Well, Google Mock has an action to solve _exactly_ this problem:
1876
1877```
1878  InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
1879```
1880
1881will invoke the `N`-th (0-based) argument the mock function receives,
1882with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is
1883a function pointer or a functor, Google Mock handles them both.
1884
1885With that, you could write:
1886
1887```
1888using ::testing::_;
1889using ::testing::InvokeArgument;
1890...
1891  EXPECT_CALL(foo, DoThis(_, _))
1892      .WillOnce(InvokeArgument<1>(5));
1893  // Will execute (*fp)(5), where fp is the
1894  // second argument DoThis() receives.
1895```
1896
1897What if the callable takes an argument by reference? No problem - just
1898wrap it inside `ByRef()`:
1899
1900```
1901...
1902  MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
1903...
1904using ::testing::_;
1905using ::testing::ByRef;
1906using ::testing::InvokeArgument;
1907...
1908
1909  MockFoo foo;
1910  Helper helper;
1911  ...
1912  EXPECT_CALL(foo, Bar(_))
1913      .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
1914  // ByRef(helper) guarantees that a reference to helper, not a copy of it,
1915  // will be passed to the callable.
1916```
1917
1918What if the callable takes an argument by reference and we do **not**
1919wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a
1920copy_ of the argument, and pass a _reference to the copy_, instead of
1921a reference to the original value, to the callable. This is especially
1922handy when the argument is a temporary value:
1923
1924```
1925...
1926  MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
1927...
1928using ::testing::_;
1929using ::testing::InvokeArgument;
1930...
1931
1932  MockFoo foo;
1933  ...
1934  EXPECT_CALL(foo, DoThat(_))
1935      .WillOnce(InvokeArgument<0>(5.0, string("Hi")));
1936  // Will execute (*f)(5.0, string("Hi")), where f is the function pointer
1937  // DoThat() receives.  Note that the values 5.0 and string("Hi") are
1938  // temporary and dead once the EXPECT_CALL() statement finishes.  Yet
1939  // it's fine to perform this action later, since a copy of the values
1940  // are kept inside the InvokeArgument action.
1941```
1942
1943## Ignoring an Action's Result ##
1944
1945Sometimes you have an action that returns _something_, but you need an
1946action that returns `void` (perhaps you want to use it in a mock
1947function that returns `void`, or perhaps it needs to be used in
1948`DoAll()` and it's not the last in the list). `IgnoreResult()` lets
1949you do that. For example:
1950
1951```
1952using ::testing::_;
1953using ::testing::Invoke;
1954using ::testing::Return;
1955
1956int Process(const MyData& data);
1957string DoSomething();
1958
1959class MockFoo : public Foo {
1960 public:
1961  MOCK_METHOD1(Abc, void(const MyData& data));
1962  MOCK_METHOD0(Xyz, bool());
1963};
1964...
1965
1966  MockFoo foo;
1967  EXPECT_CALL(foo, Abc(_))
1968  // .WillOnce(Invoke(Process));
1969  // The above line won't compile as Process() returns int but Abc() needs
1970  // to return void.
1971      .WillOnce(IgnoreResult(Invoke(Process)));
1972
1973  EXPECT_CALL(foo, Xyz())
1974      .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
1975      // Ignores the string DoSomething() returns.
1976                      Return(true)));
1977```
1978
1979Note that you **cannot** use `IgnoreResult()` on an action that already
1980returns `void`. Doing so will lead to ugly compiler errors.
1981
1982## Selecting an Action's Arguments ##
1983
1984Say you have a mock function `Foo()` that takes seven arguments, and
1985you have a custom action that you want to invoke when `Foo()` is
1986called. Trouble is, the custom action only wants three arguments:
1987
1988```
1989using ::testing::_;
1990using ::testing::Invoke;
1991...
1992  MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
1993                         const map<pair<int, int>, double>& weight,
1994                         double min_weight, double max_wight));
1995...
1996
1997bool IsVisibleInQuadrant1(bool visible, int x, int y) {
1998  return visible && x >= 0 && y >= 0;
1999}
2000...
2001
2002  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
2003      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(
2004```
2005
2006To please the compiler God, you can to define an "adaptor" that has
2007the same signature as `Foo()` and calls the custom action with the
2008right arguments:
2009
2010```
2011using ::testing::_;
2012using ::testing::Invoke;
2013
2014bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
2015                            const map<pair<int, int>, double>& weight,
2016                            double min_weight, double max_wight) {
2017  return IsVisibleInQuadrant1(visible, x, y);
2018}
2019...
2020
2021  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
2022      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.
2023```
2024
2025But isn't this awkward?
2026
2027Google Mock provides a generic _action adaptor_, so you can spend your
2028time minding more important business than writing your own
2029adaptors. Here's the syntax:
2030
2031```
2032  WithArgs<N1, N2, ..., Nk>(action)
2033```
2034
2035creates an action that passes the arguments of the mock function at
2036the given indices (0-based) to the inner `action` and performs
2037it. Using `WithArgs`, our original example can be written as:
2038
2039```
2040using ::testing::_;
2041using ::testing::Invoke;
2042using ::testing::WithArgs;
2043...
2044  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
2045      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
2046      // No need to define your own adaptor.
2047```
2048
2049For better readability, Google Mock also gives you:
2050
2051  * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and
2052  * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument.
2053
2054As you may have realized, `InvokeWithoutArgs(...)` is just syntactic
2055sugar for `WithoutArgs(Inovke(...))`.
2056
2057Here are more tips:
2058
2059  * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything.
2060  * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`.
2061  * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.
2062  * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work.
2063
2064## Ignoring Arguments in Action Functions ##
2065
2066The selecting-an-action's-arguments recipe showed us one way to make a
2067mock function and an action with incompatible argument lists fit
2068together. The downside is that wrapping the action in
2069`WithArgs<...>()` can get tedious for people writing the tests.
2070
2071If you are defining a function, method, or functor to be used with
2072`Invoke*()`, and you are not interested in some of its arguments, an
2073alternative to `WithArgs` is to declare the uninteresting arguments as
2074`Unused`. This makes the definition less cluttered and less fragile in
2075case the types of the uninteresting arguments change. It could also
2076increase the chance the action function can be reused. For example,
2077given
2078
2079```
2080  MOCK_METHOD3(Foo, double(const string& label, double x, double y));
2081  MOCK_METHOD3(Bar, double(int index, double x, double y));
2082```
2083
2084instead of
2085
2086```
2087using ::testing::_;
2088using ::testing::Invoke;
2089
2090double DistanceToOriginWithLabel(const string& label, double x, double y) {
2091  return sqrt(x*x + y*y);
2092}
2093
2094double DistanceToOriginWithIndex(int index, double x, double y) {
2095  return sqrt(x*x + y*y);
2096}
2097...
2098
2099  EXEPCT_CALL(mock, Foo("abc", _, _))
2100      .WillOnce(Invoke(DistanceToOriginWithLabel));
2101  EXEPCT_CALL(mock, Bar(5, _, _))
2102      .WillOnce(Invoke(DistanceToOriginWithIndex));
2103```
2104
2105you could write
2106
2107```
2108using ::testing::_;
2109using ::testing::Invoke;
2110using ::testing::Unused;
2111
2112double DistanceToOrigin(Unused, double x, double y) {
2113  return sqrt(x*x + y*y);
2114}
2115...
2116
2117  EXEPCT_CALL(mock, Foo("abc", _, _))
2118      .WillOnce(Invoke(DistanceToOrigin));
2119  EXEPCT_CALL(mock, Bar(5, _, _))
2120      .WillOnce(Invoke(DistanceToOrigin));
2121```
2122
2123## Sharing Actions ##
2124
2125Just like matchers, a Google Mock action object consists of a pointer
2126to a ref-counted implementation object. Therefore copying actions is
2127also allowed and very efficient. When the last action that references
2128the implementation object dies, the implementation object will be
2129deleted.
2130
2131If you have some complex action that you want to use again and again,
2132you may not have to build it from scratch everytime. If the action
2133doesn't have an internal state (i.e. if it always does the same thing
2134no matter how many times it has been called), you can assign it to an
2135action variable and use that variable repeatedly. For example:
2136
2137```
2138  Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5),
2139                                      Return(true));
2140  ... use set_flag in .WillOnce() and .WillRepeatedly() ...
2141```
2142
2143However, if the action has its own state, you may be surprised if you
2144share the action object. Suppose you have an action factory
2145`IncrementCounter(init)` which creates an action that increments and
2146returns a counter whose initial value is `init`, using two actions
2147created from the same expression and using a shared action will
2148exihibit different behaviors. Example:
2149
2150```
2151  EXPECT_CALL(foo, DoThis())
2152      .WillRepeatedly(IncrementCounter(0));
2153  EXPECT_CALL(foo, DoThat())
2154      .WillRepeatedly(IncrementCounter(0));
2155  foo.DoThis();  // Returns 1.
2156  foo.DoThis();  // Returns 2.
2157  foo.DoThat();  // Returns 1 - Blah() uses a different
2158                 // counter than Bar()'s.
2159```
2160
2161versus
2162
2163```
2164  Action<int()> increment = IncrementCounter(0);
2165
2166  EXPECT_CALL(foo, DoThis())
2167      .WillRepeatedly(increment);
2168  EXPECT_CALL(foo, DoThat())
2169      .WillRepeatedly(increment);
2170  foo.DoThis();  // Returns 1.
2171  foo.DoThis();  // Returns 2.
2172  foo.DoThat();  // Returns 3 - the counter is shared.
2173```
2174
2175# Misc Recipes on Using Google Mock #
2176
2177## Making the Compilation Faster ##
2178
2179Believe it or not, the _vast majority_ of the time spent on compiling
2180a mock class is in generating its constructor and destructor, as they
2181perform non-trivial tasks (e.g. verification of the
2182expectations). What's more, mock methods with different signatures
2183have different types and thus their constructors/destructors need to
2184be generated by the compiler separately. As a result, if you mock many
2185different types of methods, compiling your mock class can get really
2186slow.
2187
2188If you are experiencing slow compilation, you can move the definition
2189of your mock class' constructor and destructor out of the class body
2190and into a `.cpp` file. This way, even if you `#include` your mock
2191class in N files, the compiler only needs to generate its constructor
2192and destructor once, resulting in a much faster compilation.
2193
2194Let's illustrate the idea using an example. Here's the definition of a
2195mock class before applying this recipe:
2196
2197```
2198// File mock_foo.h.
2199...
2200class MockFoo : public Foo {
2201 public:
2202  // Since we don't declare the constructor or the destructor,
2203  // the compiler will generate them in every translation unit
2204  // where this mock class is used.
2205
2206  MOCK_METHOD0(DoThis, int());
2207  MOCK_METHOD1(DoThat, bool(const char* str));
2208  ... more mock methods ...
2209};
2210```
2211
2212After the change, it would look like:
2213
2214```
2215// File mock_foo.h.
2216...
2217class MockFoo : public Foo {
2218 public:
2219  // The constructor and destructor are declared, but not defined, here.
2220  MockFoo();
2221  virtual ~MockFoo();
2222
2223  MOCK_METHOD0(DoThis, int());
2224  MOCK_METHOD1(DoThat, bool(const char* str));
2225  ... more mock methods ...
2226};
2227```
2228and
2229```
2230// File mock_foo.cpp.
2231#include "path/to/mock_foo.h"
2232
2233// The definitions may appear trivial, but the functions actually do a
2234// lot of things through the constructors/destructors of the member
2235// variables used to implement the mock methods.
2236MockFoo::MockFoo() {}
2237MockFoo::~MockFoo() {}
2238```
2239
2240## Forcing a Verification ##
2241
2242When it's being destoyed, your friendly mock object will automatically
2243verify that all expectations on it have been satisfied, and will
2244generate [Google Test](http://code.google.com/p/googletest/) failures
2245if not. This is convenient as it leaves you with one less thing to
2246worry about. That is, unless you are not sure if your mock object will
2247be destoyed.
2248
2249How could it be that your mock object won't eventually be destroyed?
2250Well, it might be created on the heap and owned by the code you are
2251testing. Suppose there's a bug in that code and it doesn't delete the
2252mock object properly - you could end up with a passing test when
2253there's actually a bug.
2254
2255Using a heap checker is a good idea and can alleviate the concern, but
2256its implementation may not be 100% reliable. So, sometimes you do want
2257to _force_ Google Mock to verify a mock object before it is
2258(hopefully) destructed. You can do this with
2259`Mock::VerifyAndClearExpectations(&mock_object)`:
2260
2261```
2262TEST(MyServerTest, ProcessesRequest) {
2263  using ::testing::Mock;
2264
2265  MockFoo* const foo = new MockFoo;
2266  EXPECT_CALL(*foo, ...)...;
2267  // ... other expectations ...
2268
2269  // server now owns foo.
2270  MyServer server(foo);
2271  server.ProcessRequest(...);
2272
2273  // In case that server's destructor will forget to delete foo,
2274  // this will verify the expectations anyway.
2275  Mock::VerifyAndClearExpectations(foo);
2276}  // server is destroyed when it goes out of scope here.
2277```
2278
2279**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a
2280`bool` to indicate whether the verification was successful (`true` for
2281yes), so you can wrap that function call inside a `ASSERT_TRUE()` if
2282there is no point going further when the verification has failed.
2283
2284## Using Check Points ##
2285
2286Sometimes you may want to "reset" a mock object at various check
2287points in your test: at each check point, you verify that all existing
2288expectations on the mock object have been satisfied, and then you set
2289some new expectations on it as if it's newly created. This allows you
2290to work with a mock object in "phases" whose sizes are each
2291manageable.
2292
2293One such scenario is that in your test's `SetUp()` function, you may
2294want to put the object you are testing into a certain state, with the
2295help from a mock object. Once in the desired state, you want to clear
2296all expectations on the mock, such that in the `TEST_F` body you can
2297set fresh expectations on it.
2298
2299As you may have figured out, the `Mock::VerifyAndClearExpectations()`
2300function we saw in the previous recipe can help you here. Or, if you
2301are using `ON_CALL()` to set default actions on the mock object and
2302want to clear the default actions as well, use
2303`Mock::VerifyAndClear(&mock_object)` instead. This function does what
2304`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the
2305same `bool`, **plus** it clears the `ON_CALL()` statements on
2306`mock_object` too.
2307
2308Another trick you can use to achieve the same effect is to put the
2309expectations in sequences and insert calls to a dummy "check-point"
2310function at specific places. Then you can verify that the mock
2311function calls do happen at the right time. For example, if you are
2312exercising code:
2313
2314```
2315Foo(1);
2316Foo(2);
2317Foo(3);
2318```
2319
2320and want to verify that `Foo(1)` and `Foo(3)` both invoke
2321`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write:
2322
2323```
2324using ::testing::MockFunction;
2325
2326TEST(FooTest, InvokesBarCorrectly) {
2327  MyMock mock;
2328  // Class MockFunction<F> has exactly one mock method.  It is named
2329  // Call() and has type F.
2330  MockFunction<void(string check_point_name)> check;
2331  {
2332    InSequence s;
2333
2334    EXPECT_CALL(mock, Bar("a"));
2335    EXPECT_CALL(check, Call("1"));
2336    EXPECT_CALL(check, Call("2"));
2337    EXPECT_CALL(mock, Bar("a"));
2338  }
2339  Foo(1);
2340  check.Call("1");
2341  Foo(2);
2342  check.Call("2");
2343  Foo(3);
2344}
2345```
2346
2347The expectation spec says that the first `Bar("a")` must happen before
2348check point "1", the second `Bar("a")` must happen after check point "2",
2349and nothing should happen between the two check points. The explicit
2350check points make it easy to tell which `Bar("a")` is called by which
2351call to `Foo()`.
2352
2353## Mocking Destructors ##
2354
2355Sometimes you want to make sure a mock object is destructed at the
2356right time, e.g. after `bar->A()` is called but before `bar->B()` is
2357called. We already know that you can specify constraints on the order
2358of mock function calls, so all we need to do is to mock the destructor
2359of the mock function.
2360
2361This sounds simple, except for one problem: a destructor is a special
2362function with special syntax and special semantics, and the
2363`MOCK_METHOD0` macro doesn't work for it:
2364
2365```
2366  MOCK_METHOD0(~MockFoo, void());  // Won't compile!
2367```
2368
2369The good news is that you can use a simple pattern to achieve the same
2370effect. First, add a mock function `Die()` to your mock class and call
2371it in the destructor, like this:
2372
2373```
2374class MockFoo : public Foo {
2375  ...
2376  // Add the following two lines to the mock class.
2377  MOCK_METHOD0(Die, void());
2378  virtual ~MockFoo() { Die(); }
2379};
2380```
2381
2382(If the name `Die()` clashes with an existing symbol, choose another
2383name.) Now, we have translated the problem of testing when a `MockFoo`
2384object dies to testing when its `Die()` method is called:
2385
2386```
2387  MockFoo* foo = new MockFoo;
2388  MockBar* bar = new MockBar;
2389  ...
2390  {
2391    InSequence s;
2392
2393    // Expects *foo to die after bar->A() and before bar->B().
2394    EXPECT_CALL(*bar, A());
2395    EXPECT_CALL(*foo, Die());
2396    EXPECT_CALL(*bar, B());
2397  }
2398```
2399
2400And that's that.
2401
2402## Using Google Mock and Threads ##
2403
2404**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on
2405platforms where Google Mock is thread-safe. Currently these are only
2406platforms that support the pthreads library (this includes Linux and Mac).
2407To make it thread-safe on other platforms we only need to implement
2408some synchronization operations in `"gtest/internal/gtest-port.h"`.
2409
2410In a **unit** test, it's best if you could isolate and test a piece of
2411code in a single-threaded context. That avoids race conditions and
2412dead locks, and makes debugging your test much easier.
2413
2414Yet many programs are multi-threaded, and sometimes to test something
2415we need to pound on it from more than one thread. Google Mock works
2416for this purpose too.
2417
2418Remember the steps for using a mock:
2419
2420  1. Create a mock object `foo`.
2421  1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`.
2422  1. The code under test calls methods of `foo`.
2423  1. Optionally, verify and reset the mock.
2424  1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.
2425
2426If you follow the following simple rules, your mocks and threads can
2427live happily togeter:
2428
2429  * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow.
2430  * Obviously, you can do step #1 without locking.
2431  * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh?
2432  * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic.
2433
2434If you violate the rules (for example, if you set expectations on a
2435mock while another thread is calling its methods), you get undefined
2436behavior. That's not fun, so don't do it.
2437
2438Google Mock guarantees that the action for a mock function is done in
2439the same thread that called the mock function. For example, in
2440
2441```
2442  EXPECT_CALL(mock, Foo(1))
2443      .WillOnce(action1);
2444  EXPECT_CALL(mock, Foo(2))
2445      .WillOnce(action2);
2446```
2447
2448if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2,
2449Google Mock will execute `action1` in thread 1 and `action2` in thread
24502.
2451
2452Google Mock does _not_ impose a sequence on actions performed in
2453different threads (doing so may create deadlocks as the actions may
2454need to cooperate). This means that the execution of `action1` and
2455`action2` in the above example _may_ interleave. If this is a problem,
2456you should add proper synchronization logic to `action1` and `action2`
2457to make the test thread-safe.
2458
2459
2460Also, remember that `DefaultValue<T>` is a global resource that
2461potentially affects _all_ living mock objects in your
2462program. Naturally, you won't want to mess with it from multiple
2463threads or when there still are mocks in action.
2464
2465## Controlling How Much Information Google Mock Prints ##
2466
2467When Google Mock sees something that has the potential of being an
2468error (e.g. a mock function with no expectation is called, a.k.a. an
2469uninteresting call, which is allowed but perhaps you forgot to
2470explicitly ban the call), it prints some warning messages, including
2471the arguments of the function and the return value. Hopefully this
2472will remind you to take a look and see if there is indeed a problem.
2473
2474Sometimes you are confident that your tests are correct and may not
2475appreciate such friendly messages. Some other times, you are debugging
2476your tests or learning about the behavior of the code you are testing,
2477and wish you could observe every mock call that happens (including
2478argument values and the return value). Clearly, one size doesn't fit
2479all.
2480
2481You can control how much Google Mock tells you using the
2482`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string
2483with three possible values:
2484
2485  * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros.
2486  * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default.
2487  * `error`: Google Mock will print errors only (least verbose).
2488
2489Alternatively, you can adjust the value of that flag from within your
2490tests like so:
2491
2492```
2493  ::testing::FLAGS_gmock_verbose = "error";
2494```
2495
2496Now, judiciously use the right flag to enable Google Mock serve you better!
2497
2498## Gaining Super Vision into Mock Calls ##
2499
2500You have a test using Google Mock. It fails: Google Mock tells you
2501that some expectations aren't satisfied. However, you aren't sure why:
2502Is there a typo somewhere in the matchers? Did you mess up the order
2503of the `EXPECT_CALL`s? Or is the code under test doing something
2504wrong?  How can you find out the cause?
2505
2506Won't it be nice if you have X-ray vision and can actually see the
2507trace of all `EXPECT_CALL`s and mock method calls as they are made?
2508For each call, would you like to see its actual argument values and
2509which `EXPECT_CALL` Google Mock thinks it matches?
2510
2511You can unlock this power by running your test with the
2512`--gmock_verbose=info` flag. For example, given the test program:
2513
2514```
2515using testing::_;
2516using testing::HasSubstr;
2517using testing::Return;
2518
2519class MockFoo {
2520 public:
2521  MOCK_METHOD2(F, void(const string& x, const string& y));
2522};
2523
2524TEST(Foo, Bar) {
2525  MockFoo mock;
2526  EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return());
2527  EXPECT_CALL(mock, F("a", "b"));
2528  EXPECT_CALL(mock, F("c", HasSubstr("d")));
2529
2530  mock.F("a", "good");
2531  mock.F("a", "b");
2532}
2533```
2534
2535if you run it with `--gmock_verbose=info`, you will see this output:
2536
2537```
2538[ RUN      ] Foo.Bar
2539
2540foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked
2541foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked
2542foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked
2543foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))...
2544    Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good")
2545foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))...
2546    Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b")
2547foo_test.cc:16: Failure
2548Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))...
2549         Expected: to be called once
2550           Actual: never called - unsatisfied and active
2551[  FAILED  ] Foo.Bar
2552```
2553
2554Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo
2555and should actually be `"a"`. With the above message, you should see
2556that the actual `F("a", "good")` call is matched by the first
2557`EXPECT_CALL`, not the third as you thought. From that it should be
2558obvious that the third `EXPECT_CALL` is written wrong. Case solved.
2559
2560## Running Tests in Emacs ##
2561
2562If you build and run your tests in Emacs, the source file locations of
2563Google Mock and [Google Test](http://code.google.com/p/googletest/)
2564errors will be highlighted. Just press `<Enter>` on one of them and
2565you'll be taken to the offending line. Or, you can just type `C-x ``
2566to jump to the next error.
2567
2568To make it even easier, you can add the following lines to your
2569`~/.emacs` file:
2570
2571```
2572(global-set-key "\M-m"   'compile)  ; m is for make
2573(global-set-key [M-down] 'next-error)
2574(global-set-key [M-up]   '(lambda () (interactive) (next-error -1)))
2575```
2576
2577Then you can type `M-m` to start a build, or `M-up`/`M-down` to move
2578back and forth between errors.
2579
2580## Fusing Google Mock Source Files ##
2581
2582Google Mock's implementation consists of dozens of files (excluding
2583its own tests).  Sometimes you may want them to be packaged up in
2584fewer files instead, such that you can easily copy them to a new
2585machine and start hacking there.  For this we provide an experimental
2586Python script `fuse_gmock_files.py` in the `scripts/` directory
2587(starting with release 1.2.0).  Assuming you have Python 2.4 or above
2588installed on your machine, just go to that directory and run
2589```
2590python fuse_gmock_files.py OUTPUT_DIR
2591```
2592
2593and you should see an `OUTPUT_DIR` directory being created with files
2594`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it.
2595These three files contain everything you need to use Google Mock (and
2596Google Test).  Just copy them to anywhere you want and you are ready
2597to write tests and use mocks.  You can use the
2598[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests
2599against them.
2600
2601# Extending Google Mock #
2602
2603## Writing New Matchers Quickly ##
2604
2605The `MATCHER*` family of macros can be used to define custom matchers
2606easily.  The syntax:
2607
2608```
2609MATCHER(name, description_string_expression) { statements; }
2610```
2611
2612will define a matcher with the given name that executes the
2613statements, which must return a `bool` to indicate if the match
2614succeeds.  Inside the statements, you can refer to the value being
2615matched by `arg`, and refer to its type by `arg_type`.
2616
2617The description string is a `string`-typed expression that documents
2618what the matcher does, and is used to generate the failure message
2619when the match fails.  It can (and should) reference the special
2620`bool` variable `negation`, and should evaluate to the description of
2621the matcher when `negation` is `false`, or that of the matcher's
2622negation when `negation` is `true`.
2623
2624For convenience, we allow the description string to be empty (`""`),
2625in which case Google Mock will use the sequence of words in the
2626matcher name as the description.
2627
2628For example:
2629```
2630MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
2631```
2632allows you to write
2633```
2634  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.
2635  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
2636```
2637or,
2638```
2639using ::testing::Not;
2640...
2641  EXPECT_THAT(some_expression, IsDivisibleBy7());
2642  EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));
2643```
2644If the above assertions fail, they will print something like:
2645```
2646  Value of: some_expression
2647  Expected: is divisible by 7
2648    Actual: 27
2649...
2650  Value of: some_other_expression
2651  Expected: not (is divisible by 7)
2652    Actual: 21
2653```
2654where the descriptions `"is divisible by 7"` and `"not (is divisible
2655by 7)"` are automatically calculated from the matcher name
2656`IsDivisibleBy7`.
2657
2658As you may have noticed, the auto-generated descriptions (especially
2659those for the negation) may not be so great. You can always override
2660them with a string expression of your own:
2661```
2662MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") +
2663                        " divisible by 7") {
2664  return (arg % 7) == 0;
2665}
2666```
2667
2668Optionally, you can stream additional information to a hidden argument
2669named `result_listener` to explain the match result. For example, a
2670better definition of `IsDivisibleBy7` is:
2671```
2672MATCHER(IsDivisibleBy7, "") {
2673  if ((arg % 7) == 0)
2674    return true;
2675
2676  *result_listener << "the remainder is " << (arg % 7);
2677  return false;
2678}
2679```
2680
2681With this definition, the above assertion will give a better message:
2682```
2683  Value of: some_expression
2684  Expected: is divisible by 7
2685    Actual: 27 (the remainder is 6)
2686```
2687
2688You should let `MatchAndExplain()` print _any additional information_
2689that can help a user understand the match result. Note that it should
2690explain why the match succeeds in case of a success (unless it's
2691obvious) - this is useful when the matcher is used inside
2692`Not()`. There is no need to print the argument value itself, as
2693Google Mock already prints it for you.
2694
2695**Notes:**
2696
2697  1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you).  This allows the matcher to be polymorphic.  For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`.  In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on.
2698  1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock.
2699
2700## Writing New Parameterized Matchers Quickly ##
2701
2702Sometimes you'll want to define a matcher that has parameters.  For that you
2703can use the macro:
2704```
2705MATCHER_P(name, param_name, description_string) { statements; }
2706```
2707where the description string can be either `""` or a string expression
2708that references `negation` and `param_name`.
2709
2710For example:
2711```
2712MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2713```
2714will allow you to write:
2715```
2716  EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2717```
2718which may lead to this message (assuming `n` is 10):
2719```
2720  Value of: Blah("a")
2721  Expected: has absolute value 10
2722    Actual: -9
2723```
2724
2725Note that both the matcher description and its parameter are
2726printed, making the message human-friendly.
2727
2728In the matcher definition body, you can write `foo_type` to
2729reference the type of a parameter named `foo`.  For example, in the
2730body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write
2731`value_type` to refer to the type of `value`.
2732
2733Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to
2734`MATCHER_P10` to support multi-parameter matchers:
2735```
2736MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }
2737```
2738
2739Please note that the custom description string is for a particular
2740**instance** of the matcher, where the parameters have been bound to
2741actual values.  Therefore usually you'll want the parameter values to
2742be part of the description.  Google Mock lets you do that by
2743referencing the matcher parameters in the description string
2744expression.
2745
2746For example,
2747```
2748  using ::testing::PrintToString;
2749  MATCHER_P2(InClosedRange, low, hi,
2750             std::string(negation ? "isn't" : "is") + " in range [" +
2751             PrintToString(low) + ", " + PrintToString(hi) + "]") {
2752    return low <= arg && arg <= hi;
2753  }
2754  ...
2755  EXPECT_THAT(3, InClosedRange(4, 6));
2756```
2757would generate a failure that contains the message:
2758```
2759  Expected: is in range [4, 6]
2760```
2761
2762If you specify `""` as the description, the failure message will
2763contain the sequence of words in the matcher name followed by the
2764parameter values printed as a tuple.  For example,
2765```
2766  MATCHER_P2(InClosedRange, low, hi, "") { ... }
2767  ...
2768  EXPECT_THAT(3, InClosedRange(4, 6));
2769```
2770would generate a failure that contains the text:
2771```
2772  Expected: in closed range (4, 6)
2773```
2774
2775For the purpose of typing, you can view
2776```
2777MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
2778```
2779as shorthand for
2780```
2781template <typename p1_type, ..., typename pk_type>
2782FooMatcherPk<p1_type, ..., pk_type>
2783Foo(p1_type p1, ..., pk_type pk) { ... }
2784```
2785
2786When you write `Foo(v1, ..., vk)`, the compiler infers the types of
2787the parameters `v1`, ..., and `vk` for you.  If you are not happy with
2788the result of the type inference, you can specify the types by
2789explicitly instantiating the template, as in `Foo<long, bool>(5, false)`.
2790As said earlier, you don't get to (or need to) specify
2791`arg_type` as that's determined by the context in which the matcher
2792is used.
2793
2794You can assign the result of expression `Foo(p1, ..., pk)` to a
2795variable of type `FooMatcherPk<p1_type, ..., pk_type>`.  This can be
2796useful when composing matchers.  Matchers that don't have a parameter
2797or have only one parameter have special types: you can assign `Foo()`
2798to a `FooMatcher`-typed variable, and assign `Foo(p)` to a
2799`FooMatcherP<p_type>`-typed variable.
2800
2801While you can instantiate a matcher template with reference types,
2802passing the parameters by pointer usually makes your code more
2803readable.  If, however, you still want to pass a parameter by
2804reference, be aware that in the failure message generated by the
2805matcher you will see the value of the referenced object but not its
2806address.
2807
2808You can overload matchers with different numbers of parameters:
2809```
2810MATCHER_P(Blah, a, description_string_1) { ... }
2811MATCHER_P2(Blah, a, b, description_string_2) { ... }
2812```
2813
2814While it's tempting to always use the `MATCHER*` macros when defining
2815a new matcher, you should also consider implementing
2816`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see
2817the recipes that follow), especially if you need to use the matcher a
2818lot.  While these approaches require more work, they give you more
2819control on the types of the value being matched and the matcher
2820parameters, which in general leads to better compiler error messages
2821that pay off in the long run.  They also allow overloading matchers
2822based on parameter types (as opposed to just based on the number of
2823parameters).
2824
2825## Writing New Monomorphic Matchers ##
2826
2827A matcher of argument type `T` implements
2828`::testing::MatcherInterface<T>` and does two things: it tests whether a
2829value of type `T` matches the matcher, and can describe what kind of
2830values it matches. The latter ability is used for generating readable
2831error messages when expectations are violated.
2832
2833The interface looks like this:
2834
2835```
2836class MatchResultListener {
2837 public:
2838  ...
2839  // Streams x to the underlying ostream; does nothing if the ostream
2840  // is NULL.
2841  template <typename T>
2842  MatchResultListener& operator<<(const T& x);
2843
2844  // Returns the underlying ostream.
2845  ::std::ostream* stream();
2846};
2847
2848template <typename T>
2849class MatcherInterface {
2850 public:
2851  virtual ~MatcherInterface();
2852
2853  // Returns true iff the matcher matches x; also explains the match
2854  // result to 'listener'.
2855  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
2856
2857  // Describes this matcher to an ostream.
2858  virtual void DescribeTo(::std::ostream* os) const = 0;
2859
2860  // Describes the negation of this matcher to an ostream.
2861  virtual void DescribeNegationTo(::std::ostream* os) const;
2862};
2863```
2864
2865If you need a custom matcher but `Truly()` is not a good option (for
2866example, you may not be happy with the way `Truly(predicate)`
2867describes itself, or you may want your matcher to be polymorphic as
2868`Eq(value)` is), you can define a matcher to do whatever you want in
2869two steps: first implement the matcher interface, and then define a
2870factory function to create a matcher instance. The second step is not
2871strictly needed but it makes the syntax of using the matcher nicer.
2872
2873For example, you can define a matcher to test whether an `int` is
2874divisible by 7 and then use it like this:
2875```
2876using ::testing::MakeMatcher;
2877using ::testing::Matcher;
2878using ::testing::MatcherInterface;
2879using ::testing::MatchResultListener;
2880
2881class DivisibleBy7Matcher : public MatcherInterface<int> {
2882 public:
2883  virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
2884    return (n % 7) == 0;
2885  }
2886
2887  virtual void DescribeTo(::std::ostream* os) const {
2888    *os << "is divisible by 7";
2889  }
2890
2891  virtual void DescribeNegationTo(::std::ostream* os) const {
2892    *os << "is not divisible by 7";
2893  }
2894};
2895
2896inline Matcher<int> DivisibleBy7() {
2897  return MakeMatcher(new DivisibleBy7Matcher);
2898}
2899...
2900
2901  EXPECT_CALL(foo, Bar(DivisibleBy7()));
2902```
2903
2904You may improve the matcher message by streaming additional
2905information to the `listener` argument in `MatchAndExplain()`:
2906
2907```
2908class DivisibleBy7Matcher : public MatcherInterface<int> {
2909 public:
2910  virtual bool MatchAndExplain(int n,
2911                               MatchResultListener* listener) const {
2912    const int remainder = n % 7;
2913    if (remainder != 0) {
2914      *listener << "the remainder is " << remainder;
2915    }
2916    return remainder == 0;
2917  }
2918  ...
2919};
2920```
2921
2922Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this:
2923```
2924Value of: x
2925Expected: is divisible by 7
2926  Actual: 23 (the remainder is 2)
2927```
2928
2929## Writing New Polymorphic Matchers ##
2930
2931You've learned how to write your own matchers in the previous
2932recipe. Just one problem: a matcher created using `MakeMatcher()` only
2933works for one particular type of arguments. If you want a
2934_polymorphic_ matcher that works with arguments of several types (for
2935instance, `Eq(x)` can be used to match a `value` as long as `value` ==
2936`x` compiles -- `value` and `x` don't have to share the same type),
2937you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit
2938involved.
2939
2940Fortunately, most of the time you can define a polymorphic matcher
2941easily with the help of `MakePolymorphicMatcher()`. Here's how you can
2942define `NotNull()` as an example:
2943
2944```
2945using ::testing::MakePolymorphicMatcher;
2946using ::testing::MatchResultListener;
2947using ::testing::NotNull;
2948using ::testing::PolymorphicMatcher;
2949
2950class NotNullMatcher {
2951 public:
2952  // To implement a polymorphic matcher, first define a COPYABLE class
2953  // that has three members MatchAndExplain(), DescribeTo(), and
2954  // DescribeNegationTo(), like the following.
2955
2956  // In this example, we want to use NotNull() with any pointer, so
2957  // MatchAndExplain() accepts a pointer of any type as its first argument.
2958  // In general, you can define MatchAndExplain() as an ordinary method or
2959  // a method template, or even overload it.
2960  template <typename T>
2961  bool MatchAndExplain(T* p,
2962                       MatchResultListener* /* listener */) const {
2963    return p != NULL;
2964  }
2965
2966  // Describes the property of a value matching this matcher.
2967  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
2968
2969  // Describes the property of a value NOT matching this matcher.
2970  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
2971};
2972
2973// To construct a polymorphic matcher, pass an instance of the class
2974// to MakePolymorphicMatcher().  Note the return type.
2975inline PolymorphicMatcher<NotNullMatcher> NotNull() {
2976  return MakePolymorphicMatcher(NotNullMatcher());
2977}
2978...
2979
2980  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.
2981```
2982
2983**Note:** Your polymorphic matcher class does **not** need to inherit from
2984`MatcherInterface` or any other class, and its methods do **not** need
2985to be virtual.
2986
2987Like in a monomorphic matcher, you may explain the match result by
2988streaming additional information to the `listener` argument in
2989`MatchAndExplain()`.
2990
2991## Writing New Cardinalities ##
2992
2993A cardinality is used in `Times()` to tell Google Mock how many times
2994you expect a call to occur. It doesn't have to be exact. For example,
2995you can say `AtLeast(5)` or `Between(2, 4)`.
2996
2997If the built-in set of cardinalities doesn't suit you, you are free to
2998define your own by implementing the following interface (in namespace
2999`testing`):
3000
3001```
3002class CardinalityInterface {
3003 public:
3004  virtual ~CardinalityInterface();
3005
3006  // Returns true iff call_count calls will satisfy this cardinality.
3007  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
3008
3009  // Returns true iff call_count calls will saturate this cardinality.
3010  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
3011
3012  // Describes self to an ostream.
3013  virtual void DescribeTo(::std::ostream* os) const = 0;
3014};
3015```
3016
3017For example, to specify that a call must occur even number of times,
3018you can write
3019
3020```
3021using ::testing::Cardinality;
3022using ::testing::CardinalityInterface;
3023using ::testing::MakeCardinality;
3024
3025class EvenNumberCardinality : public CardinalityInterface {
3026 public:
3027  virtual bool IsSatisfiedByCallCount(int call_count) const {
3028    return (call_count % 2) == 0;
3029  }
3030
3031  virtual bool IsSaturatedByCallCount(int call_count) const {
3032    return false;
3033  }
3034
3035  virtual void DescribeTo(::std::ostream* os) const {
3036    *os << "called even number of times";
3037  }
3038};
3039
3040Cardinality EvenNumber() {
3041  return MakeCardinality(new EvenNumberCardinality);
3042}
3043...
3044
3045  EXPECT_CALL(foo, Bar(3))
3046      .Times(EvenNumber());
3047```
3048
3049## Writing New Actions Quickly ##
3050
3051If the built-in actions don't work for you, and you find it
3052inconvenient to use `Invoke()`, you can use a macro from the `ACTION*`
3053family to quickly define a new action that can be used in your code as
3054if it's a built-in action.
3055
3056By writing
3057```
3058ACTION(name) { statements; }
3059```
3060in a namespace scope (i.e. not inside a class or function), you will
3061define an action with the given name that executes the statements.
3062The value returned by `statements` will be used as the return value of
3063the action.  Inside the statements, you can refer to the K-th
3064(0-based) argument of the mock function as `argK`.  For example:
3065```
3066ACTION(IncrementArg1) { return ++(*arg1); }
3067```
3068allows you to write
3069```
3070... WillOnce(IncrementArg1());
3071```
3072
3073Note that you don't need to specify the types of the mock function
3074arguments.  Rest assured that your code is type-safe though:
3075you'll get a compiler error if `*arg1` doesn't support the `++`
3076operator, or if the type of `++(*arg1)` isn't compatible with the mock
3077function's return type.
3078
3079Another example:
3080```
3081ACTION(Foo) {
3082  (*arg2)(5);
3083  Blah();
3084  *arg1 = 0;
3085  return arg0;
3086}
3087```
3088defines an action `Foo()` that invokes argument #2 (a function pointer)
3089with 5, calls function `Blah()`, sets the value pointed to by argument
3090#1 to 0, and returns argument #0.
3091
3092For more convenience and flexibility, you can also use the following
3093pre-defined symbols in the body of `ACTION`:
3094
3095| `argK_type` | The type of the K-th (0-based) argument of the mock function |
3096|:------------|:-------------------------------------------------------------|
3097| `args`      | All arguments of the mock function as a tuple                |
3098| `args_type` | The type of all arguments of the mock function as a tuple    |
3099| `return_type` | The return type of the mock function                         |
3100| `function_type` | The type of the mock function                                |
3101
3102For example, when using an `ACTION` as a stub action for mock function:
3103```
3104int DoSomething(bool flag, int* ptr);
3105```
3106we have:
3107| **Pre-defined Symbol** | **Is Bound To** |
3108|:-----------------------|:----------------|
3109| `arg0`                 | the value of `flag` |
3110| `arg0_type`            | the type `bool` |
3111| `arg1`                 | the value of `ptr` |
3112| `arg1_type`            | the type `int*` |
3113| `args`                 | the tuple `(flag, ptr)` |
3114| `args_type`            | the type `std::tr1::tuple<bool, int*>` |
3115| `return_type`          | the type `int`  |
3116| `function_type`        | the type `int(bool, int*)` |
3117
3118## Writing New Parameterized Actions Quickly ##
3119
3120Sometimes you'll want to parameterize an action you define.  For that
3121we have another macro
3122```
3123ACTION_P(name, param) { statements; }
3124```
3125
3126For example,
3127```
3128ACTION_P(Add, n) { return arg0 + n; }
3129```
3130will allow you to write
3131```
3132// Returns argument #0 + 5.
3133... WillOnce(Add(5));
3134```
3135
3136For convenience, we use the term _arguments_ for the values used to
3137invoke the mock function, and the term _parameters_ for the values
3138used to instantiate an action.
3139
3140Note that you don't need to provide the type of the parameter either.
3141Suppose the parameter is named `param`, you can also use the
3142Google-Mock-defined symbol `param_type` to refer to the type of the
3143parameter as inferred by the compiler.  For example, in the body of
3144`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`.
3145
3146Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support
3147multi-parameter actions.  For example,
3148```
3149ACTION_P2(ReturnDistanceTo, x, y) {
3150  double dx = arg0 - x;
3151  double dy = arg1 - y;
3152  return sqrt(dx*dx + dy*dy);
3153}
3154```
3155lets you write
3156```
3157... WillOnce(ReturnDistanceTo(5.0, 26.5));
3158```
3159
3160You can view `ACTION` as a degenerated parameterized action where the
3161number of parameters is 0.
3162
3163You can also easily define actions overloaded on the number of parameters:
3164```
3165ACTION_P(Plus, a) { ... }
3166ACTION_P2(Plus, a, b) { ... }
3167```
3168
3169## Restricting the Type of an Argument or Parameter in an ACTION ##
3170
3171For maximum brevity and reusability, the `ACTION*` macros don't ask
3172you to provide the types of the mock function arguments and the action
3173parameters.  Instead, we let the compiler infer the types for us.
3174
3175Sometimes, however, we may want to be more explicit about the types.
3176There are several tricks to do that.  For example:
3177```
3178ACTION(Foo) {
3179  // Makes sure arg0 can be converted to int.
3180  int n = arg0;
3181  ... use n instead of arg0 here ...
3182}
3183
3184ACTION_P(Bar, param) {
3185  // Makes sure the type of arg1 is const char*.
3186  ::testing::StaticAssertTypeEq<const char*, arg1_type>();
3187
3188  // Makes sure param can be converted to bool.
3189  bool flag = param;
3190}
3191```
3192where `StaticAssertTypeEq` is a compile-time assertion in Google Test
3193that verifies two types are the same.
3194
3195## Writing New Action Templates Quickly ##
3196
3197Sometimes you want to give an action explicit template parameters that
3198cannot be inferred from its value parameters.  `ACTION_TEMPLATE()`
3199supports that and can be viewed as an extension to `ACTION()` and
3200`ACTION_P*()`.
3201
3202The syntax:
3203```
3204ACTION_TEMPLATE(ActionName,
3205                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
3206                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
3207```
3208
3209defines an action template that takes _m_ explicit template parameters
3210and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is
3211between 0 and 10.  `name_i` is the name of the i-th template
3212parameter, and `kind_i` specifies whether it's a `typename`, an
3213integral constant, or a template.  `p_i` is the name of the i-th value
3214parameter.
3215
3216Example:
3217```
3218// DuplicateArg<k, T>(output) converts the k-th argument of the mock
3219// function to type T and copies it to *output.
3220ACTION_TEMPLATE(DuplicateArg,
3221                // Note the comma between int and k:
3222                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
3223                AND_1_VALUE_PARAMS(output)) {
3224  *output = T(std::tr1::get<k>(args));
3225}
3226```
3227
3228To create an instance of an action template, write:
3229```
3230  ActionName<t1, ..., t_m>(v1, ..., v_n)
3231```
3232where the `t`s are the template arguments and the
3233`v`s are the value arguments.  The value argument
3234types are inferred by the compiler.  For example:
3235```
3236using ::testing::_;
3237...
3238  int n;
3239  EXPECT_CALL(mock, Foo(_, _))
3240      .WillOnce(DuplicateArg<1, unsigned char>(&n));
3241```
3242
3243If you want to explicitly specify the value argument types, you can
3244provide additional template arguments:
3245```
3246  ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
3247```
3248where `u_i` is the desired type of `v_i`.
3249
3250`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the
3251number of value parameters, but not on the number of template
3252parameters.  Without the restriction, the meaning of the following is
3253unclear:
3254
3255```
3256  OverloadedAction<int, bool>(x);
3257```
3258
3259Are we using a single-template-parameter action where `bool` refers to
3260the type of `x`, or a two-template-parameter action where the compiler
3261is asked to infer the type of `x`?
3262
3263## Using the ACTION Object's Type ##
3264
3265If you are writing a function that returns an `ACTION` object, you'll
3266need to know its type.  The type depends on the macro used to define
3267the action and the parameter types.  The rule is relatively simple:
3268| **Given Definition** | **Expression** | **Has Type** |
3269|:---------------------|:---------------|:-------------|
3270| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
3271| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` |   `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
3272| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
3273| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` |
3274| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
3275| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` |
3276| ...                  | ...            | ...          |
3277
3278Note that we have to pick different suffixes (`Action`, `ActionP`,
3279`ActionP2`, and etc) for actions with different numbers of value
3280parameters, or the action definitions cannot be overloaded on the
3281number of them.
3282
3283## Writing New Monomorphic Actions ##
3284
3285While the `ACTION*` macros are very convenient, sometimes they are
3286inappropriate.  For example, despite the tricks shown in the previous
3287recipes, they don't let you directly specify the types of the mock
3288function arguments and the action parameters, which in general leads
3289to unoptimized compiler error messages that can baffle unfamiliar
3290users.  They also don't allow overloading actions based on parameter
3291types without jumping through some hoops.
3292
3293An alternative to the `ACTION*` macros is to implement
3294`::testing::ActionInterface<F>`, where `F` is the type of the mock
3295function in which the action will be used. For example:
3296
3297```
3298template <typename F>class ActionInterface {
3299 public:
3300  virtual ~ActionInterface();
3301
3302  // Performs the action.  Result is the return type of function type
3303  // F, and ArgumentTuple is the tuple of arguments of F.
3304  //
3305  // For example, if F is int(bool, const string&), then Result would
3306  // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>.
3307  virtual Result Perform(const ArgumentTuple& args) = 0;
3308};
3309
3310using ::testing::_;
3311using ::testing::Action;
3312using ::testing::ActionInterface;
3313using ::testing::MakeAction;
3314
3315typedef int IncrementMethod(int*);
3316
3317class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
3318 public:
3319  virtual int Perform(const tr1::tuple<int*>& args) {
3320    int* p = tr1::get<0>(args);  // Grabs the first argument.
3321    return *p++;
3322  }
3323};
3324
3325Action<IncrementMethod> IncrementArgument() {
3326  return MakeAction(new IncrementArgumentAction);
3327}
3328...
3329
3330  EXPECT_CALL(foo, Baz(_))
3331      .WillOnce(IncrementArgument());
3332
3333  int n = 5;
3334  foo.Baz(&n);  // Should return 5 and change n to 6.
3335```
3336
3337## Writing New Polymorphic Actions ##
3338
3339The previous recipe showed you how to define your own action. This is
3340all good, except that you need to know the type of the function in
3341which the action will be used. Sometimes that can be a problem. For
3342example, if you want to use the action in functions with _different_
3343types (e.g. like `Return()` and `SetArgPointee()`).
3344
3345If an action can be used in several types of mock functions, we say
3346it's _polymorphic_. The `MakePolymorphicAction()` function template
3347makes it easy to define such an action:
3348
3349```
3350namespace testing {
3351
3352template <typename Impl>
3353PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);
3354
3355}  // namespace testing
3356```
3357
3358As an example, let's define an action that returns the second argument
3359in the mock function's argument list. The first step is to define an
3360implementation class:
3361
3362```
3363class ReturnSecondArgumentAction {
3364 public:
3365  template <typename Result, typename ArgumentTuple>
3366  Result Perform(const ArgumentTuple& args) const {
3367    // To get the i-th (0-based) argument, use tr1::get<i>(args).
3368    return tr1::get<1>(args);
3369  }
3370};
3371```
3372
3373This implementation class does _not_ need to inherit from any
3374particular class. What matters is that it must have a `Perform()`
3375method template. This method template takes the mock function's
3376arguments as a tuple in a **single** argument, and returns the result of
3377the action. It can be either `const` or not, but must be invokable
3378with exactly one template argument, which is the result type. In other
3379words, you must be able to call `Perform<R>(args)` where `R` is the
3380mock function's return type and `args` is its arguments in a tuple.
3381
3382Next, we use `MakePolymorphicAction()` to turn an instance of the
3383implementation class into the polymorphic action we need. It will be
3384convenient to have a wrapper for this:
3385
3386```
3387using ::testing::MakePolymorphicAction;
3388using ::testing::PolymorphicAction;
3389
3390PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
3391  return MakePolymorphicAction(ReturnSecondArgumentAction());
3392}
3393```
3394
3395Now, you can use this polymorphic action the same way you use the
3396built-in ones:
3397
3398```
3399using ::testing::_;
3400
3401class MockFoo : public Foo {
3402 public:
3403  MOCK_METHOD2(DoThis, int(bool flag, int n));
3404  MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
3405};
3406...
3407
3408  MockFoo foo;
3409  EXPECT_CALL(foo, DoThis(_, _))
3410      .WillOnce(ReturnSecondArgument());
3411  EXPECT_CALL(foo, DoThat(_, _, _))
3412      .WillOnce(ReturnSecondArgument());
3413  ...
3414  foo.DoThis(true, 5);         // Will return 5.
3415  foo.DoThat(1, "Hi", "Bye");  // Will return "Hi".
3416```
3417
3418## Teaching Google Mock How to Print Your Values ##
3419
3420When an uninteresting or unexpected call occurs, Google Mock prints the
3421argument values and the stack trace to help you debug.  Assertion
3422macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in
3423question when the assertion fails.  Google Mock and Google Test do this using
3424Google Test's user-extensible value printer.
3425
3426This printer knows how to print built-in C++ types, native arrays, STL
3427containers, and any type that supports the `<<` operator.  For other
3428types, it prints the raw bytes in the value and hopes that you the
3429user can figure it out.
3430[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values)
3431explains how to extend the printer to do a better job at
3432printing your particular type than to dump the bytes.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_7/Documentation.md
r0r249096
1This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)**
2- **if you use a released version of Google Mock, please read the documentation for that specific version instead.**
3
4  * [ForDummies](V1_7_ForDummies.md) -- start here if you are new to Google Mock.
5  * [CheatSheet](V1_7_CheatSheet.md) -- a quick reference.
6  * [CookBook](V1_7_CookBook.md) -- recipes for doing various tasks using Google Mock.
7  * [FrequentlyAskedQuestions](V1_7_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list.
8
9To contribute code to Google Mock, read:
10
11  * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch.
12  * [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_7/ForDummies.md
r0r249096
1
2
3(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_7_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).)
4
5# What Is Google C++ Mocking Framework? #
6When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc).
7
8**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community:
9
10  * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
11  * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive.
12
13If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks.
14
15**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java.
16
17Using Google Mock involves three basic steps:
18
19  1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class;
20  1. Create some mock objects and specify its expectations and behavior using an intuitive syntax;
21  1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises.
22
23# Why Google Mock? #
24While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_:
25
26  * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it.
27  * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions.
28  * The knowledge you gained from using one mock doesn't transfer to the next.
29
30In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference.
31
32Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you:
33
34  * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid".
35  * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database).
36  * Your tests are brittle as some resources they use are unreliable (e.g. the network).
37  * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one.
38  * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best.
39  * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks.
40
41We encourage you to use Google Mock as:
42
43  * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs!
44  * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators.
45
46# Getting Started #
47Using Google Mock is easy! Inside your C++ source file, just #include `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go.
48
49# A Case for Mock Turtles #
50Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
51
52```
53class Turtle {
54  ...
55  virtual ~Turtle() {}
56  virtual void PenUp() = 0;
57  virtual void PenDown() = 0;
58  virtual void Forward(int distance) = 0;
59  virtual void Turn(int degrees) = 0;
60  virtual void GoTo(int x, int y) = 0;
61  virtual int GetX() const = 0;
62  virtual int GetY() const = 0;
63};
64```
65
66(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.)
67
68You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle.
69
70Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_.
71
72# Writing the Mock Class #
73If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.)
74
75## How to Define It ##
76Using the `Turtle` interface as example, here are the simple steps you need to follow:
77
78  1. Derive a class `MockTurtle` from `Turtle`.
79  1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has.
80  1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so.
81  1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_).
82  1. Repeat until all virtual functions you want to mock are done.
83
84After the process, you should have something like:
85
86```
87#include "gmock/gmock.h"  // Brings in Google Mock.
88class MockTurtle : public Turtle {
89 public:
90  ...
91  MOCK_METHOD0(PenUp, void());
92  MOCK_METHOD0(PenDown, void());
93  MOCK_METHOD1(Forward, void(int distance));
94  MOCK_METHOD1(Turn, void(int degrees));
95  MOCK_METHOD2(GoTo, void(int x, int y));
96  MOCK_CONST_METHOD0(GetX, int());
97  MOCK_CONST_METHOD0(GetY, int());
98};
99```
100
101You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins.
102
103**Tip:** If even this is too much work for you, you'll find the
104`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful.  This command-line
105tool requires that you have Python 2.4 installed.  You give it a C++ file and the name of an abstract class defined in it,
106and it will print the definition of the mock class for you.  Due to the
107complexity of the C++ language, this script may not always work, but
108it can be quite handy when it does.  For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README).
109
110## Where to Put It ##
111When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?)
112
113So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed.
114
115Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does.
116
117# Using Mocks in Tests #
118Once you have a mock class, using it is easy. The typical work flow is:
119
120  1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.).
121  1. Create some mock objects.
122  1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.).
123  1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately.
124  1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.
125
126Here's an example:
127
128```
129#include "path/to/mock-turtle.h"
130#include "gmock/gmock.h"
131#include "gtest/gtest.h"
132using ::testing::AtLeast;                     // #1
133
134TEST(PainterTest, CanDrawSomething) {
135  MockTurtle turtle;                          // #2
136  EXPECT_CALL(turtle, PenDown())              // #3
137      .Times(AtLeast(1));
138
139  Painter painter(&turtle);                   // #4
140
141  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
142}                                             // #5
143
144int main(int argc, char** argv) {
145  // The following line must be executed to initialize Google Mock
146  // (and Google Test) before running the tests.
147  ::testing::InitGoogleMock(&argc, argv);
148  return RUN_ALL_TESTS();
149}
150```
151
152As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this:
153
154```
155path/to/my_test.cc:119: Failure
156Actual function call count doesn't match this expectation:
157Actually: never called;
158Expected: called at least once.
159```
160
161**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation.
162
163**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap.
164
165**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions.
166
167This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier.
168
169Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks.
170
171## Using Google Mock with Any Testing Framework ##
172If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or
173[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to:
174```
175int main(int argc, char** argv) {
176  // The following line causes Google Mock to throw an exception on failure,
177  // which will be interpreted by your testing framework as a test failure.
178  ::testing::GTEST_FLAG(throw_on_failure) = true;
179  ::testing::InitGoogleMock(&argc, argv);
180  ... whatever your testing framework requires ...
181}
182```
183
184This approach has a catch: it makes Google Mock throw an exception
185from a mock object's destructor sometimes.  With some compilers, this
186sometimes causes the test program to crash.  You'll still be able to
187notice that the test has failed, but it's not a graceful failure.
188
189A better solution is to use Google Test's
190[event listener API](http://code.google.com/p/googletest/wiki/AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events)
191to report a test failure to your testing framework properly.  You'll need to
192implement the `OnTestPartResult()` method of the event listener interface, but it
193should be straightforward.
194
195If this turns out to be too much work, we suggest that you stick with
196Google Test, which works with Google Mock seamlessly (in fact, it is
197technically part of Google Mock.).  If there is a reason that you
198cannot use Google Test, please let us know.
199
200# Setting Expectations #
201The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right."
202
203## General Syntax ##
204In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
205
206```
207EXPECT_CALL(mock_object, method(matchers))
208    .Times(cardinality)
209    .WillOnce(action)
210    .WillRepeatedly(action);
211```
212
213The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.)
214
215The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections.
216
217This syntax is designed to make an expectation read like English. For example, you can probably guess that
218
219```
220using ::testing::Return;...
221EXPECT_CALL(turtle, GetX())
222    .Times(5)
223    .WillOnce(Return(100))
224    .WillOnce(Return(150))
225    .WillRepeatedly(Return(200));
226```
227
228says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL).
229
230**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier.
231
232## Matchers: What Arguments Do We Expect? ##
233When a mock function takes arguments, we must specify what arguments we are expecting; for example:
234
235```
236// Expects the turtle to move forward by 100 units.
237EXPECT_CALL(turtle, Forward(100));
238```
239
240Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
241
242```
243using ::testing::_;
244...
245// Expects the turtle to move forward.
246EXPECT_CALL(turtle, Forward(_));
247```
248
249`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected.
250
251A list of built-in matchers can be found in the [CheatSheet](V1_7_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
252
253```
254using ::testing::Ge;...
255EXPECT_CALL(turtle, Forward(Ge(100)));
256```
257
258This checks that the turtle will be told to go forward by at least 100 units.
259
260## Cardinalities: How Many Times Will It Be Called? ##
261The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly.
262
263An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called.
264
265We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_7_CheatSheet.md).
266
267The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember:
268
269  * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
270  * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`.
271  * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`.
272
273**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times?
274
275## Actions: What Should It Do? ##
276Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock.
277
278First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used.
279
280Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
281
282```
283using ::testing::Return;...
284EXPECT_CALL(turtle, GetX())
285    .WillOnce(Return(100))
286    .WillOnce(Return(200))
287    .WillOnce(Return(300));
288```
289
290This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
291
292```
293using ::testing::Return;...
294EXPECT_CALL(turtle, GetY())
295    .WillOnce(Return(100))
296    .WillOnce(Return(200))
297    .WillRepeatedly(Return(300));
298```
299
300says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on.
301
302Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).
303
304What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#Actions).
305
306**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
307
308```
309int n = 100;
310EXPECT_CALL(turtle, GetX())
311.Times(4)
312.WillRepeatedly(Return(n++));
313```
314
315Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_7_CookBook.md).
316
317Time for another quiz! What do you think the following means?
318
319```
320using ::testing::Return;...
321EXPECT_CALL(turtle, GetY())
322.Times(4)
323.WillOnce(Return(100));
324```
325
326Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions.
327
328## Using Multiple Expectations ##
329So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects.
330
331By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:
332
333```
334using ::testing::_;...
335EXPECT_CALL(turtle, Forward(_));  // #1
336EXPECT_CALL(turtle, Forward(10))  // #2
337    .Times(2);
338```
339
340If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation.
341
342**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it.
343
344## Ordered vs Unordered Calls ##
345By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified.
346
347Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
348
349```
350using ::testing::InSequence;...
351TEST(FooTest, DrawsLineSegment) {
352  ...
353  {
354    InSequence dummy;
355
356    EXPECT_CALL(turtle, PenDown());
357    EXPECT_CALL(turtle, Forward(100));
358    EXPECT_CALL(turtle, PenUp());
359  }
360  Foo();
361}
362```
363
364By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant.
365
366In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error.
367
368(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_7_CookBook#Expecting_Partially_Ordered_Calls.md).)
369
370## All Expectations Are Sticky (Unless Said Otherwise) ##
371Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)?
372
373After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
374
375```
376using ::testing::_;...
377EXPECT_CALL(turtle, GoTo(_, _))  // #1
378    .Times(AnyNumber());
379EXPECT_CALL(turtle, GoTo(0, 0))  // #2
380    .Times(2);
381```
382
383Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above.
384
385This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.).
386
387Simple? Let's see if you've really understood it: what does the following code say?
388
389```
390using ::testing::Return;
391...
392for (int i = n; i > 0; i--) {
393  EXPECT_CALL(turtle, GetX())
394      .WillOnce(Return(10*i));
395}
396```
397
398If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful!
399
400One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
401
402```
403using ::testing::Return;
404...
405for (int i = n; i > 0; i--) {
406  EXPECT_CALL(turtle, GetX())
407    .WillOnce(Return(10*i))
408    .RetiresOnSaturation();
409}
410```
411
412And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:
413
414```
415using ::testing::InSequence;
416using ::testing::Return;
417...
418{
419  InSequence s;
420
421  for (int i = 1; i <= n; i++) {
422    EXPECT_CALL(turtle, GetX())
423        .WillOnce(Return(10*i))
424        .RetiresOnSaturation();
425  }
426}
427```
428
429By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call).
430
431## Uninteresting Calls ##
432A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called.
433
434In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure.
435
436# What Now? #
437Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.
438
439Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_7_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
No newline at end of file
trunk/3rdparty/googletest/googlemock/docs/v1_7/FrequentlyAskedQuestions.md
r0r249096
1
2
3Please send your questions to the
4[googlemock](http://groups.google.com/group/googlemock) discussion
5group. If you need help with compiler errors, make sure you have
6tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.
7
8## When I call a method on my mock object, the method for the real object is invoked instead.  What's the problem? ##
9
10In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods).
11
12## I wrote some matchers.  After I upgraded to a new version of Google Mock, they no longer compile.  What's going on? ##
13
14After version 1.4.0 of Google Mock was released, we had an idea on how
15to make it easier to write matchers that can generate informative
16messages efficiently.  We experimented with this idea and liked what
17we saw.  Therefore we decided to implement it.
18
19Unfortunately, this means that if you have defined your own matchers
20by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
21your definitions will no longer compile.  Matchers defined using the
22`MATCHER*` family of macros are not affected.
23
24Sorry for the hassle if your matchers are affected.  We believe it's
25in everyone's long-term interest to make this change sooner than
26later.  Fortunately, it's usually not hard to migrate an existing
27matcher to the new API.  Here's what you need to do:
28
29If you wrote your matcher like this:
30```
31// Old matcher definition that doesn't work with the latest
32// Google Mock.
33using ::testing::MatcherInterface;
34...
35class MyWonderfulMatcher : public MatcherInterface<MyType> {
36 public:
37  ...
38  virtual bool Matches(MyType value) const {
39    // Returns true if value matches.
40    return value.GetFoo() > 5;
41  }
42  ...
43};
44```
45
46you'll need to change it to:
47```
48// New matcher definition that works with the latest Google Mock.
49using ::testing::MatcherInterface;
50using ::testing::MatchResultListener;
51...
52class MyWonderfulMatcher : public MatcherInterface<MyType> {
53 public:
54  ...
55  virtual bool MatchAndExplain(MyType value,
56                               MatchResultListener* listener) const {
57    // Returns true if value matches.
58    return value.GetFoo() > 5;
59  }
60  ...
61};
62```
63(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
64argument of type `MatchResultListener*`.)
65
66If you were also using `ExplainMatchResultTo()` to improve the matcher
67message:
68```
69// Old matcher definition that doesn't work with the lastest
70// Google Mock.
71using ::testing::MatcherInterface;
72...
73class MyWonderfulMatcher : public MatcherInterface<MyType> {
74 public:
75  ...
76  virtual bool Matches(MyType value) const {
77    // Returns true if value matches.
78    return value.GetFoo() > 5;
79  }
80
81  virtual void ExplainMatchResultTo(MyType value,
82                                    ::std::ostream* os) const {
83    // Prints some helpful information to os to help
84    // a user understand why value matches (or doesn't match).
85    *os << "the Foo property is " << value.GetFoo();
86  }
87  ...
88};
89```
90
91you should move the logic of `ExplainMatchResultTo()` into
92`MatchAndExplain()`, using the `MatchResultListener` argument where
93the `::std::ostream` was used:
94```
95// New matcher definition that works with the latest Google Mock.
96using ::testing::MatcherInterface;
97using ::testing::MatchResultListener;
98...
99class MyWonderfulMatcher : public MatcherInterface<MyType> {
100 public:
101  ...
102  virtual bool MatchAndExplain(MyType value,
103                               MatchResultListener* listener) const {
104    // Returns true if value matches.
105    *listener << "the Foo property is " << value.GetFoo();
106    return value.GetFoo() > 5;
107  }
108  ...
109};
110```
111
112If your matcher is defined using `MakePolymorphicMatcher()`:
113```
114// Old matcher definition that doesn't work with the latest
115// Google Mock.
116using ::testing::MakePolymorphicMatcher;
117...
118class MyGreatMatcher {
119 public:
120  ...
121  bool Matches(MyType value) const {
122    // Returns true if value matches.
123    return value.GetBar() < 42;
124  }
125  ...
126};
127... MakePolymorphicMatcher(MyGreatMatcher()) ...
128```
129
130you should rename the `Matches()` method to `MatchAndExplain()` and
131add a `MatchResultListener*` argument (the same as what you need to do
132for matchers defined by implementing `MatcherInterface`):
133```
134// New matcher definition that works with the latest Google Mock.
135using ::testing::MakePolymorphicMatcher;
136using ::testing::MatchResultListener;
137...
138class MyGreatMatcher {
139 public:
140  ...
141  bool MatchAndExplain(MyType value,
142                       MatchResultListener* listener) const {
143    // Returns true if value matches.
144    return value.GetBar() < 42;
145  }
146  ...
147};
148... MakePolymorphicMatcher(MyGreatMatcher()) ...
149```
150
151If your polymorphic matcher uses `ExplainMatchResultTo()` for better
152failure messages:
153```
154// Old matcher definition that doesn't work with the latest
155// Google Mock.
156using ::testing::MakePolymorphicMatcher;
157...
158class MyGreatMatcher {
159 public:
160  ...
161  bool Matches(MyType value) const {
162    // Returns true if value matches.
163    return value.GetBar() < 42;
164  }
165  ...
166};
167void ExplainMatchResultTo(const MyGreatMatcher& matcher,
168                          MyType value,
169                          ::std::ostream* os) {
170  // Prints some helpful information to os to help
171  // a user understand why value matches (or doesn't match).
172  *os << "the Bar property is " << value.GetBar();
173}
174... MakePolymorphicMatcher(MyGreatMatcher()) ...
175```
176
177you'll need to move the logic inside `ExplainMatchResultTo()` to
178`MatchAndExplain()`:
179```
180// New matcher definition that works with the latest Google Mock.
181using ::testing::MakePolymorphicMatcher;
182using ::testing::MatchResultListener;
183...
184class MyGreatMatcher {
185 public:
186  ...
187  bool MatchAndExplain(MyType value,
188                       MatchResultListener* listener) const {
189    // Returns true if value matches.
190    *listener << "the Bar property is " << value.GetBar();
191    return value.GetBar() < 42;
192  }
193  ...
194};
195... MakePolymorphicMatcher(MyGreatMatcher()) ...
196```
197
198For more information, you can read these
199[two](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Monomorphic_Matchers)
200[recipes](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Matchers)
201from the cookbook.  As always, you
202are welcome to post questions on `googlemock@googlegroups.com` if you
203need any help.
204
205## When using Google Mock, do I have to use Google Test as the testing framework?  I have my favorite testing framework and don't want to switch. ##
206
207Google Mock works out of the box with Google Test.  However, it's easy
208to configure it to work with any testing framework of your choice.
209[Here](http://code.google.com/p/googlemock/wiki/V1_7_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how.
210
211## How am I supposed to make sense of these horrible template errors? ##
212
213If you are confused by the compiler errors gcc threw at you,
214try consulting the _Google Mock Doctor_ tool first.  What it does is to
215scan stdin for gcc error messages, and spit out diagnoses on the
216problems (we call them diseases) your code has.
217
218To "install", run command:
219```
220alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
221```
222
223To use it, do:
224```
225<your-favorite-build-command> <your-test> 2>&1 | gmd
226```
227
228For example:
229```
230make my_test 2>&1 | gmd
231```
232
233Or you can run `gmd` and copy-n-paste gcc's error messages to it.
234
235## Can I mock a variadic function? ##
236
237You cannot mock a variadic function (i.e. a function taking ellipsis
238(`...`) arguments) directly in Google Mock.
239
240The problem is that in general, there is _no way_ for a mock object to
241know how many arguments are passed to the variadic method, and what
242the arguments' types are.  Only the _author of the base class_ knows
243the protocol, and we cannot look into his head.
244
245Therefore, to mock such a function, the _user_ must teach the mock
246object how to figure out the number of arguments and their types.  One
247way to do it is to provide overloaded versions of the function.
248
249Ellipsis arguments are inherited from C and not really a C++ feature.
250They are unsafe to use and don't work with arguments that have
251constructors or destructors.  Therefore we recommend to avoid them in
252C++ as much as possible.
253
254## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter.  Why? ##
255
256If you compile this using Microsoft Visual C++ 2005 SP1:
257```
258class Foo {
259  ...
260  virtual void Bar(const int i) = 0;
261};
262
263class MockFoo : public Foo {
264  ...
265  MOCK_METHOD1(Bar, void(const int i));
266};
267```
268You may get the following warning:
269```
270warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
271```
272
273This is a MSVC bug.  The same code compiles fine with gcc ,for
274example.  If you use Visual C++ 2008 SP1, you would get the warning:
275```
276warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
277```
278
279In C++, if you _declare_ a function with a `const` parameter, the
280`const` modifier is _ignored_.  Therefore, the `Foo` base class above
281is equivalent to:
282```
283class Foo {
284  ...
285  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
286};
287```
288
289In fact, you can _declare_ Bar() with an `int` parameter, and _define_
290it with a `const int` parameter.  The compiler will still match them
291up.
292
293Since making a parameter `const` is meaningless in the method
294_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
295That should workaround the VC bug.
296
297Note that we are talking about the _top-level_ `const` modifier here.
298If the function parameter is passed by pointer or reference, declaring
299the _pointee_ or _referee_ as `const` is still meaningful.  For
300example, the following two declarations are _not_ equivalent:
301```
302void Bar(int* p);        // Neither p nor *p is const.
303void Bar(const int* p);  // p is not const, but *p is.
304```
305
306## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it.  What can I do? ##
307
308We've noticed that when the `/clr` compiler flag is used, Visual C++
309uses 5~6 times as much memory when compiling a mock class.  We suggest
310to avoid `/clr` when compiling native C++ mocks.
311
312## I can't figure out why Google Mock thinks my expectations are not satisfied.  What should I do? ##
313
314You might want to run your test with
315`--gmock_verbose=info`.  This flag lets Google Mock print a trace
316of every mock function call it receives.  By studying the trace,
317you'll gain insights on why the expectations you set are not met.
318
319## How can I assert that a function is NEVER called? ##
320
321```
322EXPECT_CALL(foo, Bar(_))
323    .Times(0);
324```
325
326## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied.  Isn't this redundant? ##
327
328When Google Mock detects a failure, it prints relevant information
329(the mock function arguments, the state of relevant expectations, and
330etc) to help the user debug.  If another failure is detected, Google
331Mock will do the same, including printing the state of relevant
332expectations.
333
334Sometimes an expectation's state didn't change between two failures,
335and you'll see the same description of the state twice.  They are
336however _not_ redundant, as they refer to _different points in time_.
337The fact they are the same _is_ interesting information.
338
339## I get a heap check failure when using a mock object, but using a real object is fine.  What can be wrong? ##
340
341Does the class (hopefully a pure interface) you are mocking have a
342virtual destructor?
343
344Whenever you derive from a base class, make sure its destructor is
345virtual.  Otherwise Bad Things will happen.  Consider the following
346code:
347
348```
349class Base {
350 public:
351  // Not virtual, but should be.
352  ~Base() { ... }
353  ...
354};
355
356class Derived : public Base {
357 public:
358  ...
359 private:
360  std::string value_;
361};
362
363...
364  Base* p = new Derived;
365  ...
366  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not
367             // - value_ is leaked.
368```
369
370By changing `~Base()` to virtual, `~Derived()` will be correctly
371called when `delete p` is executed, and the heap checker
372will be happy.
373
374## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##
375
376When people complain about this, often they are referring to code like:
377
378```
379// foo.Bar() should be called twice, return 1 the first time, and return
380// 2 the second time.  However, I have to write the expectations in the
381// reverse order.  This sucks big time!!!
382EXPECT_CALL(foo, Bar())
383    .WillOnce(Return(2))
384    .RetiresOnSaturation();
385EXPECT_CALL(foo, Bar())
386    .WillOnce(Return(1))
387    .RetiresOnSaturation();
388```
389
390The problem is that they didn't pick the **best** way to express the test's
391intent.
392
393By default, expectations don't have to be matched in _any_ particular
394order.  If you want them to match in a certain order, you need to be
395explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
396easy to accidentally over-specify your tests, and we want to make it
397harder to do so.
398
399There are two better ways to write the test spec.  You could either
400put the expectations in sequence:
401
402```
403// foo.Bar() should be called twice, return 1 the first time, and return
404// 2 the second time.  Using a sequence, we can write the expectations
405// in their natural order.
406{
407  InSequence s;
408  EXPECT_CALL(foo, Bar())
409      .WillOnce(Return(1))
410      .RetiresOnSaturation();
411  EXPECT_CALL(foo, Bar())
412      .WillOnce(Return(2))
413      .RetiresOnSaturation();
414}
415```
416
417or you can put the sequence of actions in the same expectation:
418
419```
420// foo.Bar() should be called twice, return 1 the first time, and return
421// 2 the second time.
422EXPECT_CALL(foo, Bar())
423    .WillOnce(Return(1))
424    .WillOnce(Return(2))
425    .RetiresOnSaturation();
426```
427
428Back to the original questions: why does Google Mock search the
429expectations (and `ON_CALL`s) from back to front?  Because this
430allows a user to set up a mock's behavior for the common case early
431(e.g. in the mock's constructor or the test fixture's set-up phase)
432and customize it with more specific rules later.  If Google Mock
433searches from front to back, this very useful pattern won't be
434possible.
435
436## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL.  Would it be reasonable not to show the warning in this case? ##
437
438When choosing between being neat and being safe, we lean toward the
439latter.  So the answer is that we think it's better to show the
440warning.
441
442Often people write `ON_CALL`s in the mock object's
443constructor or `SetUp()`, as the default behavior rarely changes from
444test to test.  Then in the test body they set the expectations, which
445are often different for each test.  Having an `ON_CALL` in the set-up
446part of a test doesn't mean that the calls are expected.  If there's
447no `EXPECT_CALL` and the method is called, it's possibly an error.  If
448we quietly let the call go through without notifying the user, bugs
449may creep in unnoticed.
450
451If, however, you are sure that the calls are OK, you can write
452
453```
454EXPECT_CALL(foo, Bar(_))
455    .WillRepeatedly(...);
456```
457
458instead of
459
460```
461ON_CALL(foo, Bar(_))
462    .WillByDefault(...);
463```
464
465This tells Google Mock that you do expect the calls and no warning should be
466printed.
467
468Also, you can control the verbosity using the `--gmock_verbose` flag.
469If you find the output too noisy when debugging, just choose a less
470verbose level.
471
472## How can I delete the mock function's argument in an action? ##
473
474If you find yourself needing to perform some action that's not
475supported by Google Mock directly, remember that you can define your own
476actions using
477[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Actions) or
478[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Actions),
479or you can write a stub function and invoke it using
480[Invoke()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Functions_Methods_Functors).
481
482## MOCK\_METHODn()'s second argument looks funny.  Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##
483
484What?!  I think it's beautiful. :-)
485
486While which syntax looks more natural is a subjective matter to some
487extent, Google Mock's syntax was chosen for several practical advantages it
488has.
489
490Try to mock a function that takes a map as an argument:
491```
492virtual int GetSize(const map<int, std::string>& m);
493```
494
495Using the proposed syntax, it would be:
496```
497MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
498```
499
500Guess what?  You'll get a compiler error as the compiler thinks that
501`const map<int, std::string>& m` are **two**, not one, arguments. To work
502around this you can use `typedef` to give the map type a name, but
503that gets in the way of your work.  Google Mock's syntax avoids this
504problem as the function's argument types are protected inside a pair
505of parentheses:
506```
507// This compiles fine.
508MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
509```
510
511You still need a `typedef` if the return type contains an unprotected
512comma, but that's much rarer.
513
514Other advantages include:
515  1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
516  1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it.  The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively.  Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
517  1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features.  We'd as well stick to the same syntax in `MOCK_METHOD*`!
518
519## My code calls a static/global function.  Can I mock it? ##
520
521You can, but you need to make some changes.
522
523In general, if you find yourself needing to mock a static function,
524it's a sign that your modules are too tightly coupled (and less
525flexible, less reusable, less testable, etc).  You are probably better
526off defining a small interface and call the function through that
527interface, which then can be easily mocked.  It's a bit of work
528initially, but usually pays for itself quickly.
529
530This Google Testing Blog
531[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
532says it excellently.  Check it out.
533
534## My mock object needs to do complex stuff.  It's a lot of pain to specify the actions.  Google Mock sucks! ##
535
536I know it's not a question, but you get an answer for free any way. :-)
537
538With Google Mock, you can create mocks in C++ easily.  And people might be
539tempted to use them everywhere. Sometimes they work great, and
540sometimes you may find them, well, a pain to use. So, what's wrong in
541the latter case?
542
543When you write a test without using mocks, you exercise the code and
544assert that it returns the correct value or that the system is in an
545expected state.  This is sometimes called "state-based testing".
546
547Mocks are great for what some call "interaction-based" testing:
548instead of checking the system state at the very end, mock objects
549verify that they are invoked the right way and report an error as soon
550as it arises, giving you a handle on the precise context in which the
551error was triggered.  This is often more effective and economical to
552do than state-based testing.
553
554If you are doing state-based testing and using a test double just to
555simulate the real object, you are probably better off using a fake.
556Using a mock in this case causes pain, as it's not a strong point for
557mocks to perform complex actions.  If you experience this and think
558that mocks suck, you are just not using the right tool for your
559problem. Or, you might be trying to solve the wrong problem. :-)
560
561## I got a warning "Uninteresting function call encountered - default action taken.."  Should I panic? ##
562
563By all means, NO!  It's just an FYI.
564
565What it means is that you have a mock function, you haven't set any
566expectations on it (by Google Mock's rule this means that you are not
567interested in calls to this function and therefore it can be called
568any number of times), and it is called.  That's OK - you didn't say
569it's not OK to call the function!
570
571What if you actually meant to disallow this function to be called, but
572forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
573one can argue that it's the user's fault, Google Mock tries to be nice and
574prints you a note.
575
576So, when you see the message and believe that there shouldn't be any
577uninteresting calls, you should investigate what's going on.  To make
578your life easier, Google Mock prints the function name and arguments
579when an uninteresting call is encountered.
580
581## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##
582
583Either way is fine - you want to choose the one that's more convenient
584for your circumstance.
585
586Usually, if your action is for a particular function type, defining it
587using `Invoke()` should be easier; if your action can be used in
588functions of different types (e.g. if you are defining
589`Return(value)`), `MakePolymorphicAction()` is
590easiest.  Sometimes you want precise control on what types of
591functions the action can be used in, and implementing
592`ActionInterface` is the way to go here. See the implementation of
593`Return()` in `include/gmock/gmock-actions.h` for an example.
594
595## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified".  What does it mean? ##
596
597You got this error as Google Mock has no idea what value it should return
598when the mock method is called.  `SetArgPointee()` says what the
599side effect is, but doesn't say what the return value should be.  You
600need `DoAll()` to chain a `SetArgPointee()` with a `Return()`.
601
602See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Side_Effects) for more details and an example.
603
604
605## My question is not in your FAQ! ##
606
607If you cannot find the answer to your question in this FAQ, there are
608some other resources you can use:
609
610  1. read other [wiki pages](http://code.google.com/p/googlemock/w/list),
611  1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
612  1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).
613
614Please note that creating an issue in the
615[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_
616a good way to get your answer, as it is monitored infrequently by a
617very small number of people.
618
619When asking a question, it's helpful to provide as much of the
620following information as possible (people cannot help you if there's
621not enough information in your question):
622
623  * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
624  * your operating system,
625  * the name and version of your compiler,
626  * the complete command line flags you give to your compiler,
627  * the complete compiler error messages (if the question is about compilation),
628  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-actions.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used actions.
35
36#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
37#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
38
39#ifndef _WIN32_WCE
40# include <errno.h>
41#endif
42
43#include <algorithm>
44#include <string>
45
46#include "gmock/internal/gmock-internal-utils.h"
47#include "gmock/internal/gmock-port.h"
48
49#if GTEST_LANG_CXX11  // Defined by gtest-port.h via gmock-port.h.
50#include <type_traits>
51#endif
52
53namespace testing {
54
55// To implement an action Foo, define:
56//   1. a class FooAction that implements the ActionInterface interface, and
57//   2. a factory function that creates an Action object from a
58//      const FooAction*.
59//
60// The two-level delegation design follows that of Matcher, providing
61// consistency for extension developers.  It also eases ownership
62// management as Action objects can now be copied like plain values.
63
64namespace internal {
65
66template <typename F1, typename F2>
67class ActionAdaptor;
68
69// BuiltInDefaultValueGetter<T, true>::Get() returns a
70// default-constructed T value.  BuiltInDefaultValueGetter<T,
71// false>::Get() crashes with an error.
72//
73// This primary template is used when kDefaultConstructible is true.
74template <typename T, bool kDefaultConstructible>
75struct BuiltInDefaultValueGetter {
76  static T Get() { return T(); }
77};
78template <typename T>
79struct BuiltInDefaultValueGetter<T, false> {
80  static T Get() {
81    Assert(false, __FILE__, __LINE__,
82           "Default action undefined for the function return type.");
83    return internal::Invalid<T>();
84    // The above statement will never be reached, but is required in
85    // order for this function to compile.
86  }
87};
88
89// BuiltInDefaultValue<T>::Get() returns the "built-in" default value
90// for type T, which is NULL when T is a raw pointer type, 0 when T is
91// a numeric type, false when T is bool, or "" when T is string or
92// std::string.  In addition, in C++11 and above, it turns a
93// default-constructed T value if T is default constructible.  For any
94// other type T, the built-in default T value is undefined, and the
95// function will abort the process.
96template <typename T>
97class BuiltInDefaultValue {
98 public:
99#if GTEST_LANG_CXX11
100  // This function returns true iff type T has a built-in default value.
101  static bool Exists() {
102    return ::std::is_default_constructible<T>::value;
103  }
104
105  static T Get() {
106    return BuiltInDefaultValueGetter<
107        T, ::std::is_default_constructible<T>::value>::Get();
108  }
109
110#else  // GTEST_LANG_CXX11
111  // This function returns true iff type T has a built-in default value.
112  static bool Exists() {
113    return false;
114  }
115
116  static T Get() {
117    return BuiltInDefaultValueGetter<T, false>::Get();
118  }
119
120#endif  // GTEST_LANG_CXX11
121};
122
123// This partial specialization says that we use the same built-in
124// default value for T and const T.
125template <typename T>
126class BuiltInDefaultValue<const T> {
127 public:
128  static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
129  static T Get() { return BuiltInDefaultValue<T>::Get(); }
130};
131
132// This partial specialization defines the default values for pointer
133// types.
134template <typename T>
135class BuiltInDefaultValue<T*> {
136 public:
137  static bool Exists() { return true; }
138  static T* Get() { return NULL; }
139};
140
141// The following specializations define the default values for
142// specific types we care about.
143#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
144  template <> \
145  class BuiltInDefaultValue<type> { \
146   public: \
147    static bool Exists() { return true; } \
148    static type Get() { return value; } \
149  }
150
151GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT
152#if GTEST_HAS_GLOBAL_STRING
153GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
154#endif  // GTEST_HAS_GLOBAL_STRING
155GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
156GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
157GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
158GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
159GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
160
161// There's no need for a default action for signed wchar_t, as that
162// type is the same as wchar_t for gcc, and invalid for MSVC.
163//
164// There's also no need for a default action for unsigned wchar_t, as
165// that type is the same as unsigned int for gcc, and invalid for
166// MSVC.
167#if GMOCK_WCHAR_T_IS_NATIVE_
168GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U);  // NOLINT
169#endif
170
171GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT
172GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT
173GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
174GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
175GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);  // NOLINT
176GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);     // NOLINT
177GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
178GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
179GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
180GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
181
182#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
183
184}  // namespace internal
185
186// When an unexpected function call is encountered, Google Mock will
187// let it return a default value if the user has specified one for its
188// return type, or if the return type has a built-in default value;
189// otherwise Google Mock won't know what value to return and will have
190// to abort the process.
191//
192// The DefaultValue<T> class allows a user to specify the
193// default value for a type T that is both copyable and publicly
194// destructible (i.e. anything that can be used as a function return
195// type).  The usage is:
196//
197//   // Sets the default value for type T to be foo.
198//   DefaultValue<T>::Set(foo);
199template <typename T>
200class DefaultValue {
201 public:
202  // Sets the default value for type T; requires T to be
203  // copy-constructable and have a public destructor.
204  static void Set(T x) {
205    delete producer_;
206    producer_ = new FixedValueProducer(x);
207  }
208
209  // Provides a factory function to be called to generate the default value.
210  // This method can be used even if T is only move-constructible, but it is not
211  // limited to that case.
212  typedef T (*FactoryFunction)();
213  static void SetFactory(FactoryFunction factory) {
214    delete producer_;
215    producer_ = new FactoryValueProducer(factory);
216  }
217
218  // Unsets the default value for type T.
219  static void Clear() {
220    delete producer_;
221    producer_ = NULL;
222  }
223
224  // Returns true iff the user has set the default value for type T.
225  static bool IsSet() { return producer_ != NULL; }
226
227  // Returns true if T has a default return value set by the user or there
228  // exists a built-in default value.
229  static bool Exists() {
230    return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
231  }
232
233  // Returns the default value for type T if the user has set one;
234  // otherwise returns the built-in default value. Requires that Exists()
235  // is true, which ensures that the return value is well-defined.
236  static T Get() {
237    return producer_ == NULL ?
238        internal::BuiltInDefaultValue<T>::Get() : producer_->Produce();
239  }
240
241 private:
242  class ValueProducer {
243   public:
244    virtual ~ValueProducer() {}
245    virtual T Produce() = 0;
246  };
247
248  class FixedValueProducer : public ValueProducer {
249   public:
250    explicit FixedValueProducer(T value) : value_(value) {}
251    virtual T Produce() { return value_; }
252
253   private:
254    const T value_;
255    GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
256  };
257
258  class FactoryValueProducer : public ValueProducer {
259   public:
260    explicit FactoryValueProducer(FactoryFunction factory)
261        : factory_(factory) {}
262    virtual T Produce() { return factory_(); }
263
264   private:
265    const FactoryFunction factory_;
266    GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
267  };
268
269  static ValueProducer* producer_;
270};
271
272// This partial specialization allows a user to set default values for
273// reference types.
274template <typename T>
275class DefaultValue<T&> {
276 public:
277  // Sets the default value for type T&.
278  static void Set(T& x) {  // NOLINT
279    address_ = &x;
280  }
281
282  // Unsets the default value for type T&.
283  static void Clear() {
284    address_ = NULL;
285  }
286
287  // Returns true iff the user has set the default value for type T&.
288  static bool IsSet() { return address_ != NULL; }
289
290  // Returns true if T has a default return value set by the user or there
291  // exists a built-in default value.
292  static bool Exists() {
293    return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
294  }
295
296  // Returns the default value for type T& if the user has set one;
297  // otherwise returns the built-in default value if there is one;
298  // otherwise aborts the process.
299  static T& Get() {
300    return address_ == NULL ?
301        internal::BuiltInDefaultValue<T&>::Get() : *address_;
302  }
303
304 private:
305  static T* address_;
306};
307
308// This specialization allows DefaultValue<void>::Get() to
309// compile.
310template <>
311class DefaultValue<void> {
312 public:
313  static bool Exists() { return true; }
314  static void Get() {}
315};
316
317// Points to the user-set default value for type T.
318template <typename T>
319typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;
320
321// Points to the user-set default value for type T&.
322template <typename T>
323T* DefaultValue<T&>::address_ = NULL;
324
325// Implement this interface to define an action for function type F.
326template <typename F>
327class ActionInterface {
328 public:
329  typedef typename internal::Function<F>::Result Result;
330  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
331
332  ActionInterface() {}
333  virtual ~ActionInterface() {}
334
335  // Performs the action.  This method is not const, as in general an
336  // action can have side effects and be stateful.  For example, a
337  // get-the-next-element-from-the-collection action will need to
338  // remember the current element.
339  virtual Result Perform(const ArgumentTuple& args) = 0;
340
341 private:
342  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
343};
344
345// An Action<F> is a copyable and IMMUTABLE (except by assignment)
346// object that represents an action to be taken when a mock function
347// of type F is called.  The implementation of Action<T> is just a
348// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
349// Don't inherit from Action!
350//
351// You can view an object implementing ActionInterface<F> as a
352// concrete action (including its current state), and an Action<F>
353// object as a handle to it.
354template <typename F>
355class Action {
356 public:
357  typedef typename internal::Function<F>::Result Result;
358  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
359
360  // Constructs a null Action.  Needed for storing Action objects in
361  // STL containers.
362  Action() : impl_(NULL) {}
363
364  // Constructs an Action from its implementation.  A NULL impl is
365  // used to represent the "do-default" action.
366  explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
367
368  // Copy constructor.
369  Action(const Action& action) : impl_(action.impl_) {}
370
371  // This constructor allows us to turn an Action<Func> object into an
372  // Action<F>, as long as F's arguments can be implicitly converted
373  // to Func's and Func's return type can be implicitly converted to
374  // F's.
375  template <typename Func>
376  explicit Action(const Action<Func>& action);
377
378  // Returns true iff this is the DoDefault() action.
379  bool IsDoDefault() const { return impl_.get() == NULL; }
380
381  // Performs the action.  Note that this method is const even though
382  // the corresponding method in ActionInterface is not.  The reason
383  // is that a const Action<F> means that it cannot be re-bound to
384  // another concrete action, not that the concrete action it binds to
385  // cannot change state.  (Think of the difference between a const
386  // pointer and a pointer to const.)
387  Result Perform(const ArgumentTuple& args) const {
388    internal::Assert(
389        !IsDoDefault(), __FILE__, __LINE__,
390        "You are using DoDefault() inside a composite action like "
391        "DoAll() or WithArgs().  This is not supported for technical "
392        "reasons.  Please instead spell out the default action, or "
393        "assign the default action to an Action variable and use "
394        "the variable in various places.");
395    return impl_->Perform(args);
396  }
397
398 private:
399  template <typename F1, typename F2>
400  friend class internal::ActionAdaptor;
401
402  internal::linked_ptr<ActionInterface<F> > impl_;
403};
404
405// The PolymorphicAction class template makes it easy to implement a
406// polymorphic action (i.e. an action that can be used in mock
407// functions of than one type, e.g. Return()).
408//
409// To define a polymorphic action, a user first provides a COPYABLE
410// implementation class that has a Perform() method template:
411//
412//   class FooAction {
413//    public:
414//     template <typename Result, typename ArgumentTuple>
415//     Result Perform(const ArgumentTuple& args) const {
416//       // Processes the arguments and returns a result, using
417//       // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
418//     }
419//     ...
420//   };
421//
422// Then the user creates the polymorphic action using
423// MakePolymorphicAction(object) where object has type FooAction.  See
424// the definition of Return(void) and SetArgumentPointee<N>(value) for
425// complete examples.
426template <typename Impl>
427class PolymorphicAction {
428 public:
429  explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
430
431  template <typename F>
432  operator Action<F>() const {
433    return Action<F>(new MonomorphicImpl<F>(impl_));
434  }
435
436 private:
437  template <typename F>
438  class MonomorphicImpl : public ActionInterface<F> {
439   public:
440    typedef typename internal::Function<F>::Result Result;
441    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
442
443    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
444
445    virtual Result Perform(const ArgumentTuple& args) {
446      return impl_.template Perform<Result>(args);
447    }
448
449   private:
450    Impl impl_;
451
452    GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
453  };
454
455  Impl impl_;
456
457  GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
458};
459
460// Creates an Action from its implementation and returns it.  The
461// created Action object owns the implementation.
462template <typename F>
463Action<F> MakeAction(ActionInterface<F>* impl) {
464  return Action<F>(impl);
465}
466
467// Creates a polymorphic action from its implementation.  This is
468// easier to use than the PolymorphicAction<Impl> constructor as it
469// doesn't require you to explicitly write the template argument, e.g.
470//
471//   MakePolymorphicAction(foo);
472// vs
473//   PolymorphicAction<TypeOfFoo>(foo);
474template <typename Impl>
475inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
476  return PolymorphicAction<Impl>(impl);
477}
478
479namespace internal {
480
481// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
482// and F1 are compatible.
483template <typename F1, typename F2>
484class ActionAdaptor : public ActionInterface<F1> {
485 public:
486  typedef typename internal::Function<F1>::Result Result;
487  typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
488
489  explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
490
491  virtual Result Perform(const ArgumentTuple& args) {
492    return impl_->Perform(args);
493  }
494
495 private:
496  const internal::linked_ptr<ActionInterface<F2> > impl_;
497
498  GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
499};
500
501// Helper struct to specialize ReturnAction to execute a move instead of a copy
502// on return. Useful for move-only types, but could be used on any type.
503template <typename T>
504struct ByMoveWrapper {
505  explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
506  T payload;
507};
508
509// Implements the polymorphic Return(x) action, which can be used in
510// any function that returns the type of x, regardless of the argument
511// types.
512//
513// Note: The value passed into Return must be converted into
514// Function<F>::Result when this action is cast to Action<F> rather than
515// when that action is performed. This is important in scenarios like
516//
517// MOCK_METHOD1(Method, T(U));
518// ...
519// {
520//   Foo foo;
521//   X x(&foo);
522//   EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
523// }
524//
525// In the example above the variable x holds reference to foo which leaves
526// scope and gets destroyed.  If copying X just copies a reference to foo,
527// that copy will be left with a hanging reference.  If conversion to T
528// makes a copy of foo, the above code is safe. To support that scenario, we
529// need to make sure that the type conversion happens inside the EXPECT_CALL
530// statement, and conversion of the result of Return to Action<T(U)> is a
531// good place for that.
532//
533template <typename R>
534class ReturnAction {
535 public:
536  // Constructs a ReturnAction object from the value to be returned.
537  // 'value' is passed by value instead of by const reference in order
538  // to allow Return("string literal") to compile.
539  explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
540
541  // This template type conversion operator allows Return(x) to be
542  // used in ANY function that returns x's type.
543  template <typename F>
544  operator Action<F>() const {
545    // Assert statement belongs here because this is the best place to verify
546    // conditions on F. It produces the clearest error messages
547    // in most compilers.
548    // Impl really belongs in this scope as a local class but can't
549    // because MSVC produces duplicate symbols in different translation units
550    // in this case. Until MS fixes that bug we put Impl into the class scope
551    // and put the typedef both here (for use in assert statement) and
552    // in the Impl class. But both definitions must be the same.
553    typedef typename Function<F>::Result Result;
554    GTEST_COMPILE_ASSERT_(
555        !is_reference<Result>::value,
556        use_ReturnRef_instead_of_Return_to_return_a_reference);
557    return Action<F>(new Impl<R, F>(value_));
558  }
559
560 private:
561  // Implements the Return(x) action for a particular function type F.
562  template <typename R_, typename F>
563  class Impl : public ActionInterface<F> {
564   public:
565    typedef typename Function<F>::Result Result;
566    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
567
568    // The implicit cast is necessary when Result has more than one
569    // single-argument constructor (e.g. Result is std::vector<int>) and R
570    // has a type conversion operator template.  In that case, value_(value)
571    // won't compile as the compiler doesn't known which constructor of
572    // Result to call.  ImplicitCast_ forces the compiler to convert R to
573    // Result without considering explicit constructors, thus resolving the
574    // ambiguity. value_ is then initialized using its copy constructor.
575    explicit Impl(const linked_ptr<R>& value)
576        : value_before_cast_(*value),
577          value_(ImplicitCast_<Result>(value_before_cast_)) {}
578
579    virtual Result Perform(const ArgumentTuple&) { return value_; }
580
581   private:
582    GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
583                          Result_cannot_be_a_reference_type);
584    // We save the value before casting just in case it is being cast to a
585    // wrapper type.
586    R value_before_cast_;
587    Result value_;
588
589    GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
590  };
591
592  // Partially specialize for ByMoveWrapper. This version of ReturnAction will
593  // move its contents instead.
594  template <typename R_, typename F>
595  class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
596   public:
597    typedef typename Function<F>::Result Result;
598    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
599
600    explicit Impl(const linked_ptr<R>& wrapper)
601        : performed_(false), wrapper_(wrapper) {}
602
603    virtual Result Perform(const ArgumentTuple&) {
604      GTEST_CHECK_(!performed_)
605          << "A ByMove() action should only be performed once.";
606      performed_ = true;
607      return internal::move(wrapper_->payload);
608    }
609
610   private:
611    bool performed_;
612    const linked_ptr<R> wrapper_;
613
614    GTEST_DISALLOW_ASSIGN_(Impl);
615  };
616
617  const linked_ptr<R> value_;
618
619  GTEST_DISALLOW_ASSIGN_(ReturnAction);
620};
621
622// Implements the ReturnNull() action.
623class ReturnNullAction {
624 public:
625  // Allows ReturnNull() to be used in any pointer-returning function. In C++11
626  // this is enforced by returning nullptr, and in non-C++11 by asserting a
627  // pointer type on compile time.
628  template <typename Result, typename ArgumentTuple>
629  static Result Perform(const ArgumentTuple&) {
630#if GTEST_LANG_CXX11
631    return nullptr;
632#else
633    GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
634                          ReturnNull_can_be_used_to_return_a_pointer_only);
635    return NULL;
636#endif  // GTEST_LANG_CXX11
637  }
638};
639
640// Implements the Return() action.
641class ReturnVoidAction {
642 public:
643  // Allows Return() to be used in any void-returning function.
644  template <typename Result, typename ArgumentTuple>
645  static void Perform(const ArgumentTuple&) {
646    CompileAssertTypesEqual<void, Result>();
647  }
648};
649
650// Implements the polymorphic ReturnRef(x) action, which can be used
651// in any function that returns a reference to the type of x,
652// regardless of the argument types.
653template <typename T>
654class ReturnRefAction {
655 public:
656  // Constructs a ReturnRefAction object from the reference to be returned.
657  explicit ReturnRefAction(T& ref) : ref_(ref) {}  // NOLINT
658
659  // This template type conversion operator allows ReturnRef(x) to be
660  // used in ANY function that returns a reference to x's type.
661  template <typename F>
662  operator Action<F>() const {
663    typedef typename Function<F>::Result Result;
664    // Asserts that the function return type is a reference.  This
665    // catches the user error of using ReturnRef(x) when Return(x)
666    // should be used, and generates some helpful error message.
667    GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
668                          use_Return_instead_of_ReturnRef_to_return_a_value);
669    return Action<F>(new Impl<F>(ref_));
670  }
671
672 private:
673  // Implements the ReturnRef(x) action for a particular function type F.
674  template <typename F>
675  class Impl : public ActionInterface<F> {
676   public:
677    typedef typename Function<F>::Result Result;
678    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
679
680    explicit Impl(T& ref) : ref_(ref) {}  // NOLINT
681
682    virtual Result Perform(const ArgumentTuple&) {
683      return ref_;
684    }
685
686   private:
687    T& ref_;
688
689    GTEST_DISALLOW_ASSIGN_(Impl);
690  };
691
692  T& ref_;
693
694  GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
695};
696
697// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
698// used in any function that returns a reference to the type of x,
699// regardless of the argument types.
700template <typename T>
701class ReturnRefOfCopyAction {
702 public:
703  // Constructs a ReturnRefOfCopyAction object from the reference to
704  // be returned.
705  explicit ReturnRefOfCopyAction(const T& value) : value_(value) {}  // NOLINT
706
707  // This template type conversion operator allows ReturnRefOfCopy(x) to be
708  // used in ANY function that returns a reference to x's type.
709  template <typename F>
710  operator Action<F>() const {
711    typedef typename Function<F>::Result Result;
712    // Asserts that the function return type is a reference.  This
713    // catches the user error of using ReturnRefOfCopy(x) when Return(x)
714    // should be used, and generates some helpful error message.
715    GTEST_COMPILE_ASSERT_(
716        internal::is_reference<Result>::value,
717        use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
718    return Action<F>(new Impl<F>(value_));
719  }
720
721 private:
722  // Implements the ReturnRefOfCopy(x) action for a particular function type F.
723  template <typename F>
724  class Impl : public ActionInterface<F> {
725   public:
726    typedef typename Function<F>::Result Result;
727    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
728
729    explicit Impl(const T& value) : value_(value) {}  // NOLINT
730
731    virtual Result Perform(const ArgumentTuple&) {
732      return value_;
733    }
734
735   private:
736    T value_;
737
738    GTEST_DISALLOW_ASSIGN_(Impl);
739  };
740
741  const T value_;
742
743  GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
744};
745
746// Implements the polymorphic DoDefault() action.
747class DoDefaultAction {
748 public:
749  // This template type conversion operator allows DoDefault() to be
750  // used in any function.
751  template <typename F>
752  operator Action<F>() const { return Action<F>(NULL); }
753};
754
755// Implements the Assign action to set a given pointer referent to a
756// particular value.
757template <typename T1, typename T2>
758class AssignAction {
759 public:
760  AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
761
762  template <typename Result, typename ArgumentTuple>
763  void Perform(const ArgumentTuple& /* args */) const {
764    *ptr_ = value_;
765  }
766
767 private:
768  T1* const ptr_;
769  const T2 value_;
770
771  GTEST_DISALLOW_ASSIGN_(AssignAction);
772};
773
774#if !GTEST_OS_WINDOWS_MOBILE
775
776// Implements the SetErrnoAndReturn action to simulate return from
777// various system calls and libc functions.
778template <typename T>
779class SetErrnoAndReturnAction {
780 public:
781  SetErrnoAndReturnAction(int errno_value, T result)
782      : errno_(errno_value),
783        result_(result) {}
784  template <typename Result, typename ArgumentTuple>
785  Result Perform(const ArgumentTuple& /* args */) const {
786    errno = errno_;
787    return result_;
788  }
789
790 private:
791  const int errno_;
792  const T result_;
793
794  GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
795};
796
797#endif  // !GTEST_OS_WINDOWS_MOBILE
798
799// Implements the SetArgumentPointee<N>(x) action for any function
800// whose N-th argument (0-based) is a pointer to x's type.  The
801// template parameter kIsProto is true iff type A is ProtocolMessage,
802// proto2::Message, or a sub-class of those.
803template <size_t N, typename A, bool kIsProto>
804class SetArgumentPointeeAction {
805 public:
806  // Constructs an action that sets the variable pointed to by the
807  // N-th function argument to 'value'.
808  explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
809
810  template <typename Result, typename ArgumentTuple>
811  void Perform(const ArgumentTuple& args) const {
812    CompileAssertTypesEqual<void, Result>();
813    *::testing::get<N>(args) = value_;
814  }
815
816 private:
817  const A value_;
818
819  GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
820};
821
822template <size_t N, typename Proto>
823class SetArgumentPointeeAction<N, Proto, true> {
824 public:
825  // Constructs an action that sets the variable pointed to by the
826  // N-th function argument to 'proto'.  Both ProtocolMessage and
827  // proto2::Message have the CopyFrom() method, so the same
828  // implementation works for both.
829  explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
830    proto_->CopyFrom(proto);
831  }
832
833  template <typename Result, typename ArgumentTuple>
834  void Perform(const ArgumentTuple& args) const {
835    CompileAssertTypesEqual<void, Result>();
836    ::testing::get<N>(args)->CopyFrom(*proto_);
837  }
838
839 private:
840  const internal::linked_ptr<Proto> proto_;
841
842  GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
843};
844
845// Implements the InvokeWithoutArgs(f) action.  The template argument
846// FunctionImpl is the implementation type of f, which can be either a
847// function pointer or a functor.  InvokeWithoutArgs(f) can be used as an
848// Action<F> as long as f's type is compatible with F (i.e. f can be
849// assigned to a tr1::function<F>).
850template <typename FunctionImpl>
851class InvokeWithoutArgsAction {
852 public:
853  // The c'tor makes a copy of function_impl (either a function
854  // pointer or a functor).
855  explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
856      : function_impl_(function_impl) {}
857
858  // Allows InvokeWithoutArgs(f) to be used as any action whose type is
859  // compatible with f.
860  template <typename Result, typename ArgumentTuple>
861  Result Perform(const ArgumentTuple&) { return function_impl_(); }
862
863 private:
864  FunctionImpl function_impl_;
865
866  GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
867};
868
869// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
870template <class Class, typename MethodPtr>
871class InvokeMethodWithoutArgsAction {
872 public:
873  InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
874      : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
875
876  template <typename Result, typename ArgumentTuple>
877  Result Perform(const ArgumentTuple&) const {
878    return (obj_ptr_->*method_ptr_)();
879  }
880
881 private:
882  Class* const obj_ptr_;
883  const MethodPtr method_ptr_;
884
885  GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
886};
887
888// Implements the IgnoreResult(action) action.
889template <typename A>
890class IgnoreResultAction {
891 public:
892  explicit IgnoreResultAction(const A& action) : action_(action) {}
893
894  template <typename F>
895  operator Action<F>() const {
896    // Assert statement belongs here because this is the best place to verify
897    // conditions on F. It produces the clearest error messages
898    // in most compilers.
899    // Impl really belongs in this scope as a local class but can't
900    // because MSVC produces duplicate symbols in different translation units
901    // in this case. Until MS fixes that bug we put Impl into the class scope
902    // and put the typedef both here (for use in assert statement) and
903    // in the Impl class. But both definitions must be the same.
904    typedef typename internal::Function<F>::Result Result;
905
906    // Asserts at compile time that F returns void.
907    CompileAssertTypesEqual<void, Result>();
908
909    return Action<F>(new Impl<F>(action_));
910  }
911
912 private:
913  template <typename F>
914  class Impl : public ActionInterface<F> {
915   public:
916    typedef typename internal::Function<F>::Result Result;
917    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
918
919    explicit Impl(const A& action) : action_(action) {}
920
921    virtual void Perform(const ArgumentTuple& args) {
922      // Performs the action and ignores its result.
923      action_.Perform(args);
924    }
925
926   private:
927    // Type OriginalFunction is the same as F except that its return
928    // type is IgnoredValue.
929    typedef typename internal::Function<F>::MakeResultIgnoredValue
930        OriginalFunction;
931
932    const Action<OriginalFunction> action_;
933
934    GTEST_DISALLOW_ASSIGN_(Impl);
935  };
936
937  const A action_;
938
939  GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
940};
941
942// A ReferenceWrapper<T> object represents a reference to type T,
943// which can be either const or not.  It can be explicitly converted
944// from, and implicitly converted to, a T&.  Unlike a reference,
945// ReferenceWrapper<T> can be copied and can survive template type
946// inference.  This is used to support by-reference arguments in the
947// InvokeArgument<N>(...) action.  The idea was from "reference
948// wrappers" in tr1, which we don't have in our source tree yet.
949template <typename T>
950class ReferenceWrapper {
951 public:
952  // Constructs a ReferenceWrapper<T> object from a T&.
953  explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {}  // NOLINT
954
955  // Allows a ReferenceWrapper<T> object to be implicitly converted to
956  // a T&.
957  operator T&() const { return *pointer_; }
958 private:
959  T* pointer_;
960};
961
962// Allows the expression ByRef(x) to be printed as a reference to x.
963template <typename T>
964void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
965  T& value = ref;
966  UniversalPrinter<T&>::Print(value, os);
967}
968
969// Does two actions sequentially.  Used for implementing the DoAll(a1,
970// a2, ...) action.
971template <typename Action1, typename Action2>
972class DoBothAction {
973 public:
974  DoBothAction(Action1 action1, Action2 action2)
975      : action1_(action1), action2_(action2) {}
976
977  // This template type conversion operator allows DoAll(a1, ..., a_n)
978  // to be used in ANY function of compatible type.
979  template <typename F>
980  operator Action<F>() const {
981    return Action<F>(new Impl<F>(action1_, action2_));
982  }
983
984 private:
985  // Implements the DoAll(...) action for a particular function type F.
986  template <typename F>
987  class Impl : public ActionInterface<F> {
988   public:
989    typedef typename Function<F>::Result Result;
990    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
991    typedef typename Function<F>::MakeResultVoid VoidResult;
992
993    Impl(const Action<VoidResult>& action1, const Action<F>& action2)
994        : action1_(action1), action2_(action2) {}
995
996    virtual Result Perform(const ArgumentTuple& args) {
997      action1_.Perform(args);
998      return action2_.Perform(args);
999    }
1000
1001   private:
1002    const Action<VoidResult> action1_;
1003    const Action<F> action2_;
1004
1005    GTEST_DISALLOW_ASSIGN_(Impl);
1006  };
1007
1008  Action1 action1_;
1009  Action2 action2_;
1010
1011  GTEST_DISALLOW_ASSIGN_(DoBothAction);
1012};
1013
1014}  // namespace internal
1015
1016// An Unused object can be implicitly constructed from ANY value.
1017// This is handy when defining actions that ignore some or all of the
1018// mock function arguments.  For example, given
1019//
1020//   MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1021//   MOCK_METHOD3(Bar, double(int index, double x, double y));
1022//
1023// instead of
1024//
1025//   double DistanceToOriginWithLabel(const string& label, double x, double y) {
1026//     return sqrt(x*x + y*y);
1027//   }
1028//   double DistanceToOriginWithIndex(int index, double x, double y) {
1029//     return sqrt(x*x + y*y);
1030//   }
1031//   ...
1032//   EXEPCT_CALL(mock, Foo("abc", _, _))
1033//       .WillOnce(Invoke(DistanceToOriginWithLabel));
1034//   EXEPCT_CALL(mock, Bar(5, _, _))
1035//       .WillOnce(Invoke(DistanceToOriginWithIndex));
1036//
1037// you could write
1038//
1039//   // We can declare any uninteresting argument as Unused.
1040//   double DistanceToOrigin(Unused, double x, double y) {
1041//     return sqrt(x*x + y*y);
1042//   }
1043//   ...
1044//   EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
1045//   EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
1046typedef internal::IgnoredValue Unused;
1047
1048// This constructor allows us to turn an Action<From> object into an
1049// Action<To>, as long as To's arguments can be implicitly converted
1050// to From's and From's return type cann be implicitly converted to
1051// To's.
1052template <typename To>
1053template <typename From>
1054Action<To>::Action(const Action<From>& from)
1055    : impl_(new internal::ActionAdaptor<To, From>(from)) {}
1056
1057// Creates an action that returns 'value'.  'value' is passed by value
1058// instead of const reference - otherwise Return("string literal")
1059// will trigger a compiler error about using array as initializer.
1060template <typename R>
1061internal::ReturnAction<R> Return(R value) {
1062  return internal::ReturnAction<R>(internal::move(value));
1063}
1064
1065// Creates an action that returns NULL.
1066inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1067  return MakePolymorphicAction(internal::ReturnNullAction());
1068}
1069
1070// Creates an action that returns from a void function.
1071inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1072  return MakePolymorphicAction(internal::ReturnVoidAction());
1073}
1074
1075// Creates an action that returns the reference to a variable.
1076template <typename R>
1077inline internal::ReturnRefAction<R> ReturnRef(R& x) {  // NOLINT
1078  return internal::ReturnRefAction<R>(x);
1079}
1080
1081// Creates an action that returns the reference to a copy of the
1082// argument.  The copy is created when the action is constructed and
1083// lives as long as the action.
1084template <typename R>
1085inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1086  return internal::ReturnRefOfCopyAction<R>(x);
1087}
1088
1089// Modifies the parent action (a Return() action) to perform a move of the
1090// argument instead of a copy.
1091// Return(ByMove()) actions can only be executed once and will assert this
1092// invariant.
1093template <typename R>
1094internal::ByMoveWrapper<R> ByMove(R x) {
1095  return internal::ByMoveWrapper<R>(internal::move(x));
1096}
1097
1098// Creates an action that does the default action for the give mock function.
1099inline internal::DoDefaultAction DoDefault() {
1100  return internal::DoDefaultAction();
1101}
1102
1103// Creates an action that sets the variable pointed by the N-th
1104// (0-based) function argument to 'value'.
1105template <size_t N, typename T>
1106PolymorphicAction<
1107  internal::SetArgumentPointeeAction<
1108    N, T, internal::IsAProtocolMessage<T>::value> >
1109SetArgPointee(const T& x) {
1110  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1111      N, T, internal::IsAProtocolMessage<T>::value>(x));
1112}
1113
1114#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
1115// This overload allows SetArgPointee() to accept a string literal.
1116// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
1117// this overload from the templated version and emit a compile error.
1118template <size_t N>
1119PolymorphicAction<
1120  internal::SetArgumentPointeeAction<N, const char*, false> >
1121SetArgPointee(const char* p) {
1122  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1123      N, const char*, false>(p));
1124}
1125
1126template <size_t N>
1127PolymorphicAction<
1128  internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
1129SetArgPointee(const wchar_t* p) {
1130  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1131      N, const wchar_t*, false>(p));
1132}
1133#endif
1134
1135// The following version is DEPRECATED.
1136template <size_t N, typename T>
1137PolymorphicAction<
1138  internal::SetArgumentPointeeAction<
1139    N, T, internal::IsAProtocolMessage<T>::value> >
1140SetArgumentPointee(const T& x) {
1141  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1142      N, T, internal::IsAProtocolMessage<T>::value>(x));
1143}
1144
1145// Creates an action that sets a pointer referent to a given value.
1146template <typename T1, typename T2>
1147PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1148  return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1149}
1150
1151#if !GTEST_OS_WINDOWS_MOBILE
1152
1153// Creates an action that sets errno and returns the appropriate error.
1154template <typename T>
1155PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1156SetErrnoAndReturn(int errval, T result) {
1157  return MakePolymorphicAction(
1158      internal::SetErrnoAndReturnAction<T>(errval, result));
1159}
1160
1161#endif  // !GTEST_OS_WINDOWS_MOBILE
1162
1163// Various overloads for InvokeWithoutArgs().
1164
1165// Creates an action that invokes 'function_impl' with no argument.
1166template <typename FunctionImpl>
1167PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
1168InvokeWithoutArgs(FunctionImpl function_impl) {
1169  return MakePolymorphicAction(
1170      internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
1171}
1172
1173// Creates an action that invokes the given method on the given object
1174// with no argument.
1175template <class Class, typename MethodPtr>
1176PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
1177InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
1178  return MakePolymorphicAction(
1179      internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
1180          obj_ptr, method_ptr));
1181}
1182
1183// Creates an action that performs an_action and throws away its
1184// result.  In other words, it changes the return type of an_action to
1185// void.  an_action MUST NOT return void, or the code won't compile.
1186template <typename A>
1187inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1188  return internal::IgnoreResultAction<A>(an_action);
1189}
1190
1191// Creates a reference wrapper for the given L-value.  If necessary,
1192// you can explicitly specify the type of the reference.  For example,
1193// suppose 'derived' is an object of type Derived, ByRef(derived)
1194// would wrap a Derived&.  If you want to wrap a const Base& instead,
1195// where Base is a base class of Derived, just write:
1196//
1197//   ByRef<const Base>(derived)
1198template <typename T>
1199inline internal::ReferenceWrapper<T> ByRef(T& l_value) {  // NOLINT
1200  return internal::ReferenceWrapper<T>(l_value);
1201}
1202
1203}  // namespace testing
1204
1205#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-cardinalities.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used cardinalities.  More
35// cardinalities can be defined by the user implementing the
36// CardinalityInterface interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
40
41#include <limits.h>
42#include <ostream>  // NOLINT
43#include "gmock/internal/gmock-port.h"
44#include "gtest/gtest.h"
45
46namespace testing {
47
48// To implement a cardinality Foo, define:
49//   1. a class FooCardinality that implements the
50//      CardinalityInterface interface, and
51//   2. a factory function that creates a Cardinality object from a
52//      const FooCardinality*.
53//
54// The two-level delegation design follows that of Matcher, providing
55// consistency for extension developers.  It also eases ownership
56// management as Cardinality objects can now be copied like plain values.
57
58// The implementation of a cardinality.
59class CardinalityInterface {
60 public:
61  virtual ~CardinalityInterface() {}
62
63  // Conservative estimate on the lower/upper bound of the number of
64  // calls allowed.
65  virtual int ConservativeLowerBound() const { return 0; }
66  virtual int ConservativeUpperBound() const { return INT_MAX; }
67
68  // Returns true iff call_count calls will satisfy this cardinality.
69  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
70
71  // Returns true iff call_count calls will saturate this cardinality.
72  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
73
74  // Describes self to an ostream.
75  virtual void DescribeTo(::std::ostream* os) const = 0;
76};
77
78// A Cardinality is a copyable and IMMUTABLE (except by assignment)
79// object that specifies how many times a mock function is expected to
80// be called.  The implementation of Cardinality is just a linked_ptr
81// to const CardinalityInterface, so copying is fairly cheap.
82// Don't inherit from Cardinality!
83class GTEST_API_ Cardinality {
84 public:
85  // Constructs a null cardinality.  Needed for storing Cardinality
86  // objects in STL containers.
87  Cardinality() {}
88
89  // Constructs a Cardinality from its implementation.
90  explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
91
92  // Conservative estimate on the lower/upper bound of the number of
93  // calls allowed.
94  int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
95  int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
96
97  // Returns true iff call_count calls will satisfy this cardinality.
98  bool IsSatisfiedByCallCount(int call_count) const {
99    return impl_->IsSatisfiedByCallCount(call_count);
100  }
101
102  // Returns true iff call_count calls will saturate this cardinality.
103  bool IsSaturatedByCallCount(int call_count) const {
104    return impl_->IsSaturatedByCallCount(call_count);
105  }
106
107  // Returns true iff call_count calls will over-saturate this
108  // cardinality, i.e. exceed the maximum number of allowed calls.
109  bool IsOverSaturatedByCallCount(int call_count) const {
110    return impl_->IsSaturatedByCallCount(call_count) &&
111        !impl_->IsSatisfiedByCallCount(call_count);
112  }
113
114  // Describes self to an ostream
115  void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
116
117  // Describes the given actual call count to an ostream.
118  static void DescribeActualCallCountTo(int actual_call_count,
119                                        ::std::ostream* os);
120
121 private:
122  internal::linked_ptr<const CardinalityInterface> impl_;
123};
124
125// Creates a cardinality that allows at least n calls.
126GTEST_API_ Cardinality AtLeast(int n);
127
128// Creates a cardinality that allows at most n calls.
129GTEST_API_ Cardinality AtMost(int n);
130
131// Creates a cardinality that allows any number of calls.
132GTEST_API_ Cardinality AnyNumber();
133
134// Creates a cardinality that allows between min and max calls.
135GTEST_API_ Cardinality Between(int min, int max);
136
137// Creates a cardinality that allows exactly n calls.
138GTEST_API_ Cardinality Exactly(int n);
139
140// Creates a cardinality from its implementation.
141inline Cardinality MakeCardinality(const CardinalityInterface* c) {
142  return Cardinality(c);
143}
144
145}  // namespace testing
146
147#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-actions.h
r0r249096
1// This file was GENERATED by a script.  DO NOT EDIT BY HAND!!!
2
3// Copyright 2007, Google Inc.
4// All rights reserved.
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
10//     * Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//     * Redistributions in binary form must reproduce the above
13// copyright notice, this list of conditions and the following disclaimer
14// in the documentation and/or other materials provided with the
15// distribution.
16//     * Neither the name of Google Inc. nor the names of its
17// contributors may be used to endorse or promote products derived from
18// this software without specific prior written permission.
19//
20// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34// Google Mock - a framework for writing C++ mock classes.
35//
36// This file implements some commonly used variadic actions.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
40
41#include "gmock/gmock-actions.h"
42#include "gmock/internal/gmock-port.h"
43
44namespace testing {
45namespace internal {
46
47// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
48// function or method with the unpacked values, where F is a function
49// type that takes N arguments.
50template <typename Result, typename ArgumentTuple>
51class InvokeHelper;
52
53template <typename R>
54class InvokeHelper<R, ::testing::tuple<> > {
55 public:
56  template <typename Function>
57  static R Invoke(Function function, const ::testing::tuple<>&) {
58           return function();
59  }
60
61  template <class Class, typename MethodPtr>
62  static R InvokeMethod(Class* obj_ptr,
63                        MethodPtr method_ptr,
64                        const ::testing::tuple<>&) {
65           return (obj_ptr->*method_ptr)();
66  }
67};
68
69template <typename R, typename A1>
70class InvokeHelper<R, ::testing::tuple<A1> > {
71 public:
72  template <typename Function>
73  static R Invoke(Function function, const ::testing::tuple<A1>& args) {
74           return function(get<0>(args));
75  }
76
77  template <class Class, typename MethodPtr>
78  static R InvokeMethod(Class* obj_ptr,
79                        MethodPtr method_ptr,
80                        const ::testing::tuple<A1>& args) {
81           return (obj_ptr->*method_ptr)(get<0>(args));
82  }
83};
84
85template <typename R, typename A1, typename A2>
86class InvokeHelper<R, ::testing::tuple<A1, A2> > {
87 public:
88  template <typename Function>
89  static R Invoke(Function function, const ::testing::tuple<A1, A2>& args) {
90           return function(get<0>(args), get<1>(args));
91  }
92
93  template <class Class, typename MethodPtr>
94  static R InvokeMethod(Class* obj_ptr,
95                        MethodPtr method_ptr,
96                        const ::testing::tuple<A1, A2>& args) {
97           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args));
98  }
99};
100
101template <typename R, typename A1, typename A2, typename A3>
102class InvokeHelper<R, ::testing::tuple<A1, A2, A3> > {
103 public:
104  template <typename Function>
105  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3>& args) {
106           return function(get<0>(args), get<1>(args), get<2>(args));
107  }
108
109  template <class Class, typename MethodPtr>
110  static R InvokeMethod(Class* obj_ptr,
111                        MethodPtr method_ptr,
112                        const ::testing::tuple<A1, A2, A3>& args) {
113           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
114               get<2>(args));
115  }
116};
117
118template <typename R, typename A1, typename A2, typename A3, typename A4>
119class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4> > {
120 public:
121  template <typename Function>
122  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3,
123      A4>& args) {
124           return function(get<0>(args), get<1>(args), get<2>(args),
125               get<3>(args));
126  }
127
128  template <class Class, typename MethodPtr>
129  static R InvokeMethod(Class* obj_ptr,
130                        MethodPtr method_ptr,
131                        const ::testing::tuple<A1, A2, A3, A4>& args) {
132           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
133               get<2>(args), get<3>(args));
134  }
135};
136
137template <typename R, typename A1, typename A2, typename A3, typename A4,
138    typename A5>
139class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5> > {
140 public:
141  template <typename Function>
142  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4,
143      A5>& args) {
144           return function(get<0>(args), get<1>(args), get<2>(args),
145               get<3>(args), get<4>(args));
146  }
147
148  template <class Class, typename MethodPtr>
149  static R InvokeMethod(Class* obj_ptr,
150                        MethodPtr method_ptr,
151                        const ::testing::tuple<A1, A2, A3, A4, A5>& args) {
152           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
153               get<2>(args), get<3>(args), get<4>(args));
154  }
155};
156
157template <typename R, typename A1, typename A2, typename A3, typename A4,
158    typename A5, typename A6>
159class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
160 public:
161  template <typename Function>
162  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
163      A6>& args) {
164           return function(get<0>(args), get<1>(args), get<2>(args),
165               get<3>(args), get<4>(args), get<5>(args));
166  }
167
168  template <class Class, typename MethodPtr>
169  static R InvokeMethod(Class* obj_ptr,
170                        MethodPtr method_ptr,
171                        const ::testing::tuple<A1, A2, A3, A4, A5, A6>& args) {
172           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
173               get<2>(args), get<3>(args), get<4>(args), get<5>(args));
174  }
175};
176
177template <typename R, typename A1, typename A2, typename A3, typename A4,
178    typename A5, typename A6, typename A7>
179class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
180 public:
181  template <typename Function>
182  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
183      A6, A7>& args) {
184           return function(get<0>(args), get<1>(args), get<2>(args),
185               get<3>(args), get<4>(args), get<5>(args), get<6>(args));
186  }
187
188  template <class Class, typename MethodPtr>
189  static R InvokeMethod(Class* obj_ptr,
190                        MethodPtr method_ptr,
191                        const ::testing::tuple<A1, A2, A3, A4, A5, A6,
192                            A7>& args) {
193           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
194               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
195               get<6>(args));
196  }
197};
198
199template <typename R, typename A1, typename A2, typename A3, typename A4,
200    typename A5, typename A6, typename A7, typename A8>
201class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
202 public:
203  template <typename Function>
204  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
205      A6, A7, A8>& args) {
206           return function(get<0>(args), get<1>(args), get<2>(args),
207               get<3>(args), get<4>(args), get<5>(args), get<6>(args),
208               get<7>(args));
209  }
210
211  template <class Class, typename MethodPtr>
212  static R InvokeMethod(Class* obj_ptr,
213                        MethodPtr method_ptr,
214                        const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7,
215                            A8>& args) {
216           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
217               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
218               get<6>(args), get<7>(args));
219  }
220};
221
222template <typename R, typename A1, typename A2, typename A3, typename A4,
223    typename A5, typename A6, typename A7, typename A8, typename A9>
224class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
225 public:
226  template <typename Function>
227  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
228      A6, A7, A8, A9>& args) {
229           return function(get<0>(args), get<1>(args), get<2>(args),
230               get<3>(args), get<4>(args), get<5>(args), get<6>(args),
231               get<7>(args), get<8>(args));
232  }
233
234  template <class Class, typename MethodPtr>
235  static R InvokeMethod(Class* obj_ptr,
236                        MethodPtr method_ptr,
237                        const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8,
238                            A9>& args) {
239           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
240               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
241               get<6>(args), get<7>(args), get<8>(args));
242  }
243};
244
245template <typename R, typename A1, typename A2, typename A3, typename A4,
246    typename A5, typename A6, typename A7, typename A8, typename A9,
247    typename A10>
248class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
249    A10> > {
250 public:
251  template <typename Function>
252  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
253      A6, A7, A8, A9, A10>& args) {
254           return function(get<0>(args), get<1>(args), get<2>(args),
255               get<3>(args), get<4>(args), get<5>(args), get<6>(args),
256               get<7>(args), get<8>(args), get<9>(args));
257  }
258
259  template <class Class, typename MethodPtr>
260  static R InvokeMethod(Class* obj_ptr,
261                        MethodPtr method_ptr,
262                        const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8,
263                            A9, A10>& args) {
264           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
265               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
266               get<6>(args), get<7>(args), get<8>(args), get<9>(args));
267  }
268};
269
270// An INTERNAL macro for extracting the type of a tuple field.  It's
271// subject to change without notice - DO NOT USE IN USER CODE!
272#define GMOCK_FIELD_(Tuple, N) \
273    typename ::testing::tuple_element<N, Tuple>::type
274
275// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::type is the
276// type of an n-ary function whose i-th (1-based) argument type is the
277// k{i}-th (0-based) field of ArgumentTuple, which must be a tuple
278// type, and whose return type is Result.  For example,
279//   SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type
280// is int(bool, long).
281//
282// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args)
283// returns the selected fields (k1, k2, ..., k_n) of args as a tuple.
284// For example,
285//   SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select(
286//       ::testing::make_tuple(true, 'a', 2.5))
287// returns tuple (2.5, true).
288//
289// The numbers in list k1, k2, ..., k_n must be >= 0, where n can be
290// in the range [0, 10].  Duplicates are allowed and they don't have
291// to be in an ascending or descending order.
292
293template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
294    int k4, int k5, int k6, int k7, int k8, int k9, int k10>
295class SelectArgs {
296 public:
297  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
298      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
299      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
300      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7),
301      GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9),
302      GMOCK_FIELD_(ArgumentTuple, k10));
303  typedef typename Function<type>::ArgumentTuple SelectedArgs;
304  static SelectedArgs Select(const ArgumentTuple& args) {
305    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
306        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args),
307        get<k8>(args), get<k9>(args), get<k10>(args));
308  }
309};
310
311template <typename Result, typename ArgumentTuple>
312class SelectArgs<Result, ArgumentTuple,
313                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
314 public:
315  typedef Result type();
316  typedef typename Function<type>::ArgumentTuple SelectedArgs;
317  static SelectedArgs Select(const ArgumentTuple& /* args */) {
318    return SelectedArgs();
319  }
320};
321
322template <typename Result, typename ArgumentTuple, int k1>
323class SelectArgs<Result, ArgumentTuple,
324                 k1, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
325 public:
326  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1));
327  typedef typename Function<type>::ArgumentTuple SelectedArgs;
328  static SelectedArgs Select(const ArgumentTuple& args) {
329    return SelectedArgs(get<k1>(args));
330  }
331};
332
333template <typename Result, typename ArgumentTuple, int k1, int k2>
334class SelectArgs<Result, ArgumentTuple,
335                 k1, k2, -1, -1, -1, -1, -1, -1, -1, -1> {
336 public:
337  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
338      GMOCK_FIELD_(ArgumentTuple, k2));
339  typedef typename Function<type>::ArgumentTuple SelectedArgs;
340  static SelectedArgs Select(const ArgumentTuple& args) {
341    return SelectedArgs(get<k1>(args), get<k2>(args));
342  }
343};
344
345template <typename Result, typename ArgumentTuple, int k1, int k2, int k3>
346class SelectArgs<Result, ArgumentTuple,
347                 k1, k2, k3, -1, -1, -1, -1, -1, -1, -1> {
348 public:
349  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
350      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3));
351  typedef typename Function<type>::ArgumentTuple SelectedArgs;
352  static SelectedArgs Select(const ArgumentTuple& args) {
353    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args));
354  }
355};
356
357template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
358    int k4>
359class SelectArgs<Result, ArgumentTuple,
360                 k1, k2, k3, k4, -1, -1, -1, -1, -1, -1> {
361 public:
362  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
363      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
364      GMOCK_FIELD_(ArgumentTuple, k4));
365  typedef typename Function<type>::ArgumentTuple SelectedArgs;
366  static SelectedArgs Select(const ArgumentTuple& args) {
367    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
368        get<k4>(args));
369  }
370};
371
372template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
373    int k4, int k5>
374class SelectArgs<Result, ArgumentTuple,
375                 k1, k2, k3, k4, k5, -1, -1, -1, -1, -1> {
376 public:
377  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
378      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
379      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5));
380  typedef typename Function<type>::ArgumentTuple SelectedArgs;
381  static SelectedArgs Select(const ArgumentTuple& args) {
382    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
383        get<k4>(args), get<k5>(args));
384  }
385};
386
387template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
388    int k4, int k5, int k6>
389class SelectArgs<Result, ArgumentTuple,
390                 k1, k2, k3, k4, k5, k6, -1, -1, -1, -1> {
391 public:
392  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
393      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
394      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
395      GMOCK_FIELD_(ArgumentTuple, k6));
396  typedef typename Function<type>::ArgumentTuple SelectedArgs;
397  static SelectedArgs Select(const ArgumentTuple& args) {
398    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
399        get<k4>(args), get<k5>(args), get<k6>(args));
400  }
401};
402
403template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
404    int k4, int k5, int k6, int k7>
405class SelectArgs<Result, ArgumentTuple,
406                 k1, k2, k3, k4, k5, k6, k7, -1, -1, -1> {
407 public:
408  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
409      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
410      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
411      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7));
412  typedef typename Function<type>::ArgumentTuple SelectedArgs;
413  static SelectedArgs Select(const ArgumentTuple& args) {
414    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
415        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args));
416  }
417};
418
419template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
420    int k4, int k5, int k6, int k7, int k8>
421class SelectArgs<Result, ArgumentTuple,
422                 k1, k2, k3, k4, k5, k6, k7, k8, -1, -1> {
423 public:
424  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
425      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
426      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
427      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7),
428      GMOCK_FIELD_(ArgumentTuple, k8));
429  typedef typename Function<type>::ArgumentTuple SelectedArgs;
430  static SelectedArgs Select(const ArgumentTuple& args) {
431    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
432        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args),
433        get<k8>(args));
434  }
435};
436
437template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
438    int k4, int k5, int k6, int k7, int k8, int k9>
439class SelectArgs<Result, ArgumentTuple,
440                 k1, k2, k3, k4, k5, k6, k7, k8, k9, -1> {
441 public:
442  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
443      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
444      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
445      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7),
446      GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9));
447  typedef typename Function<type>::ArgumentTuple SelectedArgs;
448  static SelectedArgs Select(const ArgumentTuple& args) {
449    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
450        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args),
451        get<k8>(args), get<k9>(args));
452  }
453};
454
455#undef GMOCK_FIELD_
456
457// Implements the WithArgs action.
458template <typename InnerAction, int k1 = -1, int k2 = -1, int k3 = -1,
459    int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1,
460    int k9 = -1, int k10 = -1>
461class WithArgsAction {
462 public:
463  explicit WithArgsAction(const InnerAction& action) : action_(action) {}
464
465  template <typename F>
466  operator Action<F>() const { return MakeAction(new Impl<F>(action_)); }
467
468 private:
469  template <typename F>
470  class Impl : public ActionInterface<F> {
471   public:
472    typedef typename Function<F>::Result Result;
473    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
474
475    explicit Impl(const InnerAction& action) : action_(action) {}
476
477    virtual Result Perform(const ArgumentTuple& args) {
478      return action_.Perform(SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4,
479          k5, k6, k7, k8, k9, k10>::Select(args));
480    }
481
482   private:
483    typedef typename SelectArgs<Result, ArgumentTuple,
484        k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>::type InnerFunctionType;
485
486    Action<InnerFunctionType> action_;
487  };
488
489  const InnerAction action_;
490
491  GTEST_DISALLOW_ASSIGN_(WithArgsAction);
492};
493
494// A macro from the ACTION* family (defined later in this file)
495// defines an action that can be used in a mock function.  Typically,
496// these actions only care about a subset of the arguments of the mock
497// function.  For example, if such an action only uses the second
498// argument, it can be used in any mock function that takes >= 2
499// arguments where the type of the second argument is compatible.
500//
501// Therefore, the action implementation must be prepared to take more
502// arguments than it needs.  The ExcessiveArg type is used to
503// represent those excessive arguments.  In order to keep the compiler
504// error messages tractable, we define it in the testing namespace
505// instead of testing::internal.  However, this is an INTERNAL TYPE
506// and subject to change without notice, so a user MUST NOT USE THIS
507// TYPE DIRECTLY.
508struct ExcessiveArg {};
509
510// A helper class needed for implementing the ACTION* macros.
511template <typename Result, class Impl>
512class ActionHelper {
513 public:
514  static Result Perform(Impl* impl, const ::testing::tuple<>& args) {
515    return impl->template gmock_PerformImpl<>(args, ExcessiveArg(),
516        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
517        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
518        ExcessiveArg());
519  }
520
521  template <typename A0>
522  static Result Perform(Impl* impl, const ::testing::tuple<A0>& args) {
523    return impl->template gmock_PerformImpl<A0>(args, get<0>(args),
524        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
525        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
526        ExcessiveArg());
527  }
528
529  template <typename A0, typename A1>
530  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1>& args) {
531    return impl->template gmock_PerformImpl<A0, A1>(args, get<0>(args),
532        get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
533        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
534        ExcessiveArg());
535  }
536
537  template <typename A0, typename A1, typename A2>
538  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2>& args) {
539    return impl->template gmock_PerformImpl<A0, A1, A2>(args, get<0>(args),
540        get<1>(args), get<2>(args), ExcessiveArg(), ExcessiveArg(),
541        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
542        ExcessiveArg());
543  }
544
545  template <typename A0, typename A1, typename A2, typename A3>
546  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2,
547      A3>& args) {
548    return impl->template gmock_PerformImpl<A0, A1, A2, A3>(args, get<0>(args),
549        get<1>(args), get<2>(args), get<3>(args), ExcessiveArg(),
550        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
551        ExcessiveArg());
552  }
553
554  template <typename A0, typename A1, typename A2, typename A3, typename A4>
555  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3,
556      A4>& args) {
557    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4>(args,
558        get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args),
559        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
560        ExcessiveArg());
561  }
562
563  template <typename A0, typename A1, typename A2, typename A3, typename A4,
564      typename A5>
565  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
566      A5>& args) {
567    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5>(args,
568        get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args),
569        get<5>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
570        ExcessiveArg());
571  }
572
573  template <typename A0, typename A1, typename A2, typename A3, typename A4,
574      typename A5, typename A6>
575  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
576      A5, A6>& args) {
577    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6>(args,
578        get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args),
579        get<5>(args), get<6>(args), ExcessiveArg(), ExcessiveArg(),
580        ExcessiveArg());
581  }
582
583  template <typename A0, typename A1, typename A2, typename A3, typename A4,
584      typename A5, typename A6, typename A7>
585  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
586      A5, A6, A7>& args) {
587    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6,
588        A7>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args),
589        get<4>(args), get<5>(args), get<6>(args), get<7>(args), ExcessiveArg(),
590        ExcessiveArg());
591  }
592
593  template <typename A0, typename A1, typename A2, typename A3, typename A4,
594      typename A5, typename A6, typename A7, typename A8>
595  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
596      A5, A6, A7, A8>& args) {
597    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7,
598        A8>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args),
599        get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args),
600        ExcessiveArg());
601  }
602
603  template <typename A0, typename A1, typename A2, typename A3, typename A4,
604      typename A5, typename A6, typename A7, typename A8, typename A9>
605  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
606      A5, A6, A7, A8, A9>& args) {
607    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, A8,
608        A9>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args),
609        get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args),
610        get<9>(args));
611  }
612};
613
614}  // namespace internal
615
616// Various overloads for Invoke().
617
618// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
619// the selected arguments of the mock function to an_action and
620// performs it.  It serves as an adaptor between actions with
621// different argument lists.  C++ doesn't support default arguments for
622// function templates, so we have to overload it.
623template <int k1, typename InnerAction>
624inline internal::WithArgsAction<InnerAction, k1>
625WithArgs(const InnerAction& action) {
626  return internal::WithArgsAction<InnerAction, k1>(action);
627}
628
629template <int k1, int k2, typename InnerAction>
630inline internal::WithArgsAction<InnerAction, k1, k2>
631WithArgs(const InnerAction& action) {
632  return internal::WithArgsAction<InnerAction, k1, k2>(action);
633}
634
635template <int k1, int k2, int k3, typename InnerAction>
636inline internal::WithArgsAction<InnerAction, k1, k2, k3>
637WithArgs(const InnerAction& action) {
638  return internal::WithArgsAction<InnerAction, k1, k2, k3>(action);
639}
640
641template <int k1, int k2, int k3, int k4, typename InnerAction>
642inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4>
643WithArgs(const InnerAction& action) {
644  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4>(action);
645}
646
647template <int k1, int k2, int k3, int k4, int k5, typename InnerAction>
648inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5>
649WithArgs(const InnerAction& action) {
650  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5>(action);
651}
652
653template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerAction>
654inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6>
655WithArgs(const InnerAction& action) {
656  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6>(action);
657}
658
659template <int k1, int k2, int k3, int k4, int k5, int k6, int k7,
660    typename InnerAction>
661inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7>
662WithArgs(const InnerAction& action) {
663  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6,
664      k7>(action);
665}
666
667template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
668    typename InnerAction>
669inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8>
670WithArgs(const InnerAction& action) {
671  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7,
672      k8>(action);
673}
674
675template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
676    int k9, typename InnerAction>
677inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, k9>
678WithArgs(const InnerAction& action) {
679  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8,
680      k9>(action);
681}
682
683template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
684    int k9, int k10, typename InnerAction>
685inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8,
686    k9, k10>
687WithArgs(const InnerAction& action) {
688  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8,
689      k9, k10>(action);
690}
691
692// Creates an action that does actions a1, a2, ..., sequentially in
693// each invocation.
694template <typename Action1, typename Action2>
695inline internal::DoBothAction<Action1, Action2>
696DoAll(Action1 a1, Action2 a2) {
697  return internal::DoBothAction<Action1, Action2>(a1, a2);
698}
699
700template <typename Action1, typename Action2, typename Action3>
701inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
702    Action3> >
703DoAll(Action1 a1, Action2 a2, Action3 a3) {
704  return DoAll(a1, DoAll(a2, a3));
705}
706
707template <typename Action1, typename Action2, typename Action3,
708    typename Action4>
709inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
710    internal::DoBothAction<Action3, Action4> > >
711DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4) {
712  return DoAll(a1, DoAll(a2, a3, a4));
713}
714
715template <typename Action1, typename Action2, typename Action3,
716    typename Action4, typename Action5>
717inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
718    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
719    Action5> > > >
720DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5) {
721  return DoAll(a1, DoAll(a2, a3, a4, a5));
722}
723
724template <typename Action1, typename Action2, typename Action3,
725    typename Action4, typename Action5, typename Action6>
726inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
727    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
728    internal::DoBothAction<Action5, Action6> > > > >
729DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6) {
730  return DoAll(a1, DoAll(a2, a3, a4, a5, a6));
731}
732
733template <typename Action1, typename Action2, typename Action3,
734    typename Action4, typename Action5, typename Action6, typename Action7>
735inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
736    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
737    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
738    Action7> > > > > >
739DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
740    Action7 a7) {
741  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7));
742}
743
744template <typename Action1, typename Action2, typename Action3,
745    typename Action4, typename Action5, typename Action6, typename Action7,
746    typename Action8>
747inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
748    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
749    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
750    internal::DoBothAction<Action7, Action8> > > > > > >
751DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
752    Action7 a7, Action8 a8) {
753  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8));
754}
755
756template <typename Action1, typename Action2, typename Action3,
757    typename Action4, typename Action5, typename Action6, typename Action7,
758    typename Action8, typename Action9>
759inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
760    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
761    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
762    internal::DoBothAction<Action7, internal::DoBothAction<Action8,
763    Action9> > > > > > > >
764DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
765    Action7 a7, Action8 a8, Action9 a9) {
766  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9));
767}
768
769template <typename Action1, typename Action2, typename Action3,
770    typename Action4, typename Action5, typename Action6, typename Action7,
771    typename Action8, typename Action9, typename Action10>
772inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
773    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
774    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
775    internal::DoBothAction<Action7, internal::DoBothAction<Action8,
776    internal::DoBothAction<Action9, Action10> > > > > > > > >
777DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
778    Action7 a7, Action8 a8, Action9 a9, Action10 a10) {
779  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9, a10));
780}
781
782}  // namespace testing
783
784// The ACTION* family of macros can be used in a namespace scope to
785// define custom actions easily.  The syntax:
786//
787//   ACTION(name) { statements; }
788//
789// will define an action with the given name that executes the
790// statements.  The value returned by the statements will be used as
791// the return value of the action.  Inside the statements, you can
792// refer to the K-th (0-based) argument of the mock function by
793// 'argK', and refer to its type by 'argK_type'.  For example:
794//
795//   ACTION(IncrementArg1) {
796//     arg1_type temp = arg1;
797//     return ++(*temp);
798//   }
799//
800// allows you to write
801//
802//   ...WillOnce(IncrementArg1());
803//
804// You can also refer to the entire argument tuple and its type by
805// 'args' and 'args_type', and refer to the mock function type and its
806// return type by 'function_type' and 'return_type'.
807//
808// Note that you don't need to specify the types of the mock function
809// arguments.  However rest assured that your code is still type-safe:
810// you'll get a compiler error if *arg1 doesn't support the ++
811// operator, or if the type of ++(*arg1) isn't compatible with the
812// mock function's return type, for example.
813//
814// Sometimes you'll want to parameterize the action.   For that you can use
815// another macro:
816//
817//   ACTION_P(name, param_name) { statements; }
818//
819// For example:
820//
821//   ACTION_P(Add, n) { return arg0 + n; }
822//
823// will allow you to write:
824//
825//   ...WillOnce(Add(5));
826//
827// Note that you don't need to provide the type of the parameter
828// either.  If you need to reference the type of a parameter named
829// 'foo', you can write 'foo_type'.  For example, in the body of
830// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
831// of 'n'.
832//
833// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
834// multi-parameter actions.
835//
836// For the purpose of typing, you can view
837//
838//   ACTION_Pk(Foo, p1, ..., pk) { ... }
839//
840// as shorthand for
841//
842//   template <typename p1_type, ..., typename pk_type>
843//   FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
844//
845// In particular, you can provide the template type arguments
846// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
847// although usually you can rely on the compiler to infer the types
848// for you automatically.  You can assign the result of expression
849// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
850// pk_type>.  This can be useful when composing actions.
851//
852// You can also overload actions with different numbers of parameters:
853//
854//   ACTION_P(Plus, a) { ... }
855//   ACTION_P2(Plus, a, b) { ... }
856//
857// While it's tempting to always use the ACTION* macros when defining
858// a new action, you should also consider implementing ActionInterface
859// or using MakePolymorphicAction() instead, especially if you need to
860// use the action a lot.  While these approaches require more work,
861// they give you more control on the types of the mock function
862// arguments and the action parameters, which in general leads to
863// better compiler error messages that pay off in the long run.  They
864// also allow overloading actions based on parameter types (as opposed
865// to just based on the number of parameters).
866//
867// CAVEAT:
868//
869// ACTION*() can only be used in a namespace scope.  The reason is
870// that C++ doesn't yet allow function-local types to be used to
871// instantiate templates.  The up-coming C++0x standard will fix this.
872// Once that's done, we'll consider supporting using ACTION*() inside
873// a function.
874//
875// MORE INFORMATION:
876//
877// To learn more about using these macros, please search for 'ACTION'
878// on http://code.google.com/p/googlemock/wiki/CookBook.
879
880// An internal macro needed for implementing ACTION*().
881#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
882    const args_type& args GTEST_ATTRIBUTE_UNUSED_, \
883    arg0_type arg0 GTEST_ATTRIBUTE_UNUSED_, \
884    arg1_type arg1 GTEST_ATTRIBUTE_UNUSED_, \
885    arg2_type arg2 GTEST_ATTRIBUTE_UNUSED_, \
886    arg3_type arg3 GTEST_ATTRIBUTE_UNUSED_, \
887    arg4_type arg4 GTEST_ATTRIBUTE_UNUSED_, \
888    arg5_type arg5 GTEST_ATTRIBUTE_UNUSED_, \
889    arg6_type arg6 GTEST_ATTRIBUTE_UNUSED_, \
890    arg7_type arg7 GTEST_ATTRIBUTE_UNUSED_, \
891    arg8_type arg8 GTEST_ATTRIBUTE_UNUSED_, \
892    arg9_type arg9 GTEST_ATTRIBUTE_UNUSED_
893
894// Sometimes you want to give an action explicit template parameters
895// that cannot be inferred from its value parameters.  ACTION() and
896// ACTION_P*() don't support that.  ACTION_TEMPLATE() remedies that
897// and can be viewed as an extension to ACTION() and ACTION_P*().
898//
899// The syntax:
900//
901//   ACTION_TEMPLATE(ActionName,
902//                   HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
903//                   AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
904//
905// defines an action template that takes m explicit template
906// parameters and n value parameters.  name_i is the name of the i-th
907// template parameter, and kind_i specifies whether it's a typename,
908// an integral constant, or a template.  p_i is the name of the i-th
909// value parameter.
910//
911// Example:
912//
913//   // DuplicateArg<k, T>(output) converts the k-th argument of the mock
914//   // function to type T and copies it to *output.
915//   ACTION_TEMPLATE(DuplicateArg,
916//                   HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
917//                   AND_1_VALUE_PARAMS(output)) {
918//     *output = T(::testing::get<k>(args));
919//   }
920//   ...
921//     int n;
922//     EXPECT_CALL(mock, Foo(_, _))
923//         .WillOnce(DuplicateArg<1, unsigned char>(&n));
924//
925// To create an instance of an action template, write:
926//
927//   ActionName<t1, ..., t_m>(v1, ..., v_n)
928//
929// where the ts are the template arguments and the vs are the value
930// arguments.  The value argument types are inferred by the compiler.
931// If you want to explicitly specify the value argument types, you can
932// provide additional template arguments:
933//
934//   ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
935//
936// where u_i is the desired type of v_i.
937//
938// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
939// number of value parameters, but not on the number of template
940// parameters.  Without the restriction, the meaning of the following
941// is unclear:
942//
943//   OverloadedAction<int, bool>(x);
944//
945// Are we using a single-template-parameter action where 'bool' refers
946// to the type of x, or are we using a two-template-parameter action
947// where the compiler is asked to infer the type of x?
948//
949// Implementation notes:
950//
951// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
952// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
953// implementing ACTION_TEMPLATE.  The main trick we use is to create
954// new macro invocations when expanding a macro.  For example, we have
955//
956//   #define ACTION_TEMPLATE(name, template_params, value_params)
957//       ... GMOCK_INTERNAL_DECL_##template_params ...
958//
959// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
960// to expand to
961//
962//       ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
963//
964// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
965// preprocessor will continue to expand it to
966//
967//       ... typename T ...
968//
969// This technique conforms to the C++ standard and is portable.  It
970// allows us to implement action templates using O(N) code, where N is
971// the maximum number of template/value parameters supported.  Without
972// using it, we'd have to devote O(N^2) amount of code to implement all
973// combinations of m and n.
974
975// Declares the template parameters.
976#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
977#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
978    name1) kind0 name0, kind1 name1
979#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
980    kind2, name2) kind0 name0, kind1 name1, kind2 name2
981#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
982    kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
983    kind3 name3
984#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
985    kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
986    kind2 name2, kind3 name3, kind4 name4
987#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
988    kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
989    kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
990#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
991    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
992    name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
993    kind5 name5, kind6 name6
994#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
995    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
996    kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
997    kind4 name4, kind5 name5, kind6 name6, kind7 name7
998#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
999    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
1000    kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
1001    kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
1002    kind8 name8
1003#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
1004    name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
1005    name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
1006    kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
1007    kind6 name6, kind7 name7, kind8 name8, kind9 name9
1008
1009// Lists the template parameters.
1010#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
1011#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
1012    name1) name0, name1
1013#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
1014    kind2, name2) name0, name1, name2
1015#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
1016    kind2, name2, kind3, name3) name0, name1, name2, name3
1017#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
1018    kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
1019    name4
1020#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
1021    kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
1022    name2, name3, name4, name5
1023#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
1024    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
1025    name6) name0, name1, name2, name3, name4, name5, name6
1026#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
1027    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
1028    kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
1029#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
1030    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
1031    kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
1032    name6, name7, name8
1033#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
1034    name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
1035    name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
1036    name3, name4, name5, name6, name7, name8, name9
1037
1038// Declares the types of value parameters.
1039#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
1040#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
1041#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
1042    typename p0##_type, typename p1##_type
1043#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
1044    typename p0##_type, typename p1##_type, typename p2##_type
1045#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
1046    typename p0##_type, typename p1##_type, typename p2##_type, \
1047    typename p3##_type
1048#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
1049    typename p0##_type, typename p1##_type, typename p2##_type, \
1050    typename p3##_type, typename p4##_type
1051#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
1052    typename p0##_type, typename p1##_type, typename p2##_type, \
1053    typename p3##_type, typename p4##_type, typename p5##_type
1054#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1055    p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
1056    typename p3##_type, typename p4##_type, typename p5##_type, \
1057    typename p6##_type
1058#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1059    p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
1060    typename p3##_type, typename p4##_type, typename p5##_type, \
1061    typename p6##_type, typename p7##_type
1062#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1063    p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
1064    typename p3##_type, typename p4##_type, typename p5##_type, \
1065    typename p6##_type, typename p7##_type, typename p8##_type
1066#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1067    p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
1068    typename p2##_type, typename p3##_type, typename p4##_type, \
1069    typename p5##_type, typename p6##_type, typename p7##_type, \
1070    typename p8##_type, typename p9##_type
1071
1072// Initializes the value parameters.
1073#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
1074    ()
1075#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
1076    (p0##_type gmock_p0) : p0(gmock_p0)
1077#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
1078    (p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1)
1079#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
1080    (p0##_type gmock_p0, p1##_type gmock_p1, \
1081        p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2)
1082#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
1083    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1084        p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1085        p3(gmock_p3)
1086#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
1087    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1088        p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), \
1089        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4)
1090#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
1091    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1092        p3##_type gmock_p3, p4##_type gmock_p4, \
1093        p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1094        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5)
1095#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
1096    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1097        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1098        p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1099        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6)
1100#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
1101    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1102        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1103        p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), \
1104        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
1105        p7(gmock_p7)
1106#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1107    p7, p8)\
1108    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1109        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1110        p6##_type gmock_p6, p7##_type gmock_p7, \
1111        p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1112        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
1113        p8(gmock_p8)
1114#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1115    p7, p8, p9)\
1116    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1117        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1118        p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
1119        p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1120        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
1121        p8(gmock_p8), p9(gmock_p9)
1122
1123// Declares the fields for storing the value parameters.
1124#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
1125#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
1126#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
1127    p1##_type p1;
1128#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
1129    p1##_type p1; p2##_type p2;
1130#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
1131    p1##_type p1; p2##_type p2; p3##_type p3;
1132#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
1133    p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
1134#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
1135    p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
1136    p5##_type p5;
1137#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1138    p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
1139    p5##_type p5; p6##_type p6;
1140#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1141    p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
1142    p5##_type p5; p6##_type p6; p7##_type p7;
1143#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1144    p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
1145    p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
1146#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1147    p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
1148    p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
1149    p9##_type p9;
1150
1151// Lists the value parameters.
1152#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
1153#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
1154#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
1155#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
1156#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
1157#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
1158    p2, p3, p4
1159#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
1160    p1, p2, p3, p4, p5
1161#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1162    p6) p0, p1, p2, p3, p4, p5, p6
1163#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1164    p7) p0, p1, p2, p3, p4, p5, p6, p7
1165#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1166    p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
1167#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1168    p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
1169
1170// Lists the value parameter types.
1171#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
1172#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
1173#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
1174    p1##_type
1175#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
1176    p1##_type, p2##_type
1177#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
1178    p0##_type, p1##_type, p2##_type, p3##_type
1179#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
1180    p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
1181#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
1182    p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
1183#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1184    p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
1185    p6##_type
1186#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1187    p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1188    p5##_type, p6##_type, p7##_type
1189#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1190    p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1191    p5##_type, p6##_type, p7##_type, p8##_type
1192#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1193    p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1194    p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
1195
1196// Declares the value parameters.
1197#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
1198#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
1199#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
1200    p1##_type p1
1201#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
1202    p1##_type p1, p2##_type p2
1203#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
1204    p1##_type p1, p2##_type p2, p3##_type p3
1205#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
1206    p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
1207#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
1208    p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
1209    p5##_type p5
1210#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
1211    p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
1212    p5##_type p5, p6##_type p6
1213#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1214    p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
1215    p5##_type p5, p6##_type p6, p7##_type p7
1216#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1217    p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
1218    p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
1219#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1220    p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
1221    p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
1222    p9##_type p9
1223
1224// The suffix of the class template implementing the action template.
1225#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
1226#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
1227#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
1228#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
1229#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
1230#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
1231#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
1232#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
1233#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1234    p7) P8
1235#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1236    p7, p8) P9
1237#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
1238    p7, p8, p9) P10
1239
1240// The name of the class template implementing the action template.
1241#define GMOCK_ACTION_CLASS_(name, value_params)\
1242    GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
1243
1244#define ACTION_TEMPLATE(name, template_params, value_params)\
1245  template <GMOCK_INTERNAL_DECL_##template_params\
1246            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
1247  class GMOCK_ACTION_CLASS_(name, value_params) {\
1248   public:\
1249    explicit GMOCK_ACTION_CLASS_(name, value_params)\
1250        GMOCK_INTERNAL_INIT_##value_params {}\
1251    template <typename F>\
1252    class gmock_Impl : public ::testing::ActionInterface<F> {\
1253     public:\
1254      typedef F function_type;\
1255      typedef typename ::testing::internal::Function<F>::Result return_type;\
1256      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1257          args_type;\
1258      explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\
1259      virtual return_type Perform(const args_type& args) {\
1260        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1261            Perform(this, args);\
1262      }\
1263      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1264          typename arg3_type, typename arg4_type, typename arg5_type, \
1265          typename arg6_type, typename arg7_type, typename arg8_type, \
1266          typename arg9_type>\
1267      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1268          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1269          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1270          arg9_type arg9) const;\
1271      GMOCK_INTERNAL_DEFN_##value_params\
1272     private:\
1273      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1274    };\
1275    template <typename F> operator ::testing::Action<F>() const {\
1276      return ::testing::Action<F>(\
1277          new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
1278    }\
1279    GMOCK_INTERNAL_DEFN_##value_params\
1280   private:\
1281    GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
1282  };\
1283  template <GMOCK_INTERNAL_DECL_##template_params\
1284            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
1285  inline GMOCK_ACTION_CLASS_(name, value_params)<\
1286      GMOCK_INTERNAL_LIST_##template_params\
1287      GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\
1288          GMOCK_INTERNAL_DECL_##value_params) {\
1289    return GMOCK_ACTION_CLASS_(name, value_params)<\
1290        GMOCK_INTERNAL_LIST_##template_params\
1291        GMOCK_INTERNAL_LIST_TYPE_##value_params>(\
1292            GMOCK_INTERNAL_LIST_##value_params);\
1293  }\
1294  template <GMOCK_INTERNAL_DECL_##template_params\
1295            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
1296  template <typename F>\
1297  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1298      typename arg3_type, typename arg4_type, typename arg5_type, \
1299      typename arg6_type, typename arg7_type, typename arg8_type, \
1300      typename arg9_type>\
1301  typename ::testing::internal::Function<F>::Result\
1302      GMOCK_ACTION_CLASS_(name, value_params)<\
1303          GMOCK_INTERNAL_LIST_##template_params\
1304          GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\
1305              gmock_PerformImpl(\
1306          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1307
1308#define ACTION(name)\
1309  class name##Action {\
1310   public:\
1311    name##Action() {}\
1312    template <typename F>\
1313    class gmock_Impl : public ::testing::ActionInterface<F> {\
1314     public:\
1315      typedef F function_type;\
1316      typedef typename ::testing::internal::Function<F>::Result return_type;\
1317      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1318          args_type;\
1319      gmock_Impl() {}\
1320      virtual return_type Perform(const args_type& args) {\
1321        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1322            Perform(this, args);\
1323      }\
1324      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1325          typename arg3_type, typename arg4_type, typename arg5_type, \
1326          typename arg6_type, typename arg7_type, typename arg8_type, \
1327          typename arg9_type>\
1328      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1329          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1330          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1331          arg9_type arg9) const;\
1332     private:\
1333      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1334    };\
1335    template <typename F> operator ::testing::Action<F>() const {\
1336      return ::testing::Action<F>(new gmock_Impl<F>());\
1337    }\
1338   private:\
1339    GTEST_DISALLOW_ASSIGN_(name##Action);\
1340  };\
1341  inline name##Action name() {\
1342    return name##Action();\
1343  }\
1344  template <typename F>\
1345  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1346      typename arg3_type, typename arg4_type, typename arg5_type, \
1347      typename arg6_type, typename arg7_type, typename arg8_type, \
1348      typename arg9_type>\
1349  typename ::testing::internal::Function<F>::Result\
1350      name##Action::gmock_Impl<F>::gmock_PerformImpl(\
1351          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1352
1353#define ACTION_P(name, p0)\
1354  template <typename p0##_type>\
1355  class name##ActionP {\
1356   public:\
1357    explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {}\
1358    template <typename F>\
1359    class gmock_Impl : public ::testing::ActionInterface<F> {\
1360     public:\
1361      typedef F function_type;\
1362      typedef typename ::testing::internal::Function<F>::Result return_type;\
1363      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1364          args_type;\
1365      explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {}\
1366      virtual return_type Perform(const args_type& args) {\
1367        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1368            Perform(this, args);\
1369      }\
1370      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1371          typename arg3_type, typename arg4_type, typename arg5_type, \
1372          typename arg6_type, typename arg7_type, typename arg8_type, \
1373          typename arg9_type>\
1374      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1375          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1376          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1377          arg9_type arg9) const;\
1378      p0##_type p0;\
1379     private:\
1380      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1381    };\
1382    template <typename F> operator ::testing::Action<F>() const {\
1383      return ::testing::Action<F>(new gmock_Impl<F>(p0));\
1384    }\
1385    p0##_type p0;\
1386   private:\
1387    GTEST_DISALLOW_ASSIGN_(name##ActionP);\
1388  };\
1389  template <typename p0##_type>\
1390  inline name##ActionP<p0##_type> name(p0##_type p0) {\
1391    return name##ActionP<p0##_type>(p0);\
1392  }\
1393  template <typename p0##_type>\
1394  template <typename F>\
1395  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1396      typename arg3_type, typename arg4_type, typename arg5_type, \
1397      typename arg6_type, typename arg7_type, typename arg8_type, \
1398      typename arg9_type>\
1399  typename ::testing::internal::Function<F>::Result\
1400      name##ActionP<p0##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1401          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1402
1403#define ACTION_P2(name, p0, p1)\
1404  template <typename p0##_type, typename p1##_type>\
1405  class name##ActionP2 {\
1406   public:\
1407    name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
1408        p1(gmock_p1) {}\
1409    template <typename F>\
1410    class gmock_Impl : public ::testing::ActionInterface<F> {\
1411     public:\
1412      typedef F function_type;\
1413      typedef typename ::testing::internal::Function<F>::Result return_type;\
1414      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1415          args_type;\
1416      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
1417          p1(gmock_p1) {}\
1418      virtual return_type Perform(const args_type& args) {\
1419        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1420            Perform(this, args);\
1421      }\
1422      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1423          typename arg3_type, typename arg4_type, typename arg5_type, \
1424          typename arg6_type, typename arg7_type, typename arg8_type, \
1425          typename arg9_type>\
1426      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1427          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1428          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1429          arg9_type arg9) const;\
1430      p0##_type p0;\
1431      p1##_type p1;\
1432     private:\
1433      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1434    };\
1435    template <typename F> operator ::testing::Action<F>() const {\
1436      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1));\
1437    }\
1438    p0##_type p0;\
1439    p1##_type p1;\
1440   private:\
1441    GTEST_DISALLOW_ASSIGN_(name##ActionP2);\
1442  };\
1443  template <typename p0##_type, typename p1##_type>\
1444  inline name##ActionP2<p0##_type, p1##_type> name(p0##_type p0, \
1445      p1##_type p1) {\
1446    return name##ActionP2<p0##_type, p1##_type>(p0, p1);\
1447  }\
1448  template <typename p0##_type, typename p1##_type>\
1449  template <typename F>\
1450  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1451      typename arg3_type, typename arg4_type, typename arg5_type, \
1452      typename arg6_type, typename arg7_type, typename arg8_type, \
1453      typename arg9_type>\
1454  typename ::testing::internal::Function<F>::Result\
1455      name##ActionP2<p0##_type, p1##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1456          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1457
1458#define ACTION_P3(name, p0, p1, p2)\
1459  template <typename p0##_type, typename p1##_type, typename p2##_type>\
1460  class name##ActionP3 {\
1461   public:\
1462    name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \
1463        p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
1464    template <typename F>\
1465    class gmock_Impl : public ::testing::ActionInterface<F> {\
1466     public:\
1467      typedef F function_type;\
1468      typedef typename ::testing::internal::Function<F>::Result return_type;\
1469      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1470          args_type;\
1471      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \
1472          p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
1473      virtual return_type Perform(const args_type& args) {\
1474        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1475            Perform(this, args);\
1476      }\
1477      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1478          typename arg3_type, typename arg4_type, typename arg5_type, \
1479          typename arg6_type, typename arg7_type, typename arg8_type, \
1480          typename arg9_type>\
1481      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1482          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1483          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1484          arg9_type arg9) const;\
1485      p0##_type p0;\
1486      p1##_type p1;\
1487      p2##_type p2;\
1488     private:\
1489      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1490    };\
1491    template <typename F> operator ::testing::Action<F>() const {\
1492      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2));\
1493    }\
1494    p0##_type p0;\
1495    p1##_type p1;\
1496    p2##_type p2;\
1497   private:\
1498    GTEST_DISALLOW_ASSIGN_(name##ActionP3);\
1499  };\
1500  template <typename p0##_type, typename p1##_type, typename p2##_type>\
1501  inline name##ActionP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
1502      p1##_type p1, p2##_type p2) {\
1503    return name##ActionP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
1504  }\
1505  template <typename p0##_type, typename p1##_type, typename p2##_type>\
1506  template <typename F>\
1507  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1508      typename arg3_type, typename arg4_type, typename arg5_type, \
1509      typename arg6_type, typename arg7_type, typename arg8_type, \
1510      typename arg9_type>\
1511  typename ::testing::internal::Function<F>::Result\
1512      name##ActionP3<p0##_type, p1##_type, \
1513          p2##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1514          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1515
1516#define ACTION_P4(name, p0, p1, p2, p3)\
1517  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1518      typename p3##_type>\
1519  class name##ActionP4 {\
1520   public:\
1521    name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \
1522        p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \
1523        p2(gmock_p2), p3(gmock_p3) {}\
1524    template <typename F>\
1525    class gmock_Impl : public ::testing::ActionInterface<F> {\
1526     public:\
1527      typedef F function_type;\
1528      typedef typename ::testing::internal::Function<F>::Result return_type;\
1529      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1530          args_type;\
1531      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1532          p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1533          p3(gmock_p3) {}\
1534      virtual return_type Perform(const args_type& args) {\
1535        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1536            Perform(this, args);\
1537      }\
1538      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1539          typename arg3_type, typename arg4_type, typename arg5_type, \
1540          typename arg6_type, typename arg7_type, typename arg8_type, \
1541          typename arg9_type>\
1542      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1543          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1544          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1545          arg9_type arg9) const;\
1546      p0##_type p0;\
1547      p1##_type p1;\
1548      p2##_type p2;\
1549      p3##_type p3;\
1550     private:\
1551      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1552    };\
1553    template <typename F> operator ::testing::Action<F>() const {\
1554      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3));\
1555    }\
1556    p0##_type p0;\
1557    p1##_type p1;\
1558    p2##_type p2;\
1559    p3##_type p3;\
1560   private:\
1561    GTEST_DISALLOW_ASSIGN_(name##ActionP4);\
1562  };\
1563  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1564      typename p3##_type>\
1565  inline name##ActionP4<p0##_type, p1##_type, p2##_type, \
1566      p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
1567      p3##_type p3) {\
1568    return name##ActionP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, p1, \
1569        p2, p3);\
1570  }\
1571  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1572      typename p3##_type>\
1573  template <typename F>\
1574  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1575      typename arg3_type, typename arg4_type, typename arg5_type, \
1576      typename arg6_type, typename arg7_type, typename arg8_type, \
1577      typename arg9_type>\
1578  typename ::testing::internal::Function<F>::Result\
1579      name##ActionP4<p0##_type, p1##_type, p2##_type, \
1580          p3##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1581          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1582
1583#define ACTION_P5(name, p0, p1, p2, p3, p4)\
1584  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1585      typename p3##_type, typename p4##_type>\
1586  class name##ActionP5 {\
1587   public:\
1588    name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \
1589        p2##_type gmock_p2, p3##_type gmock_p3, \
1590        p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1591        p3(gmock_p3), p4(gmock_p4) {}\
1592    template <typename F>\
1593    class gmock_Impl : public ::testing::ActionInterface<F> {\
1594     public:\
1595      typedef F function_type;\
1596      typedef typename ::testing::internal::Function<F>::Result return_type;\
1597      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1598          args_type;\
1599      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1600          p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), \
1601          p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {}\
1602      virtual return_type Perform(const args_type& args) {\
1603        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1604            Perform(this, args);\
1605      }\
1606      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1607          typename arg3_type, typename arg4_type, typename arg5_type, \
1608          typename arg6_type, typename arg7_type, typename arg8_type, \
1609          typename arg9_type>\
1610      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1611          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1612          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1613          arg9_type arg9) const;\
1614      p0##_type p0;\
1615      p1##_type p1;\
1616      p2##_type p2;\
1617      p3##_type p3;\
1618      p4##_type p4;\
1619     private:\
1620      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1621    };\
1622    template <typename F> operator ::testing::Action<F>() const {\
1623      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4));\
1624    }\
1625    p0##_type p0;\
1626    p1##_type p1;\
1627    p2##_type p2;\
1628    p3##_type p3;\
1629    p4##_type p4;\
1630   private:\
1631    GTEST_DISALLOW_ASSIGN_(name##ActionP5);\
1632  };\
1633  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1634      typename p3##_type, typename p4##_type>\
1635  inline name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
1636      p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
1637      p4##_type p4) {\
1638    return name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
1639        p4##_type>(p0, p1, p2, p3, p4);\
1640  }\
1641  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1642      typename p3##_type, typename p4##_type>\
1643  template <typename F>\
1644  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1645      typename arg3_type, typename arg4_type, typename arg5_type, \
1646      typename arg6_type, typename arg7_type, typename arg8_type, \
1647      typename arg9_type>\
1648  typename ::testing::internal::Function<F>::Result\
1649      name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
1650          p4##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1651          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1652
1653#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\
1654  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1655      typename p3##_type, typename p4##_type, typename p5##_type>\
1656  class name##ActionP6 {\
1657   public:\
1658    name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \
1659        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1660        p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1661        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\
1662    template <typename F>\
1663    class gmock_Impl : public ::testing::ActionInterface<F> {\
1664     public:\
1665      typedef F function_type;\
1666      typedef typename ::testing::internal::Function<F>::Result return_type;\
1667      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1668          args_type;\
1669      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1670          p3##_type gmock_p3, p4##_type gmock_p4, \
1671          p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1672          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\
1673      virtual return_type Perform(const args_type& args) {\
1674        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1675            Perform(this, args);\
1676      }\
1677      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1678          typename arg3_type, typename arg4_type, typename arg5_type, \
1679          typename arg6_type, typename arg7_type, typename arg8_type, \
1680          typename arg9_type>\
1681      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1682          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1683          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1684          arg9_type arg9) const;\
1685      p0##_type p0;\
1686      p1##_type p1;\
1687      p2##_type p2;\
1688      p3##_type p3;\
1689      p4##_type p4;\
1690      p5##_type p5;\
1691     private:\
1692      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1693    };\
1694    template <typename F> operator ::testing::Action<F>() const {\
1695      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5));\
1696    }\
1697    p0##_type p0;\
1698    p1##_type p1;\
1699    p2##_type p2;\
1700    p3##_type p3;\
1701    p4##_type p4;\
1702    p5##_type p5;\
1703   private:\
1704    GTEST_DISALLOW_ASSIGN_(name##ActionP6);\
1705  };\
1706  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1707      typename p3##_type, typename p4##_type, typename p5##_type>\
1708  inline name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
1709      p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
1710      p3##_type p3, p4##_type p4, p5##_type p5) {\
1711    return name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
1712        p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
1713  }\
1714  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1715      typename p3##_type, typename p4##_type, typename p5##_type>\
1716  template <typename F>\
1717  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1718      typename arg3_type, typename arg4_type, typename arg5_type, \
1719      typename arg6_type, typename arg7_type, typename arg8_type, \
1720      typename arg9_type>\
1721  typename ::testing::internal::Function<F>::Result\
1722      name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1723          p5##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1724          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1725
1726#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\
1727  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1728      typename p3##_type, typename p4##_type, typename p5##_type, \
1729      typename p6##_type>\
1730  class name##ActionP7 {\
1731   public:\
1732    name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \
1733        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1734        p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \
1735        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \
1736        p6(gmock_p6) {}\
1737    template <typename F>\
1738    class gmock_Impl : public ::testing::ActionInterface<F> {\
1739     public:\
1740      typedef F function_type;\
1741      typedef typename ::testing::internal::Function<F>::Result return_type;\
1742      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1743          args_type;\
1744      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1745          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1746          p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1747          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\
1748      virtual return_type Perform(const args_type& args) {\
1749        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1750            Perform(this, args);\
1751      }\
1752      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1753          typename arg3_type, typename arg4_type, typename arg5_type, \
1754          typename arg6_type, typename arg7_type, typename arg8_type, \
1755          typename arg9_type>\
1756      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1757          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1758          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1759          arg9_type arg9) const;\
1760      p0##_type p0;\
1761      p1##_type p1;\
1762      p2##_type p2;\
1763      p3##_type p3;\
1764      p4##_type p4;\
1765      p5##_type p5;\
1766      p6##_type p6;\
1767     private:\
1768      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1769    };\
1770    template <typename F> operator ::testing::Action<F>() const {\
1771      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
1772          p6));\
1773    }\
1774    p0##_type p0;\
1775    p1##_type p1;\
1776    p2##_type p2;\
1777    p3##_type p3;\
1778    p4##_type p4;\
1779    p5##_type p5;\
1780    p6##_type p6;\
1781   private:\
1782    GTEST_DISALLOW_ASSIGN_(name##ActionP7);\
1783  };\
1784  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1785      typename p3##_type, typename p4##_type, typename p5##_type, \
1786      typename p6##_type>\
1787  inline name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
1788      p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
1789      p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
1790      p6##_type p6) {\
1791    return name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
1792        p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
1793  }\
1794  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1795      typename p3##_type, typename p4##_type, typename p5##_type, \
1796      typename p6##_type>\
1797  template <typename F>\
1798  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1799      typename arg3_type, typename arg4_type, typename arg5_type, \
1800      typename arg6_type, typename arg7_type, typename arg8_type, \
1801      typename arg9_type>\
1802  typename ::testing::internal::Function<F>::Result\
1803      name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1804          p5##_type, p6##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1805          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1806
1807#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\
1808  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1809      typename p3##_type, typename p4##_type, typename p5##_type, \
1810      typename p6##_type, typename p7##_type>\
1811  class name##ActionP8 {\
1812   public:\
1813    name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \
1814        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1815        p5##_type gmock_p5, p6##_type gmock_p6, \
1816        p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1817        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
1818        p7(gmock_p7) {}\
1819    template <typename F>\
1820    class gmock_Impl : public ::testing::ActionInterface<F> {\
1821     public:\
1822      typedef F function_type;\
1823      typedef typename ::testing::internal::Function<F>::Result return_type;\
1824      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1825          args_type;\
1826      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1827          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1828          p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), \
1829          p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), \
1830          p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\
1831      virtual return_type Perform(const args_type& args) {\
1832        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1833            Perform(this, args);\
1834      }\
1835      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1836          typename arg3_type, typename arg4_type, typename arg5_type, \
1837          typename arg6_type, typename arg7_type, typename arg8_type, \
1838          typename arg9_type>\
1839      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1840          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1841          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1842          arg9_type arg9) const;\
1843      p0##_type p0;\
1844      p1##_type p1;\
1845      p2##_type p2;\
1846      p3##_type p3;\
1847      p4##_type p4;\
1848      p5##_type p5;\
1849      p6##_type p6;\
1850      p7##_type p7;\
1851     private:\
1852      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1853    };\
1854    template <typename F> operator ::testing::Action<F>() const {\
1855      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
1856          p6, p7));\
1857    }\
1858    p0##_type p0;\
1859    p1##_type p1;\
1860    p2##_type p2;\
1861    p3##_type p3;\
1862    p4##_type p4;\
1863    p5##_type p5;\
1864    p6##_type p6;\
1865    p7##_type p7;\
1866   private:\
1867    GTEST_DISALLOW_ASSIGN_(name##ActionP8);\
1868  };\
1869  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1870      typename p3##_type, typename p4##_type, typename p5##_type, \
1871      typename p6##_type, typename p7##_type>\
1872  inline name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
1873      p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
1874      p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
1875      p6##_type p6, p7##_type p7) {\
1876    return name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
1877        p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
1878        p6, p7);\
1879  }\
1880  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1881      typename p3##_type, typename p4##_type, typename p5##_type, \
1882      typename p6##_type, typename p7##_type>\
1883  template <typename F>\
1884  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1885      typename arg3_type, typename arg4_type, typename arg5_type, \
1886      typename arg6_type, typename arg7_type, typename arg8_type, \
1887      typename arg9_type>\
1888  typename ::testing::internal::Function<F>::Result\
1889      name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1890          p5##_type, p6##_type, \
1891          p7##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1892          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1893
1894#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\
1895  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1896      typename p3##_type, typename p4##_type, typename p5##_type, \
1897      typename p6##_type, typename p7##_type, typename p8##_type>\
1898  class name##ActionP9 {\
1899   public:\
1900    name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \
1901        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1902        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
1903        p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1904        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
1905        p8(gmock_p8) {}\
1906    template <typename F>\
1907    class gmock_Impl : public ::testing::ActionInterface<F> {\
1908     public:\
1909      typedef F function_type;\
1910      typedef typename ::testing::internal::Function<F>::Result return_type;\
1911      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
1912          args_type;\
1913      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1914          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1915          p6##_type gmock_p6, p7##_type gmock_p7, \
1916          p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1917          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
1918          p7(gmock_p7), p8(gmock_p8) {}\
1919      virtual return_type Perform(const args_type& args) {\
1920        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
1921            Perform(this, args);\
1922      }\
1923      template <typename arg0_type, typename arg1_type, typename arg2_type, \
1924          typename arg3_type, typename arg4_type, typename arg5_type, \
1925          typename arg6_type, typename arg7_type, typename arg8_type, \
1926          typename arg9_type>\
1927      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
1928          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
1929          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
1930          arg9_type arg9) const;\
1931      p0##_type p0;\
1932      p1##_type p1;\
1933      p2##_type p2;\
1934      p3##_type p3;\
1935      p4##_type p4;\
1936      p5##_type p5;\
1937      p6##_type p6;\
1938      p7##_type p7;\
1939      p8##_type p8;\
1940     private:\
1941      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1942    };\
1943    template <typename F> operator ::testing::Action<F>() const {\
1944      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
1945          p6, p7, p8));\
1946    }\
1947    p0##_type p0;\
1948    p1##_type p1;\
1949    p2##_type p2;\
1950    p3##_type p3;\
1951    p4##_type p4;\
1952    p5##_type p5;\
1953    p6##_type p6;\
1954    p7##_type p7;\
1955    p8##_type p8;\
1956   private:\
1957    GTEST_DISALLOW_ASSIGN_(name##ActionP9);\
1958  };\
1959  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1960      typename p3##_type, typename p4##_type, typename p5##_type, \
1961      typename p6##_type, typename p7##_type, typename p8##_type>\
1962  inline name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
1963      p4##_type, p5##_type, p6##_type, p7##_type, \
1964      p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
1965      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \
1966      p8##_type p8) {\
1967    return name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
1968        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
1969        p3, p4, p5, p6, p7, p8);\
1970  }\
1971  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1972      typename p3##_type, typename p4##_type, typename p5##_type, \
1973      typename p6##_type, typename p7##_type, typename p8##_type>\
1974  template <typename F>\
1975  template <typename arg0_type, typename arg1_type, typename arg2_type, \
1976      typename arg3_type, typename arg4_type, typename arg5_type, \
1977      typename arg6_type, typename arg7_type, typename arg8_type, \
1978      typename arg9_type>\
1979  typename ::testing::internal::Function<F>::Result\
1980      name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1981          p5##_type, p6##_type, p7##_type, \
1982          p8##_type>::gmock_Impl<F>::gmock_PerformImpl(\
1983          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
1984
1985#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\
1986  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1987      typename p3##_type, typename p4##_type, typename p5##_type, \
1988      typename p6##_type, typename p7##_type, typename p8##_type, \
1989      typename p9##_type>\
1990  class name##ActionP10 {\
1991   public:\
1992    name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \
1993        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1994        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
1995        p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \
1996        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
1997        p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\
1998    template <typename F>\
1999    class gmock_Impl : public ::testing::ActionInterface<F> {\
2000     public:\
2001      typedef F function_type;\
2002      typedef typename ::testing::internal::Function<F>::Result return_type;\
2003      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
2004          args_type;\
2005      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
2006          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
2007          p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
2008          p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
2009          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
2010          p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\
2011      virtual return_type Perform(const args_type& args) {\
2012        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
2013            Perform(this, args);\
2014      }\
2015      template <typename arg0_type, typename arg1_type, typename arg2_type, \
2016          typename arg3_type, typename arg4_type, typename arg5_type, \
2017          typename arg6_type, typename arg7_type, typename arg8_type, \
2018          typename arg9_type>\
2019      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
2020          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
2021          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
2022          arg9_type arg9) const;\
2023      p0##_type p0;\
2024      p1##_type p1;\
2025      p2##_type p2;\
2026      p3##_type p3;\
2027      p4##_type p4;\
2028      p5##_type p5;\
2029      p6##_type p6;\
2030      p7##_type p7;\
2031      p8##_type p8;\
2032      p9##_type p9;\
2033     private:\
2034      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
2035    };\
2036    template <typename F> operator ::testing::Action<F>() const {\
2037      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
2038          p6, p7, p8, p9));\
2039    }\
2040    p0##_type p0;\
2041    p1##_type p1;\
2042    p2##_type p2;\
2043    p3##_type p3;\
2044    p4##_type p4;\
2045    p5##_type p5;\
2046    p6##_type p6;\
2047    p7##_type p7;\
2048    p8##_type p8;\
2049    p9##_type p9;\
2050   private:\
2051    GTEST_DISALLOW_ASSIGN_(name##ActionP10);\
2052  };\
2053  template <typename p0##_type, typename p1##_type, typename p2##_type, \
2054      typename p3##_type, typename p4##_type, typename p5##_type, \
2055      typename p6##_type, typename p7##_type, typename p8##_type, \
2056      typename p9##_type>\
2057  inline name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
2058      p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
2059      p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
2060      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
2061      p9##_type p9) {\
2062    return name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
2063        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
2064        p1, p2, p3, p4, p5, p6, p7, p8, p9);\
2065  }\
2066  template <typename p0##_type, typename p1##_type, typename p2##_type, \
2067      typename p3##_type, typename p4##_type, typename p5##_type, \
2068      typename p6##_type, typename p7##_type, typename p8##_type, \
2069      typename p9##_type>\
2070  template <typename F>\
2071  template <typename arg0_type, typename arg1_type, typename arg2_type, \
2072      typename arg3_type, typename arg4_type, typename arg5_type, \
2073      typename arg6_type, typename arg7_type, typename arg8_type, \
2074      typename arg9_type>\
2075  typename ::testing::internal::Function<F>::Result\
2076      name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
2077          p5##_type, p6##_type, p7##_type, p8##_type, \
2078          p9##_type>::gmock_Impl<F>::gmock_PerformImpl(\
2079          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2080
2081namespace testing {
2082
2083
2084// The ACTION*() macros trigger warning C4100 (unreferenced formal
2085// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
2086// the macro definition, as the warnings are generated when the macro
2087// is expanded and macro expansion cannot contain #pragma.  Therefore
2088// we suppress them here.
2089#ifdef _MSC_VER
2090# pragma warning(push)
2091# pragma warning(disable:4100)
2092#endif
2093
2094// Various overloads for InvokeArgument<N>().
2095//
2096// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
2097// (0-based) argument, which must be a k-ary callable, of the mock
2098// function, with arguments a1, a2, ..., a_k.
2099//
2100// Notes:
2101//
2102//   1. The arguments are passed by value by default.  If you need to
2103//   pass an argument by reference, wrap it inside ByRef().  For
2104//   example,
2105//
2106//     InvokeArgument<1>(5, string("Hello"), ByRef(foo))
2107//
2108//   passes 5 and string("Hello") by value, and passes foo by
2109//   reference.
2110//
2111//   2. If the callable takes an argument by reference but ByRef() is
2112//   not used, it will receive the reference to a copy of the value,
2113//   instead of the original value.  For example, when the 0-th
2114//   argument of the mock function takes a const string&, the action
2115//
2116//     InvokeArgument<0>(string("Hello"))
2117//
2118//   makes a copy of the temporary string("Hello") object and passes a
2119//   reference of the copy, instead of the original temporary object,
2120//   to the callable.  This makes it easy for a user to define an
2121//   InvokeArgument action from temporary values and have it performed
2122//   later.
2123
2124namespace internal {
2125namespace invoke_argument {
2126
2127// Appears in InvokeArgumentAdl's argument list to help avoid
2128// accidental calls to user functions of the same name.
2129struct AdlTag {};
2130
2131// InvokeArgumentAdl - a helper for InvokeArgument.
2132// The basic overloads are provided here for generic functors.
2133// Overloads for other custom-callables are provided in the
2134// internal/custom/callback-actions.h header.
2135
2136template <typename R, typename F>
2137R InvokeArgumentAdl(AdlTag, F f) {
2138  return f();
2139}
2140template <typename R, typename F, typename A1>
2141R InvokeArgumentAdl(AdlTag, F f, A1 a1) {
2142  return f(a1);
2143}
2144template <typename R, typename F, typename A1, typename A2>
2145R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) {
2146  return f(a1, a2);
2147}
2148template <typename R, typename F, typename A1, typename A2, typename A3>
2149R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) {
2150  return f(a1, a2, a3);
2151}
2152template <typename R, typename F, typename A1, typename A2, typename A3,
2153    typename A4>
2154R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) {
2155  return f(a1, a2, a3, a4);
2156}
2157template <typename R, typename F, typename A1, typename A2, typename A3,
2158    typename A4, typename A5>
2159R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) {
2160  return f(a1, a2, a3, a4, a5);
2161}
2162template <typename R, typename F, typename A1, typename A2, typename A3,
2163    typename A4, typename A5, typename A6>
2164R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) {
2165  return f(a1, a2, a3, a4, a5, a6);
2166}
2167template <typename R, typename F, typename A1, typename A2, typename A3,
2168    typename A4, typename A5, typename A6, typename A7>
2169R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
2170    A7 a7) {
2171  return f(a1, a2, a3, a4, a5, a6, a7);
2172}
2173template <typename R, typename F, typename A1, typename A2, typename A3,
2174    typename A4, typename A5, typename A6, typename A7, typename A8>
2175R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
2176    A7 a7, A8 a8) {
2177  return f(a1, a2, a3, a4, a5, a6, a7, a8);
2178}
2179template <typename R, typename F, typename A1, typename A2, typename A3,
2180    typename A4, typename A5, typename A6, typename A7, typename A8,
2181    typename A9>
2182R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
2183    A7 a7, A8 a8, A9 a9) {
2184  return f(a1, a2, a3, a4, a5, a6, a7, a8, a9);
2185}
2186template <typename R, typename F, typename A1, typename A2, typename A3,
2187    typename A4, typename A5, typename A6, typename A7, typename A8,
2188    typename A9, typename A10>
2189R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
2190    A7 a7, A8 a8, A9 a9, A10 a10) {
2191  return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
2192}
2193}  // namespace invoke_argument
2194}  // namespace internal
2195
2196ACTION_TEMPLATE(InvokeArgument,
2197                HAS_1_TEMPLATE_PARAMS(int, k),
2198                AND_0_VALUE_PARAMS()) {
2199  using internal::invoke_argument::InvokeArgumentAdl;
2200  return InvokeArgumentAdl<return_type>(
2201      internal::invoke_argument::AdlTag(),
2202      ::testing::get<k>(args));
2203}
2204
2205ACTION_TEMPLATE(InvokeArgument,
2206                HAS_1_TEMPLATE_PARAMS(int, k),
2207                AND_1_VALUE_PARAMS(p0)) {
2208  using internal::invoke_argument::InvokeArgumentAdl;
2209  return InvokeArgumentAdl<return_type>(
2210      internal::invoke_argument::AdlTag(),
2211      ::testing::get<k>(args), p0);
2212}
2213
2214ACTION_TEMPLATE(InvokeArgument,
2215                HAS_1_TEMPLATE_PARAMS(int, k),
2216                AND_2_VALUE_PARAMS(p0, p1)) {
2217  using internal::invoke_argument::InvokeArgumentAdl;
2218  return InvokeArgumentAdl<return_type>(
2219      internal::invoke_argument::AdlTag(),
2220      ::testing::get<k>(args), p0, p1);
2221}
2222
2223ACTION_TEMPLATE(InvokeArgument,
2224                HAS_1_TEMPLATE_PARAMS(int, k),
2225                AND_3_VALUE_PARAMS(p0, p1, p2)) {
2226  using internal::invoke_argument::InvokeArgumentAdl;
2227  return InvokeArgumentAdl<return_type>(
2228      internal::invoke_argument::AdlTag(),
2229      ::testing::get<k>(args), p0, p1, p2);
2230}
2231
2232ACTION_TEMPLATE(InvokeArgument,
2233                HAS_1_TEMPLATE_PARAMS(int, k),
2234                AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
2235  using internal::invoke_argument::InvokeArgumentAdl;
2236  return InvokeArgumentAdl<return_type>(
2237      internal::invoke_argument::AdlTag(),
2238      ::testing::get<k>(args), p0, p1, p2, p3);
2239}
2240
2241ACTION_TEMPLATE(InvokeArgument,
2242                HAS_1_TEMPLATE_PARAMS(int, k),
2243                AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
2244  using internal::invoke_argument::InvokeArgumentAdl;
2245  return InvokeArgumentAdl<return_type>(
2246      internal::invoke_argument::AdlTag(),
2247      ::testing::get<k>(args), p0, p1, p2, p3, p4);
2248}
2249
2250ACTION_TEMPLATE(InvokeArgument,
2251                HAS_1_TEMPLATE_PARAMS(int, k),
2252                AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
2253  using internal::invoke_argument::InvokeArgumentAdl;
2254  return InvokeArgumentAdl<return_type>(
2255      internal::invoke_argument::AdlTag(),
2256      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5);
2257}
2258
2259ACTION_TEMPLATE(InvokeArgument,
2260                HAS_1_TEMPLATE_PARAMS(int, k),
2261                AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
2262  using internal::invoke_argument::InvokeArgumentAdl;
2263  return InvokeArgumentAdl<return_type>(
2264      internal::invoke_argument::AdlTag(),
2265      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6);
2266}
2267
2268ACTION_TEMPLATE(InvokeArgument,
2269                HAS_1_TEMPLATE_PARAMS(int, k),
2270                AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
2271  using internal::invoke_argument::InvokeArgumentAdl;
2272  return InvokeArgumentAdl<return_type>(
2273      internal::invoke_argument::AdlTag(),
2274      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7);
2275}
2276
2277ACTION_TEMPLATE(InvokeArgument,
2278                HAS_1_TEMPLATE_PARAMS(int, k),
2279                AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
2280  using internal::invoke_argument::InvokeArgumentAdl;
2281  return InvokeArgumentAdl<return_type>(
2282      internal::invoke_argument::AdlTag(),
2283      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8);
2284}
2285
2286ACTION_TEMPLATE(InvokeArgument,
2287                HAS_1_TEMPLATE_PARAMS(int, k),
2288                AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
2289  using internal::invoke_argument::InvokeArgumentAdl;
2290  return InvokeArgumentAdl<return_type>(
2291      internal::invoke_argument::AdlTag(),
2292      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
2293}
2294
2295// Various overloads for ReturnNew<T>().
2296//
2297// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
2298// instance of type T, constructed on the heap with constructor arguments
2299// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
2300ACTION_TEMPLATE(ReturnNew,
2301                HAS_1_TEMPLATE_PARAMS(typename, T),
2302                AND_0_VALUE_PARAMS()) {
2303  return new T();
2304}
2305
2306ACTION_TEMPLATE(ReturnNew,
2307                HAS_1_TEMPLATE_PARAMS(typename, T),
2308                AND_1_VALUE_PARAMS(p0)) {
2309  return new T(p0);
2310}
2311
2312ACTION_TEMPLATE(ReturnNew,
2313                HAS_1_TEMPLATE_PARAMS(typename, T),
2314                AND_2_VALUE_PARAMS(p0, p1)) {
2315  return new T(p0, p1);
2316}
2317
2318ACTION_TEMPLATE(ReturnNew,
2319                HAS_1_TEMPLATE_PARAMS(typename, T),
2320                AND_3_VALUE_PARAMS(p0, p1, p2)) {
2321  return new T(p0, p1, p2);
2322}
2323
2324ACTION_TEMPLATE(ReturnNew,
2325                HAS_1_TEMPLATE_PARAMS(typename, T),
2326                AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
2327  return new T(p0, p1, p2, p3);
2328}
2329
2330ACTION_TEMPLATE(ReturnNew,
2331                HAS_1_TEMPLATE_PARAMS(typename, T),
2332                AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
2333  return new T(p0, p1, p2, p3, p4);
2334}
2335
2336ACTION_TEMPLATE(ReturnNew,
2337                HAS_1_TEMPLATE_PARAMS(typename, T),
2338                AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
2339  return new T(p0, p1, p2, p3, p4, p5);
2340}
2341
2342ACTION_TEMPLATE(ReturnNew,
2343                HAS_1_TEMPLATE_PARAMS(typename, T),
2344                AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
2345  return new T(p0, p1, p2, p3, p4, p5, p6);
2346}
2347
2348ACTION_TEMPLATE(ReturnNew,
2349                HAS_1_TEMPLATE_PARAMS(typename, T),
2350                AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
2351  return new T(p0, p1, p2, p3, p4, p5, p6, p7);
2352}
2353
2354ACTION_TEMPLATE(ReturnNew,
2355                HAS_1_TEMPLATE_PARAMS(typename, T),
2356                AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
2357  return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8);
2358}
2359
2360ACTION_TEMPLATE(ReturnNew,
2361                HAS_1_TEMPLATE_PARAMS(typename, T),
2362                AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
2363  return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
2364}
2365
2366#ifdef _MSC_VER
2367# pragma warning(pop)
2368#endif
2369
2370}  // namespace testing
2371
2372// Include any custom actions added by the local installation.
2373// We must include this header at the end to make sure it can use the
2374// declarations from this file.
2375#include "gmock/internal/custom/gmock-generated-actions.h"
2376
2377#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-actions.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$$ This is a Pump source file.  Please use Pump to convert it to
3$$ gmock-generated-actions.h.
4$$
5$var n = 10  $$ The maximum arity we support.
6$$}} This meta comment fixes auto-indentation in editors.
7// Copyright 2007, Google Inc.
8// All rights reserved.
9//
10// Redistribution and use in source and binary forms, with or without
11// modification, are permitted provided that the following conditions are
12// met:
13//
14//     * Redistributions of source code must retain the above copyright
15// notice, this list of conditions and the following disclaimer.
16//     * Redistributions in binary form must reproduce the above
17// copyright notice, this list of conditions and the following disclaimer
18// in the documentation and/or other materials provided with the
19// distribution.
20//     * Neither the name of Google Inc. nor the names of its
21// contributors may be used to endorse or promote products derived from
22// this software without specific prior written permission.
23//
24// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35//
36// Author: wan@google.com (Zhanyong Wan)
37
38// Google Mock - a framework for writing C++ mock classes.
39//
40// This file implements some commonly used variadic actions.
41
42#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
43#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
44
45#include "gmock/gmock-actions.h"
46#include "gmock/internal/gmock-port.h"
47
48namespace testing {
49namespace internal {
50
51// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
52// function or method with the unpacked values, where F is a function
53// type that takes N arguments.
54template <typename Result, typename ArgumentTuple>
55class InvokeHelper;
56
57
58$range i 0..n
59$for i [[
60$range j 1..i
61$var types = [[$for j [[, typename A$j]]]]
62$var as = [[$for j, [[A$j]]]]
63$var args = [[$if i==0 [[]] $else [[ args]]]]
64$var gets = [[$for j, [[get<$(j - 1)>(args)]]]]
65template <typename R$types>
66class InvokeHelper<R, ::testing::tuple<$as> > {
67 public:
68  template <typename Function>
69  static R Invoke(Function function, const ::testing::tuple<$as>&$args) {
70           return function($gets);
71  }
72
73  template <class Class, typename MethodPtr>
74  static R InvokeMethod(Class* obj_ptr,
75                        MethodPtr method_ptr,
76                        const ::testing::tuple<$as>&$args) {
77           return (obj_ptr->*method_ptr)($gets);
78  }
79};
80
81
82]]
83// An INTERNAL macro for extracting the type of a tuple field.  It's
84// subject to change without notice - DO NOT USE IN USER CODE!
85#define GMOCK_FIELD_(Tuple, N) \
86    typename ::testing::tuple_element<N, Tuple>::type
87
88$range i 1..n
89
90// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::type is the
91// type of an n-ary function whose i-th (1-based) argument type is the
92// k{i}-th (0-based) field of ArgumentTuple, which must be a tuple
93// type, and whose return type is Result.  For example,
94//   SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type
95// is int(bool, long).
96//
97// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args)
98// returns the selected fields (k1, k2, ..., k_n) of args as a tuple.
99// For example,
100//   SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select(
101//       ::testing::make_tuple(true, 'a', 2.5))
102// returns tuple (2.5, true).
103//
104// The numbers in list k1, k2, ..., k_n must be >= 0, where n can be
105// in the range [0, $n].  Duplicates are allowed and they don't have
106// to be in an ascending or descending order.
107
108template <typename Result, typename ArgumentTuple, $for i, [[int k$i]]>
109class SelectArgs {
110 public:
111  typedef Result type($for i, [[GMOCK_FIELD_(ArgumentTuple, k$i)]]);
112  typedef typename Function<type>::ArgumentTuple SelectedArgs;
113  static SelectedArgs Select(const ArgumentTuple& args) {
114    return SelectedArgs($for i, [[get<k$i>(args)]]);
115  }
116};
117
118
119$for i [[
120$range j 1..n
121$range j1 1..i-1
122template <typename Result, typename ArgumentTuple$for j1[[, int k$j1]]>
123class SelectArgs<Result, ArgumentTuple,
124                 $for j, [[$if j <= i-1 [[k$j]] $else [[-1]]]]> {
125 public:
126  typedef Result type($for j1, [[GMOCK_FIELD_(ArgumentTuple, k$j1)]]);
127  typedef typename Function<type>::ArgumentTuple SelectedArgs;
128  static SelectedArgs Select(const ArgumentTuple& [[]]
129$if i == 1 [[/* args */]] $else [[args]]) {
130    return SelectedArgs($for j1, [[get<k$j1>(args)]]);
131  }
132};
133
134
135]]
136#undef GMOCK_FIELD_
137
138$var ks = [[$for i, [[k$i]]]]
139
140// Implements the WithArgs action.
141template <typename InnerAction, $for i, [[int k$i = -1]]>
142class WithArgsAction {
143 public:
144  explicit WithArgsAction(const InnerAction& action) : action_(action) {}
145
146  template <typename F>
147  operator Action<F>() const { return MakeAction(new Impl<F>(action_)); }
148
149 private:
150  template <typename F>
151  class Impl : public ActionInterface<F> {
152   public:
153    typedef typename Function<F>::Result Result;
154    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
155
156    explicit Impl(const InnerAction& action) : action_(action) {}
157
158    virtual Result Perform(const ArgumentTuple& args) {
159      return action_.Perform(SelectArgs<Result, ArgumentTuple, $ks>::Select(args));
160    }
161
162   private:
163    typedef typename SelectArgs<Result, ArgumentTuple,
164        $ks>::type InnerFunctionType;
165
166    Action<InnerFunctionType> action_;
167  };
168
169  const InnerAction action_;
170
171  GTEST_DISALLOW_ASSIGN_(WithArgsAction);
172};
173
174// A macro from the ACTION* family (defined later in this file)
175// defines an action that can be used in a mock function.  Typically,
176// these actions only care about a subset of the arguments of the mock
177// function.  For example, if such an action only uses the second
178// argument, it can be used in any mock function that takes >= 2
179// arguments where the type of the second argument is compatible.
180//
181// Therefore, the action implementation must be prepared to take more
182// arguments than it needs.  The ExcessiveArg type is used to
183// represent those excessive arguments.  In order to keep the compiler
184// error messages tractable, we define it in the testing namespace
185// instead of testing::internal.  However, this is an INTERNAL TYPE
186// and subject to change without notice, so a user MUST NOT USE THIS
187// TYPE DIRECTLY.
188struct ExcessiveArg {};
189
190// A helper class needed for implementing the ACTION* macros.
191template <typename Result, class Impl>
192class ActionHelper {
193 public:
194$range i 0..n
195$for i
196
197[[
198$var template = [[$if i==0 [[]] $else [[
199$range j 0..i-1
200  template <$for j, [[typename A$j]]>
201]]]]
202$range j 0..i-1
203$var As = [[$for j, [[A$j]]]]
204$var as = [[$for j, [[get<$j>(args)]]]]
205$range k 1..n-i
206$var eas = [[$for k, [[ExcessiveArg()]]]]
207$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]]
208$template
209  static Result Perform(Impl* impl, const ::testing::tuple<$As>& args) {
210    return impl->template gmock_PerformImpl<$As>(args, $arg_list);
211  }
212
213]]
214};
215
216}  // namespace internal
217
218// Various overloads for Invoke().
219
220// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
221// the selected arguments of the mock function to an_action and
222// performs it.  It serves as an adaptor between actions with
223// different argument lists.  C++ doesn't support default arguments for
224// function templates, so we have to overload it.
225
226$range i 1..n
227$for i [[
228$range j 1..i
229template <$for j [[int k$j, ]]typename InnerAction>
230inline internal::WithArgsAction<InnerAction$for j [[, k$j]]>
231WithArgs(const InnerAction& action) {
232  return internal::WithArgsAction<InnerAction$for j [[, k$j]]>(action);
233}
234
235
236]]
237// Creates an action that does actions a1, a2, ..., sequentially in
238// each invocation.
239$range i 2..n
240$for i [[
241$range j 2..i
242$var types = [[$for j, [[typename Action$j]]]]
243$var Aas = [[$for j [[, Action$j a$j]]]]
244
245template <typename Action1, $types>
246$range k 1..i-1
247
248inline $for k [[internal::DoBothAction<Action$k, ]]Action$i$for k  [[>]]
249
250DoAll(Action1 a1$Aas) {
251$if i==2 [[
252
253  return internal::DoBothAction<Action1, Action2>(a1, a2);
254]] $else [[
255$range j2 2..i
256
257  return DoAll(a1, DoAll($for j2, [[a$j2]]));
258]]
259
260}
261
262]]
263
264}  // namespace testing
265
266// The ACTION* family of macros can be used in a namespace scope to
267// define custom actions easily.  The syntax:
268//
269//   ACTION(name) { statements; }
270//
271// will define an action with the given name that executes the
272// statements.  The value returned by the statements will be used as
273// the return value of the action.  Inside the statements, you can
274// refer to the K-th (0-based) argument of the mock function by
275// 'argK', and refer to its type by 'argK_type'.  For example:
276//
277//   ACTION(IncrementArg1) {
278//     arg1_type temp = arg1;
279//     return ++(*temp);
280//   }
281//
282// allows you to write
283//
284//   ...WillOnce(IncrementArg1());
285//
286// You can also refer to the entire argument tuple and its type by
287// 'args' and 'args_type', and refer to the mock function type and its
288// return type by 'function_type' and 'return_type'.
289//
290// Note that you don't need to specify the types of the mock function
291// arguments.  However rest assured that your code is still type-safe:
292// you'll get a compiler error if *arg1 doesn't support the ++
293// operator, or if the type of ++(*arg1) isn't compatible with the
294// mock function's return type, for example.
295//
296// Sometimes you'll want to parameterize the action.   For that you can use
297// another macro:
298//
299//   ACTION_P(name, param_name) { statements; }
300//
301// For example:
302//
303//   ACTION_P(Add, n) { return arg0 + n; }
304//
305// will allow you to write:
306//
307//   ...WillOnce(Add(5));
308//
309// Note that you don't need to provide the type of the parameter
310// either.  If you need to reference the type of a parameter named
311// 'foo', you can write 'foo_type'.  For example, in the body of
312// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
313// of 'n'.
314//
315// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P$n to support
316// multi-parameter actions.
317//
318// For the purpose of typing, you can view
319//
320//   ACTION_Pk(Foo, p1, ..., pk) { ... }
321//
322// as shorthand for
323//
324//   template <typename p1_type, ..., typename pk_type>
325//   FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
326//
327// In particular, you can provide the template type arguments
328// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
329// although usually you can rely on the compiler to infer the types
330// for you automatically.  You can assign the result of expression
331// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
332// pk_type>.  This can be useful when composing actions.
333//
334// You can also overload actions with different numbers of parameters:
335//
336//   ACTION_P(Plus, a) { ... }
337//   ACTION_P2(Plus, a, b) { ... }
338//
339// While it's tempting to always use the ACTION* macros when defining
340// a new action, you should also consider implementing ActionInterface
341// or using MakePolymorphicAction() instead, especially if you need to
342// use the action a lot.  While these approaches require more work,
343// they give you more control on the types of the mock function
344// arguments and the action parameters, which in general leads to
345// better compiler error messages that pay off in the long run.  They
346// also allow overloading actions based on parameter types (as opposed
347// to just based on the number of parameters).
348//
349// CAVEAT:
350//
351// ACTION*() can only be used in a namespace scope.  The reason is
352// that C++ doesn't yet allow function-local types to be used to
353// instantiate templates.  The up-coming C++0x standard will fix this.
354// Once that's done, we'll consider supporting using ACTION*() inside
355// a function.
356//
357// MORE INFORMATION:
358//
359// To learn more about using these macros, please search for 'ACTION'
360// on http://code.google.com/p/googlemock/wiki/CookBook.
361
362$range i 0..n
363$range k 0..n-1
364
365// An internal macro needed for implementing ACTION*().
366#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
367    const args_type& args GTEST_ATTRIBUTE_UNUSED_
368$for k [[, \
369    arg$k[[]]_type arg$k GTEST_ATTRIBUTE_UNUSED_]]
370
371
372// Sometimes you want to give an action explicit template parameters
373// that cannot be inferred from its value parameters.  ACTION() and
374// ACTION_P*() don't support that.  ACTION_TEMPLATE() remedies that
375// and can be viewed as an extension to ACTION() and ACTION_P*().
376//
377// The syntax:
378//
379//   ACTION_TEMPLATE(ActionName,
380//                   HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
381//                   AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
382//
383// defines an action template that takes m explicit template
384// parameters and n value parameters.  name_i is the name of the i-th
385// template parameter, and kind_i specifies whether it's a typename,
386// an integral constant, or a template.  p_i is the name of the i-th
387// value parameter.
388//
389// Example:
390//
391//   // DuplicateArg<k, T>(output) converts the k-th argument of the mock
392//   // function to type T and copies it to *output.
393//   ACTION_TEMPLATE(DuplicateArg,
394//                   HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
395//                   AND_1_VALUE_PARAMS(output)) {
396//     *output = T(::testing::get<k>(args));
397//   }
398//   ...
399//     int n;
400//     EXPECT_CALL(mock, Foo(_, _))
401//         .WillOnce(DuplicateArg<1, unsigned char>(&n));
402//
403// To create an instance of an action template, write:
404//
405//   ActionName<t1, ..., t_m>(v1, ..., v_n)
406//
407// where the ts are the template arguments and the vs are the value
408// arguments.  The value argument types are inferred by the compiler.
409// If you want to explicitly specify the value argument types, you can
410// provide additional template arguments:
411//
412//   ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
413//
414// where u_i is the desired type of v_i.
415//
416// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
417// number of value parameters, but not on the number of template
418// parameters.  Without the restriction, the meaning of the following
419// is unclear:
420//
421//   OverloadedAction<int, bool>(x);
422//
423// Are we using a single-template-parameter action where 'bool' refers
424// to the type of x, or are we using a two-template-parameter action
425// where the compiler is asked to infer the type of x?
426//
427// Implementation notes:
428//
429// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
430// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
431// implementing ACTION_TEMPLATE.  The main trick we use is to create
432// new macro invocations when expanding a macro.  For example, we have
433//
434//   #define ACTION_TEMPLATE(name, template_params, value_params)
435//       ... GMOCK_INTERNAL_DECL_##template_params ...
436//
437// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
438// to expand to
439//
440//       ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
441//
442// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
443// preprocessor will continue to expand it to
444//
445//       ... typename T ...
446//
447// This technique conforms to the C++ standard and is portable.  It
448// allows us to implement action templates using O(N) code, where N is
449// the maximum number of template/value parameters supported.  Without
450// using it, we'd have to devote O(N^2) amount of code to implement all
451// combinations of m and n.
452
453// Declares the template parameters.
454
455$range j 1..n
456$for j [[
457$range m 0..j-1
458#define GMOCK_INTERNAL_DECL_HAS_$j[[]]
459_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[kind$m name$m]]
460
461
462]]
463
464// Lists the template parameters.
465
466$for j [[
467$range m 0..j-1
468#define GMOCK_INTERNAL_LIST_HAS_$j[[]]
469_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[name$m]]
470
471
472]]
473
474// Declares the types of value parameters.
475
476$for i [[
477$range j 0..i-1
478#define GMOCK_INTERNAL_DECL_TYPE_AND_$i[[]]
479_VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]]
480
481
482]]
483
484// Initializes the value parameters.
485
486$for i [[
487$range j 0..i-1
488#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\
489    ($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(gmock_p$j)]]
490
491
492]]
493
494// Declares the fields for storing the value parameters.
495
496$for i [[
497$range j 0..i-1
498#define GMOCK_INTERNAL_DEFN_AND_$i[[]]
499_VALUE_PARAMS($for j, [[p$j]]) $for j [[p$j##_type p$j; ]]
500
501
502]]
503
504// Lists the value parameters.
505
506$for i [[
507$range j 0..i-1
508#define GMOCK_INTERNAL_LIST_AND_$i[[]]
509_VALUE_PARAMS($for j, [[p$j]]) $for j, [[p$j]]
510
511
512]]
513
514// Lists the value parameter types.
515
516$for i [[
517$range j 0..i-1
518#define GMOCK_INTERNAL_LIST_TYPE_AND_$i[[]]
519_VALUE_PARAMS($for j, [[p$j]]) $for j [[, p$j##_type]]
520
521
522]]
523
524// Declares the value parameters.
525
526$for i [[
527$range j 0..i-1
528#define GMOCK_INTERNAL_DECL_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
529$for j, [[p$j##_type p$j]]
530
531
532]]
533
534// The suffix of the class template implementing the action template.
535$for i [[
536
537
538$range j 0..i-1
539#define GMOCK_INTERNAL_COUNT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
540$if i==1 [[P]] $elif i>=2 [[P$i]]
541]]
542
543
544// The name of the class template implementing the action template.
545#define GMOCK_ACTION_CLASS_(name, value_params)\
546    GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
547
548$range k 0..n-1
549
550#define ACTION_TEMPLATE(name, template_params, value_params)\
551  template <GMOCK_INTERNAL_DECL_##template_params\
552            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
553  class GMOCK_ACTION_CLASS_(name, value_params) {\
554   public:\
555    explicit GMOCK_ACTION_CLASS_(name, value_params)\
556        GMOCK_INTERNAL_INIT_##value_params {}\
557    template <typename F>\
558    class gmock_Impl : public ::testing::ActionInterface<F> {\
559     public:\
560      typedef F function_type;\
561      typedef typename ::testing::internal::Function<F>::Result return_type;\
562      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
563          args_type;\
564      explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\
565      virtual return_type Perform(const args_type& args) {\
566        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
567            Perform(this, args);\
568      }\
569      template <$for k, [[typename arg$k[[]]_type]]>\
570      return_type gmock_PerformImpl(const args_type& args[[]]
571$for k [[, arg$k[[]]_type arg$k]]) const;\
572      GMOCK_INTERNAL_DEFN_##value_params\
573     private:\
574      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
575    };\
576    template <typename F> operator ::testing::Action<F>() const {\
577      return ::testing::Action<F>(\
578          new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
579    }\
580    GMOCK_INTERNAL_DEFN_##value_params\
581   private:\
582    GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
583  };\
584  template <GMOCK_INTERNAL_DECL_##template_params\
585            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
586  inline GMOCK_ACTION_CLASS_(name, value_params)<\
587      GMOCK_INTERNAL_LIST_##template_params\
588      GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\
589          GMOCK_INTERNAL_DECL_##value_params) {\
590    return GMOCK_ACTION_CLASS_(name, value_params)<\
591        GMOCK_INTERNAL_LIST_##template_params\
592        GMOCK_INTERNAL_LIST_TYPE_##value_params>(\
593            GMOCK_INTERNAL_LIST_##value_params);\
594  }\
595  template <GMOCK_INTERNAL_DECL_##template_params\
596            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
597  template <typename F>\
598  template <typename arg0_type, typename arg1_type, typename arg2_type, \
599      typename arg3_type, typename arg4_type, typename arg5_type, \
600      typename arg6_type, typename arg7_type, typename arg8_type, \
601      typename arg9_type>\
602  typename ::testing::internal::Function<F>::Result\
603      GMOCK_ACTION_CLASS_(name, value_params)<\
604          GMOCK_INTERNAL_LIST_##template_params\
605          GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\
606              gmock_PerformImpl(\
607          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
608
609$for i
610
611[[
612$var template = [[$if i==0 [[]] $else [[
613$range j 0..i-1
614
615  template <$for j, [[typename p$j##_type]]>\
616]]]]
617$var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]]
618                                                $else [[P$i]]]]]]
619$range j 0..i-1
620$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
621$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
622$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
623$var param_field_decls = [[$for j
624[[
625
626      p$j##_type p$j;\
627]]]]
628$var param_field_decls2 = [[$for j
629[[
630
631    p$j##_type p$j;\
632]]]]
633$var params = [[$for j, [[p$j]]]]
634$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
635$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]]
636$var arg_types_and_names = [[$for k, [[arg$k[[]]_type arg$k]]]]
637$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]]
638                                        $else [[ACTION_P$i]]]]
639
640#define $macro_name(name$for j [[, p$j]])\$template
641  class $class_name {\
642   public:\
643    [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\
644    template <typename F>\
645    class gmock_Impl : public ::testing::ActionInterface<F> {\
646     public:\
647      typedef F function_type;\
648      typedef typename ::testing::internal::Function<F>::Result return_type;\
649      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
650          args_type;\
651      [[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\
652      virtual return_type Perform(const args_type& args) {\
653        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
654            Perform(this, args);\
655      }\
656      template <$typename_arg_types>\
657      return_type gmock_PerformImpl(const args_type& args, [[]]
658$arg_types_and_names) const;\$param_field_decls
659     private:\
660      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
661    };\
662    template <typename F> operator ::testing::Action<F>() const {\
663      return ::testing::Action<F>(new gmock_Impl<F>($params));\
664    }\$param_field_decls2
665   private:\
666    GTEST_DISALLOW_ASSIGN_($class_name);\
667  };\$template
668  inline $class_name$param_types name($param_types_and_names) {\
669    return $class_name$param_types($params);\
670  }\$template
671  template <typename F>\
672  template <$typename_arg_types>\
673  typename ::testing::internal::Function<F>::Result\
674      $class_name$param_types::gmock_Impl<F>::gmock_PerformImpl(\
675          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
676]]
677$$ }  // This meta comment fixes auto-indentation in Emacs.  It won't
678$$    // show up in the generated code.
679
680
681namespace testing {
682
683
684// The ACTION*() macros trigger warning C4100 (unreferenced formal
685// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
686// the macro definition, as the warnings are generated when the macro
687// is expanded and macro expansion cannot contain #pragma.  Therefore
688// we suppress them here.
689#ifdef _MSC_VER
690# pragma warning(push)
691# pragma warning(disable:4100)
692#endif
693
694// Various overloads for InvokeArgument<N>().
695//
696// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
697// (0-based) argument, which must be a k-ary callable, of the mock
698// function, with arguments a1, a2, ..., a_k.
699//
700// Notes:
701//
702//   1. The arguments are passed by value by default.  If you need to
703//   pass an argument by reference, wrap it inside ByRef().  For
704//   example,
705//
706//     InvokeArgument<1>(5, string("Hello"), ByRef(foo))
707//
708//   passes 5 and string("Hello") by value, and passes foo by
709//   reference.
710//
711//   2. If the callable takes an argument by reference but ByRef() is
712//   not used, it will receive the reference to a copy of the value,
713//   instead of the original value.  For example, when the 0-th
714//   argument of the mock function takes a const string&, the action
715//
716//     InvokeArgument<0>(string("Hello"))
717//
718//   makes a copy of the temporary string("Hello") object and passes a
719//   reference of the copy, instead of the original temporary object,
720//   to the callable.  This makes it easy for a user to define an
721//   InvokeArgument action from temporary values and have it performed
722//   later.
723
724namespace internal {
725namespace invoke_argument {
726
727// Appears in InvokeArgumentAdl's argument list to help avoid
728// accidental calls to user functions of the same name.
729struct AdlTag {};
730
731// InvokeArgumentAdl - a helper for InvokeArgument.
732// The basic overloads are provided here for generic functors.
733// Overloads for other custom-callables are provided in the
734// internal/custom/callback-actions.h header.
735
736$range i 0..n
737$for i
738[[
739$range j 1..i
740
741template <typename R, typename F[[$for j [[, typename A$j]]]]>
742R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) {
743  return f([[$for j, [[a$j]]]]);
744}
745]]
746
747}  // namespace invoke_argument
748}  // namespace internal
749
750$range i 0..n
751$for i [[
752$range j 0..i-1
753
754ACTION_TEMPLATE(InvokeArgument,
755                HAS_1_TEMPLATE_PARAMS(int, k),
756                AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) {
757  using internal::invoke_argument::InvokeArgumentAdl;
758  return InvokeArgumentAdl<return_type>(
759      internal::invoke_argument::AdlTag(),
760      ::testing::get<k>(args)$for j [[, p$j]]);
761}
762
763]]
764
765// Various overloads for ReturnNew<T>().
766//
767// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
768// instance of type T, constructed on the heap with constructor arguments
769// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
770$range i 0..n
771$for i [[
772$range j 0..i-1
773$var ps = [[$for j, [[p$j]]]]
774
775ACTION_TEMPLATE(ReturnNew,
776                HAS_1_TEMPLATE_PARAMS(typename, T),
777                AND_$i[[]]_VALUE_PARAMS($ps)) {
778  return new T($ps);
779}
780
781]]
782
783#ifdef _MSC_VER
784# pragma warning(pop)
785#endif
786
787}  // namespace testing
788
789// Include any custom callback actions added by the local installation.
790// We must include this header at the end to make sure it can use the
791// declarations from this file.
792#include "gmock/internal/custom/gmock-generated-actions.h"
793
794#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gmock-generated-function-mockers.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2007, Google Inc.
6// All rights reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33//
34// Author: wan@google.com (Zhanyong Wan)
35
36// Google Mock - a framework for writing C++ mock classes.
37//
38// This file implements function mockers of various arities.
39
40#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
41#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
42
43#include "gmock/gmock-spec-builders.h"
44#include "gmock/internal/gmock-internal-utils.h"
45
46#if GTEST_HAS_STD_FUNCTION_
47# include <functional>
48#endif
49
50namespace testing {
51namespace internal {
52
53template <typename F>
54class FunctionMockerBase;
55
56// Note: class FunctionMocker really belongs to the ::testing
57// namespace.  However if we define it in ::testing, MSVC will
58// complain when classes in ::testing::internal declare it as a
59// friend class template.  To workaround this compiler bug, we define
60// FunctionMocker in ::testing::internal and import it into ::testing.
61template <typename F>
62class FunctionMocker;
63
64template <typename R>
65class FunctionMocker<R()> : public
66    internal::FunctionMockerBase<R()> {
67 public:
68  typedef R F();
69  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
70
71  MockSpec<F>& With() {
72    return this->current_spec();
73  }
74
75  R Invoke() {
76    // Even though gcc and MSVC don't enforce it, 'this->' is required
77    // by the C++ standard [14.6.4] here, as the base class type is
78    // dependent on the template argument (and thus shouldn't be
79    // looked into when resolving InvokeWith).
80    return this->InvokeWith(ArgumentTuple());
81  }
82};
83
84template <typename R, typename A1>
85class FunctionMocker<R(A1)> : public
86    internal::FunctionMockerBase<R(A1)> {
87 public:
88  typedef R F(A1);
89  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
90
91  MockSpec<F>& With(const Matcher<A1>& m1) {
92    this->current_spec().SetMatchers(::testing::make_tuple(m1));
93    return this->current_spec();
94  }
95
96  R Invoke(A1 a1) {
97    // Even though gcc and MSVC don't enforce it, 'this->' is required
98    // by the C++ standard [14.6.4] here, as the base class type is
99    // dependent on the template argument (and thus shouldn't be
100    // looked into when resolving InvokeWith).
101    return this->InvokeWith(ArgumentTuple(a1));
102  }
103};
104
105template <typename R, typename A1, typename A2>
106class FunctionMocker<R(A1, A2)> : public
107    internal::FunctionMockerBase<R(A1, A2)> {
108 public:
109  typedef R F(A1, A2);
110  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
111
112  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2) {
113    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2));
114    return this->current_spec();
115  }
116
117  R Invoke(A1 a1, A2 a2) {
118    // Even though gcc and MSVC don't enforce it, 'this->' is required
119    // by the C++ standard [14.6.4] here, as the base class type is
120    // dependent on the template argument (and thus shouldn't be
121    // looked into when resolving InvokeWith).
122    return this->InvokeWith(ArgumentTuple(a1, a2));
123  }
124};
125
126template <typename R, typename A1, typename A2, typename A3>
127class FunctionMocker<R(A1, A2, A3)> : public
128    internal::FunctionMockerBase<R(A1, A2, A3)> {
129 public:
130  typedef R F(A1, A2, A3);
131  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
132
133  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
134      const Matcher<A3>& m3) {
135    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3));
136    return this->current_spec();
137  }
138
139  R Invoke(A1 a1, A2 a2, A3 a3) {
140    // Even though gcc and MSVC don't enforce it, 'this->' is required
141    // by the C++ standard [14.6.4] here, as the base class type is
142    // dependent on the template argument (and thus shouldn't be
143    // looked into when resolving InvokeWith).
144    return this->InvokeWith(ArgumentTuple(a1, a2, a3));
145  }
146};
147
148template <typename R, typename A1, typename A2, typename A3, typename A4>
149class FunctionMocker<R(A1, A2, A3, A4)> : public
150    internal::FunctionMockerBase<R(A1, A2, A3, A4)> {
151 public:
152  typedef R F(A1, A2, A3, A4);
153  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
154
155  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
156      const Matcher<A3>& m3, const Matcher<A4>& m4) {
157    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4));
158    return this->current_spec();
159  }
160
161  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4) {
162    // Even though gcc and MSVC don't enforce it, 'this->' is required
163    // by the C++ standard [14.6.4] here, as the base class type is
164    // dependent on the template argument (and thus shouldn't be
165    // looked into when resolving InvokeWith).
166    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4));
167  }
168};
169
170template <typename R, typename A1, typename A2, typename A3, typename A4,
171    typename A5>
172class FunctionMocker<R(A1, A2, A3, A4, A5)> : public
173    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5)> {
174 public:
175  typedef R F(A1, A2, A3, A4, A5);
176  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
177
178  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
179      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5) {
180    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5));
181    return this->current_spec();
182  }
183
184  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) {
185    // Even though gcc and MSVC don't enforce it, 'this->' is required
186    // by the C++ standard [14.6.4] here, as the base class type is
187    // dependent on the template argument (and thus shouldn't be
188    // looked into when resolving InvokeWith).
189    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5));
190  }
191};
192
193template <typename R, typename A1, typename A2, typename A3, typename A4,
194    typename A5, typename A6>
195class FunctionMocker<R(A1, A2, A3, A4, A5, A6)> : public
196    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6)> {
197 public:
198  typedef R F(A1, A2, A3, A4, A5, A6);
199  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
200
201  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
202      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
203      const Matcher<A6>& m6) {
204    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
205        m6));
206    return this->current_spec();
207  }
208
209  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) {
210    // Even though gcc and MSVC don't enforce it, 'this->' is required
211    // by the C++ standard [14.6.4] here, as the base class type is
212    // dependent on the template argument (and thus shouldn't be
213    // looked into when resolving InvokeWith).
214    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6));
215  }
216};
217
218template <typename R, typename A1, typename A2, typename A3, typename A4,
219    typename A5, typename A6, typename A7>
220class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7)> : public
221    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7)> {
222 public:
223  typedef R F(A1, A2, A3, A4, A5, A6, A7);
224  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
225
226  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
227      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
228      const Matcher<A6>& m6, const Matcher<A7>& m7) {
229    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
230        m6, m7));
231    return this->current_spec();
232  }
233
234  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) {
235    // Even though gcc and MSVC don't enforce it, 'this->' is required
236    // by the C++ standard [14.6.4] here, as the base class type is
237    // dependent on the template argument (and thus shouldn't be
238    // looked into when resolving InvokeWith).
239    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7));
240  }
241};
242
243template <typename R, typename A1, typename A2, typename A3, typename A4,
244    typename A5, typename A6, typename A7, typename A8>
245class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8)> : public
246    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8)> {
247 public:
248  typedef R F(A1, A2, A3, A4, A5, A6, A7, A8);
249  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
250
251  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
252      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
253      const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8) {
254    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
255        m6, m7, m8));
256    return this->current_spec();
257  }
258
259  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) {
260    // Even though gcc and MSVC don't enforce it, 'this->' is required
261    // by the C++ standard [14.6.4] here, as the base class type is
262    // dependent on the template argument (and thus shouldn't be
263    // looked into when resolving InvokeWith).
264    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8));
265  }
266};
267
268template <typename R, typename A1, typename A2, typename A3, typename A4,
269    typename A5, typename A6, typename A7, typename A8, typename A9>
270class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : public
271    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
272 public:
273  typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9);
274  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
275
276  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
277      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
278      const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8,
279      const Matcher<A9>& m9) {
280    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
281        m6, m7, m8, m9));
282    return this->current_spec();
283  }
284
285  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) {
286    // Even though gcc and MSVC don't enforce it, 'this->' is required
287    // by the C++ standard [14.6.4] here, as the base class type is
288    // dependent on the template argument (and thus shouldn't be
289    // looked into when resolving InvokeWith).
290    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9));
291  }
292};
293
294template <typename R, typename A1, typename A2, typename A3, typename A4,
295    typename A5, typename A6, typename A7, typename A8, typename A9,
296    typename A10>
297class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : public
298    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> {
299 public:
300  typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
301  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
302
303  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
304      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
305      const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8,
306      const Matcher<A9>& m9, const Matcher<A10>& m10) {
307    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
308        m6, m7, m8, m9, m10));
309    return this->current_spec();
310  }
311
312  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9,
313      A10 a10) {
314    // Even though gcc and MSVC don't enforce it, 'this->' is required
315    // by the C++ standard [14.6.4] here, as the base class type is
316    // dependent on the template argument (and thus shouldn't be
317    // looked into when resolving InvokeWith).
318    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9,
319        a10));
320  }
321};
322
323}  // namespace internal
324
325// The style guide prohibits "using" statements in a namespace scope
326// inside a header file.  However, the FunctionMocker class template
327// is meant to be defined in the ::testing namespace.  The following
328// line is just a trick for working around a bug in MSVC 8.0, which
329// cannot handle it if we define FunctionMocker in ::testing.
330using internal::FunctionMocker;
331
332// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
333// We define this as a variadic macro in case F contains unprotected
334// commas (the same reason that we use variadic macros in other places
335// in this file).
336// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
337#define GMOCK_RESULT_(tn, ...) \
338    tn ::testing::internal::Function<__VA_ARGS__>::Result
339
340// The type of argument N of the given function type.
341// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
342#define GMOCK_ARG_(tn, N, ...) \
343    tn ::testing::internal::Function<__VA_ARGS__>::Argument##N
344
345// The matcher type for argument N of the given function type.
346// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
347#define GMOCK_MATCHER_(tn, N, ...) \
348    const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
349
350// The variable for mocking the given method.
351// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
352#define GMOCK_MOCKER_(arity, constness, Method) \
353    GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
354
355// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
356#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \
357  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
358      ) constness { \
359    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
360        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
361            == 0), \
362        this_method_does_not_take_0_arguments); \
363    GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \
364    return GMOCK_MOCKER_(0, constness, Method).Invoke(); \
365  } \
366  ::testing::MockSpec<__VA_ARGS__>& \
367      gmock_##Method() constness { \
368    GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \
369    return GMOCK_MOCKER_(0, constness, Method).With(); \
370  } \
371  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \
372      Method)
373
374// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
375#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \
376  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
377      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
378    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
379        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
380            == 1), \
381        this_method_does_not_take_1_argument); \
382    GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \
383    return GMOCK_MOCKER_(1, constness, Method).Invoke(gmock_a1); \
384  } \
385  ::testing::MockSpec<__VA_ARGS__>& \
386      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
387    GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \
388    return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \
389  } \
390  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \
391      Method)
392
393// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
394#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \
395  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
396      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
397      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
398    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
399        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
400            == 2), \
401        this_method_does_not_take_2_arguments); \
402    GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \
403    return GMOCK_MOCKER_(2, constness, Method).Invoke(gmock_a1, gmock_a2); \
404  } \
405  ::testing::MockSpec<__VA_ARGS__>& \
406      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
407                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
408    GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \
409    return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \
410  } \
411  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \
412      Method)
413
414// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
415#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \
416  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
417      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
418      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
419      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
420    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
421        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
422            == 3), \
423        this_method_does_not_take_3_arguments); \
424    GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \
425    return GMOCK_MOCKER_(3, constness, Method).Invoke(gmock_a1, gmock_a2, \
426        gmock_a3); \
427  } \
428  ::testing::MockSpec<__VA_ARGS__>& \
429      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
430                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
431                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
432    GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \
433    return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \
434        gmock_a3); \
435  } \
436  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \
437      Method)
438
439// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
440#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \
441  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
442      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
443      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
444      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
445      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
446    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
447        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
448            == 4), \
449        this_method_does_not_take_4_arguments); \
450    GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \
451    return GMOCK_MOCKER_(4, constness, Method).Invoke(gmock_a1, gmock_a2, \
452        gmock_a3, gmock_a4); \
453  } \
454  ::testing::MockSpec<__VA_ARGS__>& \
455      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
456                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
457                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
458                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
459    GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \
460    return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \
461        gmock_a3, gmock_a4); \
462  } \
463  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \
464      Method)
465
466// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
467#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \
468  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
469      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
470      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
471      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
472      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
473      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
474    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
475        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
476            == 5), \
477        this_method_does_not_take_5_arguments); \
478    GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \
479    return GMOCK_MOCKER_(5, constness, Method).Invoke(gmock_a1, gmock_a2, \
480        gmock_a3, gmock_a4, gmock_a5); \
481  } \
482  ::testing::MockSpec<__VA_ARGS__>& \
483      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
484                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
485                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
486                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
487                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
488    GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \
489    return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \
490        gmock_a3, gmock_a4, gmock_a5); \
491  } \
492  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \
493      Method)
494
495// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
496#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \
497  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
498      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
499      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
500      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
501      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
502      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
503      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
504    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
505        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
506            == 6), \
507        this_method_does_not_take_6_arguments); \
508    GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \
509    return GMOCK_MOCKER_(6, constness, Method).Invoke(gmock_a1, gmock_a2, \
510        gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
511  } \
512  ::testing::MockSpec<__VA_ARGS__>& \
513      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
514                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
515                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
516                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
517                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
518                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
519    GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \
520    return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \
521        gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
522  } \
523  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \
524      Method)
525
526// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
527#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \
528  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
529      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
530      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
531      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
532      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
533      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
534      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
535      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
536    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
537        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
538            == 7), \
539        this_method_does_not_take_7_arguments); \
540    GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \
541    return GMOCK_MOCKER_(7, constness, Method).Invoke(gmock_a1, gmock_a2, \
542        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
543  } \
544  ::testing::MockSpec<__VA_ARGS__>& \
545      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
546                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
547                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
548                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
549                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
550                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
551                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
552    GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \
553    return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \
554        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
555  } \
556  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \
557      Method)
558
559// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
560#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \
561  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
562      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
563      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
564      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
565      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
566      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
567      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
568      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
569      GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
570    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
571        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
572            == 8), \
573        this_method_does_not_take_8_arguments); \
574    GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \
575    return GMOCK_MOCKER_(8, constness, Method).Invoke(gmock_a1, gmock_a2, \
576        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
577  } \
578  ::testing::MockSpec<__VA_ARGS__>& \
579      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
580                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
581                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
582                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
583                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
584                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
585                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
586                     GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
587    GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \
588    return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \
589        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
590  } \
591  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \
592      Method)
593
594// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
595#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \
596  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
597      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
598      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
599      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
600      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
601      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
602      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
603      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
604      GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \
605      GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
606    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
607        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
608            == 9), \
609        this_method_does_not_take_9_arguments); \
610    GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \
611    return GMOCK_MOCKER_(9, constness, Method).Invoke(gmock_a1, gmock_a2, \
612        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
613        gmock_a9); \
614  } \
615  ::testing::MockSpec<__VA_ARGS__>& \
616      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
617                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
618                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
619                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
620                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
621                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
622                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
623                     GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
624                     GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
625    GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \
626    return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \
627        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
628        gmock_a9); \
629  } \
630  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \
631      Method)
632
633// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
634#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \
635  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
636      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
637      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
638      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
639      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
640      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
641      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
642      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
643      GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \
644      GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \
645      GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \
646    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
647        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
648            == 10), \
649        this_method_does_not_take_10_arguments); \
650    GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \
651    return GMOCK_MOCKER_(10, constness, Method).Invoke(gmock_a1, gmock_a2, \
652        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
653        gmock_a10); \
654  } \
655  ::testing::MockSpec<__VA_ARGS__>& \
656      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
657                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
658                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
659                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
660                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
661                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
662                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
663                     GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
664                     GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \
665                     GMOCK_MATCHER_(tn, 10, \
666                         __VA_ARGS__) gmock_a10) constness { \
667    GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \
668    return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \
669        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
670        gmock_a10); \
671  } \
672  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \
673      Method)
674
675#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__)
676#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__)
677#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__)
678#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__)
679#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__)
680#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__)
681#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__)
682#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__)
683#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__)
684#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__)
685#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__)
686
687#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__)
688#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__)
689#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__)
690#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__)
691#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__)
692#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__)
693#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__)
694#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__)
695#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__)
696#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__)
697#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__)
698
699#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__)
700#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__)
701#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__)
702#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__)
703#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__)
704#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__)
705#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__)
706#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__)
707#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__)
708#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__)
709#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__)
710
711#define MOCK_CONST_METHOD0_T(m, ...) \
712    GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__)
713#define MOCK_CONST_METHOD1_T(m, ...) \
714    GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__)
715#define MOCK_CONST_METHOD2_T(m, ...) \
716    GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__)
717#define MOCK_CONST_METHOD3_T(m, ...) \
718    GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__)
719#define MOCK_CONST_METHOD4_T(m, ...) \
720    GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__)
721#define MOCK_CONST_METHOD5_T(m, ...) \
722    GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__)
723#define MOCK_CONST_METHOD6_T(m, ...) \
724    GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__)
725#define MOCK_CONST_METHOD7_T(m, ...) \
726    GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__)
727#define MOCK_CONST_METHOD8_T(m, ...) \
728    GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__)
729#define MOCK_CONST_METHOD9_T(m, ...) \
730    GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__)
731#define MOCK_CONST_METHOD10_T(m, ...) \
732    GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__)
733
734#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
735    GMOCK_METHOD0_(, , ct, m, __VA_ARGS__)
736#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
737    GMOCK_METHOD1_(, , ct, m, __VA_ARGS__)
738#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
739    GMOCK_METHOD2_(, , ct, m, __VA_ARGS__)
740#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
741    GMOCK_METHOD3_(, , ct, m, __VA_ARGS__)
742#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
743    GMOCK_METHOD4_(, , ct, m, __VA_ARGS__)
744#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
745    GMOCK_METHOD5_(, , ct, m, __VA_ARGS__)
746#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
747    GMOCK_METHOD6_(, , ct, m, __VA_ARGS__)
748#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
749    GMOCK_METHOD7_(, , ct, m, __VA_ARGS__)
750#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
751    GMOCK_METHOD8_(, , ct, m, __VA_ARGS__)
752#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
753    GMOCK_METHOD9_(, , ct, m, __VA_ARGS__)
754#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
755    GMOCK_METHOD10_(, , ct, m, __VA_ARGS__)
756
757#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
758    GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__)
759#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
760    GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__)
761#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
762    GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__)
763#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
764    GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__)
765#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
766    GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__)
767#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
768    GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__)
769#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
770    GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__)
771#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
772    GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__)
773#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
774    GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__)
775#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
776    GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__)
777#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
778    GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__)
779
780#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
781    GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__)
782#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
783    GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__)
784#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
785    GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__)
786#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
787    GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__)
788#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
789    GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__)
790#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
791    GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__)
792#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
793    GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__)
794#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
795    GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__)
796#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
797    GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__)
798#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
799    GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__)
800#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
801    GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__)
802
803#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
804    GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__)
805#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
806    GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__)
807#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
808    GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__)
809#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
810    GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__)
811#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
812    GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__)
813#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
814    GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__)
815#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
816    GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__)
817#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
818    GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__)
819#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
820    GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__)
821#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
822    GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__)
823#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
824    GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__)
825
826// A MockFunction<F> class has one mock method whose type is F.  It is
827// useful when you just want your test code to emit some messages and
828// have Google Mock verify the right messages are sent (and perhaps at
829// the right times).  For example, if you are exercising code:
830//
831//   Foo(1);
832//   Foo(2);
833//   Foo(3);
834//
835// and want to verify that Foo(1) and Foo(3) both invoke
836// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
837//
838// TEST(FooTest, InvokesBarCorrectly) {
839//   MyMock mock;
840//   MockFunction<void(string check_point_name)> check;
841//   {
842//     InSequence s;
843//
844//     EXPECT_CALL(mock, Bar("a"));
845//     EXPECT_CALL(check, Call("1"));
846//     EXPECT_CALL(check, Call("2"));
847//     EXPECT_CALL(mock, Bar("a"));
848//   }
849//   Foo(1);
850//   check.Call("1");
851//   Foo(2);
852//   check.Call("2");
853//   Foo(3);
854// }
855//
856// The expectation spec says that the first Bar("a") must happen
857// before check point "1", the second Bar("a") must happen after check
858// point "2", and nothing should happen between the two check
859// points. The explicit check points make it easy to tell which
860// Bar("a") is called by which call to Foo().
861//
862// MockFunction<F> can also be used to exercise code that accepts
863// std::function<F> callbacks. To do so, use AsStdFunction() method
864// to create std::function proxy forwarding to original object's Call.
865// Example:
866//
867// TEST(FooTest, RunsCallbackWithBarArgument) {
868//   MockFunction<int(string)> callback;
869//   EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
870//   Foo(callback.AsStdFunction());
871// }
872template <typename F>
873class MockFunction;
874
875template <typename R>
876class MockFunction<R()> {
877 public:
878  MockFunction() {}
879
880  MOCK_METHOD0_T(Call, R());
881
882#if GTEST_HAS_STD_FUNCTION_
883  std::function<R()> AsStdFunction() {
884    return [this]() -> R {
885      return this->Call();
886    };
887  }
888#endif  // GTEST_HAS_STD_FUNCTION_
889
890 private:
891  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
892};
893
894template <typename R, typename A0>
895class MockFunction<R(A0)> {
896 public:
897  MockFunction() {}
898
899  MOCK_METHOD1_T(Call, R(A0));
900
901#if GTEST_HAS_STD_FUNCTION_
902  std::function<R(A0)> AsStdFunction() {
903    return [this](A0 a0) -> R {
904      return this->Call(a0);
905    };
906  }
907#endif  // GTEST_HAS_STD_FUNCTION_
908
909 private:
910  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
911};
912
913template <typename R, typename A0, typename A1>
914class MockFunction<R(A0, A1)> {
915 public:
916  MockFunction() {}
917
918  MOCK_METHOD2_T(Call, R(A0, A1));
919
920#if GTEST_HAS_STD_FUNCTION_
921  std::function<R(A0, A1)> AsStdFunction() {
922    return [this](A0 a0, A1 a1) -> R {
923      return this->Call(a0, a1);
924    };
925  }
926#endif  // GTEST_HAS_STD_FUNCTION_
927
928 private:
929  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
930};
931
932template <typename R, typename A0, typename A1, typename A2>
933class MockFunction<R(A0, A1, A2)> {
934 public:
935  MockFunction() {}
936
937  MOCK_METHOD3_T(Call, R(A0, A1, A2));
938
939#if GTEST_HAS_STD_FUNCTION_
940  std::function<R(A0, A1, A2)> AsStdFunction() {
941    return [this](A0 a0, A1 a1, A2 a2) -> R {
942      return this->Call(a0, a1, a2);
943    };
944  }
945#endif  // GTEST_HAS_STD_FUNCTION_
946
947 private:
948  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
949};
950
951template <typename R, typename A0, typename A1, typename A2, typename A3>
952class MockFunction<R(A0, A1, A2, A3)> {
953 public:
954  MockFunction() {}
955
956  MOCK_METHOD4_T(Call, R(A0, A1, A2, A3));
957
958#if GTEST_HAS_STD_FUNCTION_
959  std::function<R(A0, A1, A2, A3)> AsStdFunction() {
960    return [this](A0 a0, A1 a1, A2 a2, A3 a3) -> R {
961      return this->Call(a0, a1, a2, a3);
962    };
963  }
964#endif  // GTEST_HAS_STD_FUNCTION_
965
966 private:
967  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
968};
969
970template <typename R, typename A0, typename A1, typename A2, typename A3,
971    typename A4>
972class MockFunction<R(A0, A1, A2, A3, A4)> {
973 public:
974  MockFunction() {}
975
976  MOCK_METHOD5_T(Call, R(A0, A1, A2, A3, A4));
977
978#if GTEST_HAS_STD_FUNCTION_
979  std::function<R(A0, A1, A2, A3, A4)> AsStdFunction() {
980    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) -> R {
981      return this->Call(a0, a1, a2, a3, a4);
982    };
983  }
984#endif  // GTEST_HAS_STD_FUNCTION_
985
986 private:
987  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
988};
989
990template <typename R, typename A0, typename A1, typename A2, typename A3,
991    typename A4, typename A5>
992class MockFunction<R(A0, A1, A2, A3, A4, A5)> {
993 public:
994  MockFunction() {}
995
996  MOCK_METHOD6_T(Call, R(A0, A1, A2, A3, A4, A5));
997
998#if GTEST_HAS_STD_FUNCTION_
999  std::function<R(A0, A1, A2, A3, A4, A5)> AsStdFunction() {
1000    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) -> R {
1001      return this->Call(a0, a1, a2, a3, a4, a5);
1002    };
1003  }
1004#endif  // GTEST_HAS_STD_FUNCTION_
1005
1006 private:
1007  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
1008};
1009
1010template <typename R, typename A0, typename A1, typename A2, typename A3,
1011    typename A4, typename A5, typename A6>
1012class MockFunction<R(A0, A1, A2, A3, A4, A5, A6)> {
1013 public:
1014  MockFunction() {}
1015
1016  MOCK_METHOD7_T(Call, R(A0, A1, A2, A3, A4, A5, A6));
1017
1018#if GTEST_HAS_STD_FUNCTION_
1019  std::function<R(A0, A1, A2, A3, A4, A5, A6)> AsStdFunction() {
1020    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) -> R {
1021      return this->Call(a0, a1, a2, a3, a4, a5, a6);
1022    };
1023  }
1024#endif  // GTEST_HAS_STD_FUNCTION_
1025
1026 private:
1027  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
1028};
1029
1030template <typename R, typename A0, typename A1, typename A2, typename A3,
1031    typename A4, typename A5, typename A6, typename A7>
1032class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7)> {
1033 public:
1034  MockFunction() {}
1035
1036  MOCK_METHOD8_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7));
1037
1038#if GTEST_HAS_STD_FUNCTION_
1039  std::function<R(A0, A1, A2, A3, A4, A5, A6, A7)> AsStdFunction() {
1040    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) -> R {
1041      return this->Call(a0, a1, a2, a3, a4, a5, a6, a7);
1042    };
1043  }
1044#endif  // GTEST_HAS_STD_FUNCTION_
1045
1046 private:
1047  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
1048};
1049
1050template <typename R, typename A0, typename A1, typename A2, typename A3,
1051    typename A4, typename A5, typename A6, typename A7, typename A8>
1052class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> {
1053 public:
1054  MockFunction() {}
1055
1056  MOCK_METHOD9_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8));
1057
1058#if GTEST_HAS_STD_FUNCTION_
1059  std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> AsStdFunction() {
1060    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7,
1061        A8 a8) -> R {
1062      return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8);
1063    };
1064  }
1065#endif  // GTEST_HAS_STD_FUNCTION_
1066
1067 private:
1068  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
1069};
1070
1071template <typename R, typename A0, typename A1, typename A2, typename A3,
1072    typename A4, typename A5, typename A6, typename A7, typename A8,
1073    typename A9>
1074class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
1075 public:
1076  MockFunction() {}
1077
1078  MOCK_METHOD10_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9));
1079
1080#if GTEST_HAS_STD_FUNCTION_
1081  std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> AsStdFunction() {
1082    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7,
1083        A8 a8, A9 a9) -> R {
1084      return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
1085    };
1086  }
1087#endif  // GTEST_HAS_STD_FUNCTION_
1088
1089 private:
1090  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
1091};
1092
1093}  // namespace testing
1094
1095#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$$ This is a Pump source file.  Please use Pump to convert it to
3$$ gmock-generated-function-mockers.h.
4$$
5$var n = 10  $$ The maximum arity we support.
6// Copyright 2007, Google Inc.
7// All rights reserved.
8//
9// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions are
11// met:
12//
13//     * Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//     * Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following disclaimer
17// in the documentation and/or other materials provided with the
18// distribution.
19//     * Neither the name of Google Inc. nor the names of its
20// contributors may be used to endorse or promote products derived from
21// this software without specific prior written permission.
22//
23// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34//
35// Author: wan@google.com (Zhanyong Wan)
36
37// Google Mock - a framework for writing C++ mock classes.
38//
39// This file implements function mockers of various arities.
40
41#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
42#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
43
44#include "gmock/gmock-spec-builders.h"
45#include "gmock/internal/gmock-internal-utils.h"
46
47#if GTEST_HAS_STD_FUNCTION_
48# include <functional>
49#endif
50
51namespace testing {
52namespace internal {
53
54template <typename F>
55class FunctionMockerBase;
56
57// Note: class FunctionMocker really belongs to the ::testing
58// namespace.  However if we define it in ::testing, MSVC will
59// complain when classes in ::testing::internal declare it as a
60// friend class template.  To workaround this compiler bug, we define
61// FunctionMocker in ::testing::internal and import it into ::testing.
62template <typename F>
63class FunctionMocker;
64
65
66$range i 0..n
67$for i [[
68$range j 1..i
69$var typename_As = [[$for j [[, typename A$j]]]]
70$var As = [[$for j, [[A$j]]]]
71$var as = [[$for j, [[a$j]]]]
72$var Aas = [[$for j, [[A$j a$j]]]]
73$var ms = [[$for j, [[m$j]]]]
74$var matchers = [[$for j, [[const Matcher<A$j>& m$j]]]]
75template <typename R$typename_As>
76class FunctionMocker<R($As)> : public
77    internal::FunctionMockerBase<R($As)> {
78 public:
79  typedef R F($As);
80  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
81
82  MockSpec<F>& With($matchers) {
83
84$if i >= 1 [[
85    this->current_spec().SetMatchers(::testing::make_tuple($ms));
86
87]]
88    return this->current_spec();
89  }
90
91  R Invoke($Aas) {
92    // Even though gcc and MSVC don't enforce it, 'this->' is required
93    // by the C++ standard [14.6.4] here, as the base class type is
94    // dependent on the template argument (and thus shouldn't be
95    // looked into when resolving InvokeWith).
96    return this->InvokeWith(ArgumentTuple($as));
97  }
98};
99
100
101]]
102}  // namespace internal
103
104// The style guide prohibits "using" statements in a namespace scope
105// inside a header file.  However, the FunctionMocker class template
106// is meant to be defined in the ::testing namespace.  The following
107// line is just a trick for working around a bug in MSVC 8.0, which
108// cannot handle it if we define FunctionMocker in ::testing.
109using internal::FunctionMocker;
110
111// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
112// We define this as a variadic macro in case F contains unprotected
113// commas (the same reason that we use variadic macros in other places
114// in this file).
115// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
116#define GMOCK_RESULT_(tn, ...) \
117    tn ::testing::internal::Function<__VA_ARGS__>::Result
118
119// The type of argument N of the given function type.
120// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
121#define GMOCK_ARG_(tn, N, ...) \
122    tn ::testing::internal::Function<__VA_ARGS__>::Argument##N
123
124// The matcher type for argument N of the given function type.
125// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
126#define GMOCK_MATCHER_(tn, N, ...) \
127    const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
128
129// The variable for mocking the given method.
130// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
131#define GMOCK_MOCKER_(arity, constness, Method) \
132    GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
133
134
135$for i [[
136$range j 1..i
137$var arg_as = [[$for j, \
138      [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
139$var as = [[$for j, [[gmock_a$j]]]]
140$var matcher_as = [[$for j, \
141                     [[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
142// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
143#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \
144  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
145      $arg_as) constness { \
146    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
147        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value == $i), \
148        this_method_does_not_take_$i[[]]_argument[[$if i != 1 [[s]]]]); \
149    GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \
150    return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \
151  } \
152  ::testing::MockSpec<__VA_ARGS__>& \
153      gmock_##Method($matcher_as) constness { \
154    GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \
155    return GMOCK_MOCKER_($i, constness, Method).With($as); \
156  } \
157  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method)
158
159
160]]
161$for i [[
162#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__)
163
164]]
165
166
167$for i [[
168#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__)
169
170]]
171
172
173$for i [[
174#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__)
175
176]]
177
178
179$for i [[
180#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \
181    GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__)
182
183]]
184
185
186$for i [[
187#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
188    GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__)
189
190]]
191
192
193$for i [[
194#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
195    GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__)
196
197]]
198
199
200$for i [[
201#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
202    GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__)
203
204]]
205
206
207$for i [[
208#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
209    GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__)
210
211]]
212
213// A MockFunction<F> class has one mock method whose type is F.  It is
214// useful when you just want your test code to emit some messages and
215// have Google Mock verify the right messages are sent (and perhaps at
216// the right times).  For example, if you are exercising code:
217//
218//   Foo(1);
219//   Foo(2);
220//   Foo(3);
221//
222// and want to verify that Foo(1) and Foo(3) both invoke
223// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
224//
225// TEST(FooTest, InvokesBarCorrectly) {
226//   MyMock mock;
227//   MockFunction<void(string check_point_name)> check;
228//   {
229//     InSequence s;
230//
231//     EXPECT_CALL(mock, Bar("a"));
232//     EXPECT_CALL(check, Call("1"));
233//     EXPECT_CALL(check, Call("2"));
234//     EXPECT_CALL(mock, Bar("a"));
235//   }
236//   Foo(1);
237//   check.Call("1");
238//   Foo(2);
239//   check.Call("2");
240//   Foo(3);
241// }
242//
243// The expectation spec says that the first Bar("a") must happen
244// before check point "1", the second Bar("a") must happen after check
245// point "2", and nothing should happen between the two check
246// points. The explicit check points make it easy to tell which
247// Bar("a") is called by which call to Foo().
248//
249// MockFunction<F> can also be used to exercise code that accepts
250// std::function<F> callbacks. To do so, use AsStdFunction() method
251// to create std::function proxy forwarding to original object's Call.
252// Example:
253//
254// TEST(FooTest, RunsCallbackWithBarArgument) {
255//   MockFunction<int(string)> callback;
256//   EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
257//   Foo(callback.AsStdFunction());
258// }
259template <typename F>
260class MockFunction;
261
262
263$for i [[
264$range j 0..i-1
265$var ArgTypes = [[$for j, [[A$j]]]]
266$var ArgNames = [[$for j, [[a$j]]]]
267$var ArgDecls = [[$for j, [[A$j a$j]]]]
268template <typename R$for j [[, typename A$j]]>
269class MockFunction<R($ArgTypes)> {
270 public:
271  MockFunction() {}
272
273  MOCK_METHOD$i[[]]_T(Call, R($ArgTypes));
274
275#if GTEST_HAS_STD_FUNCTION_
276  std::function<R($ArgTypes)> AsStdFunction() {
277    return [this]($ArgDecls) -> R {
278      return this->Call($ArgNames);
279    };
280  }
281#endif  // GTEST_HAS_STD_FUNCTION_
282
283 private:
284  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
285};
286
287
288]]
289}  // namespace testing
290
291#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-matchers.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gmock-generated-matchers.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2008, Google Inc.
6// All rights reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34// Google Mock - a framework for writing C++ mock classes.
35//
36// This file implements some commonly used variadic matchers.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
40
41#include <iterator>
42#include <sstream>
43#include <string>
44#include <vector>
45#include "gmock/gmock-matchers.h"
46
47namespace testing {
48namespace internal {
49
50// The type of the i-th (0-based) field of Tuple.
51#define GMOCK_FIELD_TYPE_(Tuple, i) \
52    typename ::testing::tuple_element<i, Tuple>::type
53
54// TupleFields<Tuple, k0, ..., kn> is for selecting fields from a
55// tuple of type Tuple.  It has two members:
56//
57//   type: a tuple type whose i-th field is the ki-th field of Tuple.
58//   GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple.
59//
60// For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have:
61//
62//   type is tuple<int, bool>, and
63//   GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true).
64
65template <class Tuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1,
66    int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1,
67    int k9 = -1>
68class TupleFields;
69
70// This generic version is used when there are 10 selectors.
71template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6,
72    int k7, int k8, int k9>
73class TupleFields {
74 public:
75  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
76      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
77      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
78      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6),
79      GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8),
80      GMOCK_FIELD_TYPE_(Tuple, k9)> type;
81  static type GetSelectedFields(const Tuple& t) {
82    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
83        get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t), get<k9>(t));
84  }
85};
86
87// The following specialization is used for 0 ~ 9 selectors.
88
89template <class Tuple>
90class TupleFields<Tuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
91 public:
92  typedef ::testing::tuple<> type;
93  static type GetSelectedFields(const Tuple& /* t */) {
94    return type();
95  }
96};
97
98template <class Tuple, int k0>
99class TupleFields<Tuple, k0, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
100 public:
101  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0)> type;
102  static type GetSelectedFields(const Tuple& t) {
103    return type(get<k0>(t));
104  }
105};
106
107template <class Tuple, int k0, int k1>
108class TupleFields<Tuple, k0, k1, -1, -1, -1, -1, -1, -1, -1, -1> {
109 public:
110  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
111      GMOCK_FIELD_TYPE_(Tuple, k1)> type;
112  static type GetSelectedFields(const Tuple& t) {
113    return type(get<k0>(t), get<k1>(t));
114  }
115};
116
117template <class Tuple, int k0, int k1, int k2>
118class TupleFields<Tuple, k0, k1, k2, -1, -1, -1, -1, -1, -1, -1> {
119 public:
120  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
121      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2)> type;
122  static type GetSelectedFields(const Tuple& t) {
123    return type(get<k0>(t), get<k1>(t), get<k2>(t));
124  }
125};
126
127template <class Tuple, int k0, int k1, int k2, int k3>
128class TupleFields<Tuple, k0, k1, k2, k3, -1, -1, -1, -1, -1, -1> {
129 public:
130  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
131      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
132      GMOCK_FIELD_TYPE_(Tuple, k3)> type;
133  static type GetSelectedFields(const Tuple& t) {
134    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t));
135  }
136};
137
138template <class Tuple, int k0, int k1, int k2, int k3, int k4>
139class TupleFields<Tuple, k0, k1, k2, k3, k4, -1, -1, -1, -1, -1> {
140 public:
141  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
142      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
143      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4)> type;
144  static type GetSelectedFields(const Tuple& t) {
145    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t));
146  }
147};
148
149template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5>
150class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, -1, -1, -1, -1> {
151 public:
152  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
153      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
154      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
155      GMOCK_FIELD_TYPE_(Tuple, k5)> type;
156  static type GetSelectedFields(const Tuple& t) {
157    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
158        get<k5>(t));
159  }
160};
161
162template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6>
163class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, -1, -1, -1> {
164 public:
165  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
166      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
167      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
168      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6)> type;
169  static type GetSelectedFields(const Tuple& t) {
170    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
171        get<k5>(t), get<k6>(t));
172  }
173};
174
175template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6,
176    int k7>
177class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, -1, -1> {
178 public:
179  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
180      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
181      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
182      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6),
183      GMOCK_FIELD_TYPE_(Tuple, k7)> type;
184  static type GetSelectedFields(const Tuple& t) {
185    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
186        get<k5>(t), get<k6>(t), get<k7>(t));
187  }
188};
189
190template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6,
191    int k7, int k8>
192class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, -1> {
193 public:
194  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
195      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
196      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
197      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6),
198      GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8)> type;
199  static type GetSelectedFields(const Tuple& t) {
200    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
201        get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t));
202  }
203};
204
205#undef GMOCK_FIELD_TYPE_
206
207// Implements the Args() matcher.
208template <class ArgsTuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1,
209    int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1,
210    int k9 = -1>
211class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
212 public:
213  // ArgsTuple may have top-level const or reference modifiers.
214  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple;
215  typedef typename internal::TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5,
216      k6, k7, k8, k9>::type SelectedArgs;
217  typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher;
218
219  template <typename InnerMatcher>
220  explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
221      : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
222
223  virtual bool MatchAndExplain(ArgsTuple args,
224                               MatchResultListener* listener) const {
225    const SelectedArgs& selected_args = GetSelectedArgs(args);
226    if (!listener->IsInterested())
227      return inner_matcher_.Matches(selected_args);
228
229    PrintIndices(listener->stream());
230    *listener << "are " << PrintToString(selected_args);
231
232    StringMatchResultListener inner_listener;
233    const bool match = inner_matcher_.MatchAndExplain(selected_args,
234                                                      &inner_listener);
235    PrintIfNotEmpty(inner_listener.str(), listener->stream());
236    return match;
237  }
238
239  virtual void DescribeTo(::std::ostream* os) const {
240    *os << "are a tuple ";
241    PrintIndices(os);
242    inner_matcher_.DescribeTo(os);
243  }
244
245  virtual void DescribeNegationTo(::std::ostream* os) const {
246    *os << "are a tuple ";
247    PrintIndices(os);
248    inner_matcher_.DescribeNegationTo(os);
249  }
250
251 private:
252  static SelectedArgs GetSelectedArgs(ArgsTuple args) {
253    return TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8,
254        k9>::GetSelectedFields(args);
255  }
256
257  // Prints the indices of the selected fields.
258  static void PrintIndices(::std::ostream* os) {
259    *os << "whose fields (";
260    const int indices[10] = { k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 };
261    for (int i = 0; i < 10; i++) {
262      if (indices[i] < 0)
263        break;
264
265      if (i >= 1)
266        *os << ", ";
267
268      *os << "#" << indices[i];
269    }
270    *os << ") ";
271  }
272
273  const MonomorphicInnerMatcher inner_matcher_;
274
275  GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl);
276};
277
278template <class InnerMatcher, int k0 = -1, int k1 = -1, int k2 = -1,
279    int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1,
280    int k8 = -1, int k9 = -1>
281class ArgsMatcher {
282 public:
283  explicit ArgsMatcher(const InnerMatcher& inner_matcher)
284      : inner_matcher_(inner_matcher) {}
285
286  template <typename ArgsTuple>
287  operator Matcher<ArgsTuple>() const {
288    return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k0, k1, k2, k3, k4, k5,
289        k6, k7, k8, k9>(inner_matcher_));
290  }
291
292 private:
293  const InnerMatcher inner_matcher_;
294
295  GTEST_DISALLOW_ASSIGN_(ArgsMatcher);
296};
297
298// A set of metafunctions for computing the result type of AllOf.
299// AllOf(m1, ..., mN) returns
300// AllOfResultN<decltype(m1), ..., decltype(mN)>::type.
301
302// Although AllOf isn't defined for one argument, AllOfResult1 is defined
303// to simplify the implementation.
304template <typename M1>
305struct AllOfResult1 {
306  typedef M1 type;
307};
308
309template <typename M1, typename M2>
310struct AllOfResult2 {
311  typedef BothOfMatcher<
312      typename AllOfResult1<M1>::type,
313      typename AllOfResult1<M2>::type
314  > type;
315};
316
317template <typename M1, typename M2, typename M3>
318struct AllOfResult3 {
319  typedef BothOfMatcher<
320      typename AllOfResult1<M1>::type,
321      typename AllOfResult2<M2, M3>::type
322  > type;
323};
324
325template <typename M1, typename M2, typename M3, typename M4>
326struct AllOfResult4 {
327  typedef BothOfMatcher<
328      typename AllOfResult2<M1, M2>::type,
329      typename AllOfResult2<M3, M4>::type
330  > type;
331};
332
333template <typename M1, typename M2, typename M3, typename M4, typename M5>
334struct AllOfResult5 {
335  typedef BothOfMatcher<
336      typename AllOfResult2<M1, M2>::type,
337      typename AllOfResult3<M3, M4, M5>::type
338  > type;
339};
340
341template <typename M1, typename M2, typename M3, typename M4, typename M5,
342    typename M6>
343struct AllOfResult6 {
344  typedef BothOfMatcher<
345      typename AllOfResult3<M1, M2, M3>::type,
346      typename AllOfResult3<M4, M5, M6>::type
347  > type;
348};
349
350template <typename M1, typename M2, typename M3, typename M4, typename M5,
351    typename M6, typename M7>
352struct AllOfResult7 {
353  typedef BothOfMatcher<
354      typename AllOfResult3<M1, M2, M3>::type,
355      typename AllOfResult4<M4, M5, M6, M7>::type
356  > type;
357};
358
359template <typename M1, typename M2, typename M3, typename M4, typename M5,
360    typename M6, typename M7, typename M8>
361struct AllOfResult8 {
362  typedef BothOfMatcher<
363      typename AllOfResult4<M1, M2, M3, M4>::type,
364      typename AllOfResult4<M5, M6, M7, M8>::type
365  > type;
366};
367
368template <typename M1, typename M2, typename M3, typename M4, typename M5,
369    typename M6, typename M7, typename M8, typename M9>
370struct AllOfResult9 {
371  typedef BothOfMatcher<
372      typename AllOfResult4<M1, M2, M3, M4>::type,
373      typename AllOfResult5<M5, M6, M7, M8, M9>::type
374  > type;
375};
376
377template <typename M1, typename M2, typename M3, typename M4, typename M5,
378    typename M6, typename M7, typename M8, typename M9, typename M10>
379struct AllOfResult10 {
380  typedef BothOfMatcher<
381      typename AllOfResult5<M1, M2, M3, M4, M5>::type,
382      typename AllOfResult5<M6, M7, M8, M9, M10>::type
383  > type;
384};
385
386// A set of metafunctions for computing the result type of AnyOf.
387// AnyOf(m1, ..., mN) returns
388// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type.
389
390// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined
391// to simplify the implementation.
392template <typename M1>
393struct AnyOfResult1 {
394  typedef M1 type;
395};
396
397template <typename M1, typename M2>
398struct AnyOfResult2 {
399  typedef EitherOfMatcher<
400      typename AnyOfResult1<M1>::type,
401      typename AnyOfResult1<M2>::type
402  > type;
403};
404
405template <typename M1, typename M2, typename M3>
406struct AnyOfResult3 {
407  typedef EitherOfMatcher<
408      typename AnyOfResult1<M1>::type,
409      typename AnyOfResult2<M2, M3>::type
410  > type;
411};
412
413template <typename M1, typename M2, typename M3, typename M4>
414struct AnyOfResult4 {
415  typedef EitherOfMatcher<
416      typename AnyOfResult2<M1, M2>::type,
417      typename AnyOfResult2<M3, M4>::type
418  > type;
419};
420
421template <typename M1, typename M2, typename M3, typename M4, typename M5>
422struct AnyOfResult5 {
423  typedef EitherOfMatcher<
424      typename AnyOfResult2<M1, M2>::type,
425      typename AnyOfResult3<M3, M4, M5>::type
426  > type;
427};
428
429template <typename M1, typename M2, typename M3, typename M4, typename M5,
430    typename M6>
431struct AnyOfResult6 {
432  typedef EitherOfMatcher<
433      typename AnyOfResult3<M1, M2, M3>::type,
434      typename AnyOfResult3<M4, M5, M6>::type
435  > type;
436};
437
438template <typename M1, typename M2, typename M3, typename M4, typename M5,
439    typename M6, typename M7>
440struct AnyOfResult7 {
441  typedef EitherOfMatcher<
442      typename AnyOfResult3<M1, M2, M3>::type,
443      typename AnyOfResult4<M4, M5, M6, M7>::type
444  > type;
445};
446
447template <typename M1, typename M2, typename M3, typename M4, typename M5,
448    typename M6, typename M7, typename M8>
449struct AnyOfResult8 {
450  typedef EitherOfMatcher<
451      typename AnyOfResult4<M1, M2, M3, M4>::type,
452      typename AnyOfResult4<M5, M6, M7, M8>::type
453  > type;
454};
455
456template <typename M1, typename M2, typename M3, typename M4, typename M5,
457    typename M6, typename M7, typename M8, typename M9>
458struct AnyOfResult9 {
459  typedef EitherOfMatcher<
460      typename AnyOfResult4<M1, M2, M3, M4>::type,
461      typename AnyOfResult5<M5, M6, M7, M8, M9>::type
462  > type;
463};
464
465template <typename M1, typename M2, typename M3, typename M4, typename M5,
466    typename M6, typename M7, typename M8, typename M9, typename M10>
467struct AnyOfResult10 {
468  typedef EitherOfMatcher<
469      typename AnyOfResult5<M1, M2, M3, M4, M5>::type,
470      typename AnyOfResult5<M6, M7, M8, M9, M10>::type
471  > type;
472};
473
474}  // namespace internal
475
476// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
477// fields of it matches a_matcher.  C++ doesn't support default
478// arguments for function templates, so we have to overload it.
479template <typename InnerMatcher>
480inline internal::ArgsMatcher<InnerMatcher>
481Args(const InnerMatcher& matcher) {
482  return internal::ArgsMatcher<InnerMatcher>(matcher);
483}
484
485template <int k1, typename InnerMatcher>
486inline internal::ArgsMatcher<InnerMatcher, k1>
487Args(const InnerMatcher& matcher) {
488  return internal::ArgsMatcher<InnerMatcher, k1>(matcher);
489}
490
491template <int k1, int k2, typename InnerMatcher>
492inline internal::ArgsMatcher<InnerMatcher, k1, k2>
493Args(const InnerMatcher& matcher) {
494  return internal::ArgsMatcher<InnerMatcher, k1, k2>(matcher);
495}
496
497template <int k1, int k2, int k3, typename InnerMatcher>
498inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3>
499Args(const InnerMatcher& matcher) {
500  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3>(matcher);
501}
502
503template <int k1, int k2, int k3, int k4, typename InnerMatcher>
504inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4>
505Args(const InnerMatcher& matcher) {
506  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4>(matcher);
507}
508
509template <int k1, int k2, int k3, int k4, int k5, typename InnerMatcher>
510inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5>
511Args(const InnerMatcher& matcher) {
512  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5>(matcher);
513}
514
515template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerMatcher>
516inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6>
517Args(const InnerMatcher& matcher) {
518  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6>(matcher);
519}
520
521template <int k1, int k2, int k3, int k4, int k5, int k6, int k7,
522    typename InnerMatcher>
523inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7>
524Args(const InnerMatcher& matcher) {
525  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6,
526      k7>(matcher);
527}
528
529template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
530    typename InnerMatcher>
531inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8>
532Args(const InnerMatcher& matcher) {
533  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7,
534      k8>(matcher);
535}
536
537template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
538    int k9, typename InnerMatcher>
539inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9>
540Args(const InnerMatcher& matcher) {
541  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8,
542      k9>(matcher);
543}
544
545template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
546    int k9, int k10, typename InnerMatcher>
547inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9,
548    k10>
549Args(const InnerMatcher& matcher) {
550  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8,
551      k9, k10>(matcher);
552}
553
554// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with
555// n elements, where the i-th element in the container must
556// match the i-th argument in the list.  Each argument of
557// ElementsAre() can be either a value or a matcher.  We support up to
558// 10 arguments.
559//
560// The use of DecayArray in the implementation allows ElementsAre()
561// to accept string literals, whose type is const char[N], but we
562// want to treat them as const char*.
563//
564// NOTE: Since ElementsAre() cares about the order of the elements, it
565// must not be used with containers whose elements's order is
566// undefined (e.g. hash_map).
567
568inline internal::ElementsAreMatcher<
569    ::testing::tuple<> >
570ElementsAre() {
571  typedef ::testing::tuple<> Args;
572  return internal::ElementsAreMatcher<Args>(Args());
573}
574
575template <typename T1>
576inline internal::ElementsAreMatcher<
577    ::testing::tuple<
578        typename internal::DecayArray<T1>::type> >
579ElementsAre(const T1& e1) {
580  typedef ::testing::tuple<
581      typename internal::DecayArray<T1>::type> Args;
582  return internal::ElementsAreMatcher<Args>(Args(e1));
583}
584
585template <typename T1, typename T2>
586inline internal::ElementsAreMatcher<
587    ::testing::tuple<
588        typename internal::DecayArray<T1>::type,
589        typename internal::DecayArray<T2>::type> >
590ElementsAre(const T1& e1, const T2& e2) {
591  typedef ::testing::tuple<
592      typename internal::DecayArray<T1>::type,
593      typename internal::DecayArray<T2>::type> Args;
594  return internal::ElementsAreMatcher<Args>(Args(e1, e2));
595}
596
597template <typename T1, typename T2, typename T3>
598inline internal::ElementsAreMatcher<
599    ::testing::tuple<
600        typename internal::DecayArray<T1>::type,
601        typename internal::DecayArray<T2>::type,
602        typename internal::DecayArray<T3>::type> >
603ElementsAre(const T1& e1, const T2& e2, const T3& e3) {
604  typedef ::testing::tuple<
605      typename internal::DecayArray<T1>::type,
606      typename internal::DecayArray<T2>::type,
607      typename internal::DecayArray<T3>::type> Args;
608  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3));
609}
610
611template <typename T1, typename T2, typename T3, typename T4>
612inline internal::ElementsAreMatcher<
613    ::testing::tuple<
614        typename internal::DecayArray<T1>::type,
615        typename internal::DecayArray<T2>::type,
616        typename internal::DecayArray<T3>::type,
617        typename internal::DecayArray<T4>::type> >
618ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) {
619  typedef ::testing::tuple<
620      typename internal::DecayArray<T1>::type,
621      typename internal::DecayArray<T2>::type,
622      typename internal::DecayArray<T3>::type,
623      typename internal::DecayArray<T4>::type> Args;
624  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4));
625}
626
627template <typename T1, typename T2, typename T3, typename T4, typename T5>
628inline internal::ElementsAreMatcher<
629    ::testing::tuple<
630        typename internal::DecayArray<T1>::type,
631        typename internal::DecayArray<T2>::type,
632        typename internal::DecayArray<T3>::type,
633        typename internal::DecayArray<T4>::type,
634        typename internal::DecayArray<T5>::type> >
635ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
636    const T5& e5) {
637  typedef ::testing::tuple<
638      typename internal::DecayArray<T1>::type,
639      typename internal::DecayArray<T2>::type,
640      typename internal::DecayArray<T3>::type,
641      typename internal::DecayArray<T4>::type,
642      typename internal::DecayArray<T5>::type> Args;
643  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5));
644}
645
646template <typename T1, typename T2, typename T3, typename T4, typename T5,
647    typename T6>
648inline internal::ElementsAreMatcher<
649    ::testing::tuple<
650        typename internal::DecayArray<T1>::type,
651        typename internal::DecayArray<T2>::type,
652        typename internal::DecayArray<T3>::type,
653        typename internal::DecayArray<T4>::type,
654        typename internal::DecayArray<T5>::type,
655        typename internal::DecayArray<T6>::type> >
656ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
657    const T5& e5, const T6& e6) {
658  typedef ::testing::tuple<
659      typename internal::DecayArray<T1>::type,
660      typename internal::DecayArray<T2>::type,
661      typename internal::DecayArray<T3>::type,
662      typename internal::DecayArray<T4>::type,
663      typename internal::DecayArray<T5>::type,
664      typename internal::DecayArray<T6>::type> Args;
665  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6));
666}
667
668template <typename T1, typename T2, typename T3, typename T4, typename T5,
669    typename T6, typename T7>
670inline internal::ElementsAreMatcher<
671    ::testing::tuple<
672        typename internal::DecayArray<T1>::type,
673        typename internal::DecayArray<T2>::type,
674        typename internal::DecayArray<T3>::type,
675        typename internal::DecayArray<T4>::type,
676        typename internal::DecayArray<T5>::type,
677        typename internal::DecayArray<T6>::type,
678        typename internal::DecayArray<T7>::type> >
679ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
680    const T5& e5, const T6& e6, const T7& e7) {
681  typedef ::testing::tuple<
682      typename internal::DecayArray<T1>::type,
683      typename internal::DecayArray<T2>::type,
684      typename internal::DecayArray<T3>::type,
685      typename internal::DecayArray<T4>::type,
686      typename internal::DecayArray<T5>::type,
687      typename internal::DecayArray<T6>::type,
688      typename internal::DecayArray<T7>::type> Args;
689  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7));
690}
691
692template <typename T1, typename T2, typename T3, typename T4, typename T5,
693    typename T6, typename T7, typename T8>
694inline internal::ElementsAreMatcher<
695    ::testing::tuple<
696        typename internal::DecayArray<T1>::type,
697        typename internal::DecayArray<T2>::type,
698        typename internal::DecayArray<T3>::type,
699        typename internal::DecayArray<T4>::type,
700        typename internal::DecayArray<T5>::type,
701        typename internal::DecayArray<T6>::type,
702        typename internal::DecayArray<T7>::type,
703        typename internal::DecayArray<T8>::type> >
704ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
705    const T5& e5, const T6& e6, const T7& e7, const T8& e8) {
706  typedef ::testing::tuple<
707      typename internal::DecayArray<T1>::type,
708      typename internal::DecayArray<T2>::type,
709      typename internal::DecayArray<T3>::type,
710      typename internal::DecayArray<T4>::type,
711      typename internal::DecayArray<T5>::type,
712      typename internal::DecayArray<T6>::type,
713      typename internal::DecayArray<T7>::type,
714      typename internal::DecayArray<T8>::type> Args;
715  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7,
716      e8));
717}
718
719template <typename T1, typename T2, typename T3, typename T4, typename T5,
720    typename T6, typename T7, typename T8, typename T9>
721inline internal::ElementsAreMatcher<
722    ::testing::tuple<
723        typename internal::DecayArray<T1>::type,
724        typename internal::DecayArray<T2>::type,
725        typename internal::DecayArray<T3>::type,
726        typename internal::DecayArray<T4>::type,
727        typename internal::DecayArray<T5>::type,
728        typename internal::DecayArray<T6>::type,
729        typename internal::DecayArray<T7>::type,
730        typename internal::DecayArray<T8>::type,
731        typename internal::DecayArray<T9>::type> >
732ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
733    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) {
734  typedef ::testing::tuple<
735      typename internal::DecayArray<T1>::type,
736      typename internal::DecayArray<T2>::type,
737      typename internal::DecayArray<T3>::type,
738      typename internal::DecayArray<T4>::type,
739      typename internal::DecayArray<T5>::type,
740      typename internal::DecayArray<T6>::type,
741      typename internal::DecayArray<T7>::type,
742      typename internal::DecayArray<T8>::type,
743      typename internal::DecayArray<T9>::type> Args;
744  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7,
745      e8, e9));
746}
747
748template <typename T1, typename T2, typename T3, typename T4, typename T5,
749    typename T6, typename T7, typename T8, typename T9, typename T10>
750inline internal::ElementsAreMatcher<
751    ::testing::tuple<
752        typename internal::DecayArray<T1>::type,
753        typename internal::DecayArray<T2>::type,
754        typename internal::DecayArray<T3>::type,
755        typename internal::DecayArray<T4>::type,
756        typename internal::DecayArray<T5>::type,
757        typename internal::DecayArray<T6>::type,
758        typename internal::DecayArray<T7>::type,
759        typename internal::DecayArray<T8>::type,
760        typename internal::DecayArray<T9>::type,
761        typename internal::DecayArray<T10>::type> >
762ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
763    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9,
764    const T10& e10) {
765  typedef ::testing::tuple<
766      typename internal::DecayArray<T1>::type,
767      typename internal::DecayArray<T2>::type,
768      typename internal::DecayArray<T3>::type,
769      typename internal::DecayArray<T4>::type,
770      typename internal::DecayArray<T5>::type,
771      typename internal::DecayArray<T6>::type,
772      typename internal::DecayArray<T7>::type,
773      typename internal::DecayArray<T8>::type,
774      typename internal::DecayArray<T9>::type,
775      typename internal::DecayArray<T10>::type> Args;
776  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7,
777      e8, e9, e10));
778}
779
780// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension
781// that matches n elements in any order.  We support up to n=10 arguments.
782
783inline internal::UnorderedElementsAreMatcher<
784    ::testing::tuple<> >
785UnorderedElementsAre() {
786  typedef ::testing::tuple<> Args;
787  return internal::UnorderedElementsAreMatcher<Args>(Args());
788}
789
790template <typename T1>
791inline internal::UnorderedElementsAreMatcher<
792    ::testing::tuple<
793        typename internal::DecayArray<T1>::type> >
794UnorderedElementsAre(const T1& e1) {
795  typedef ::testing::tuple<
796      typename internal::DecayArray<T1>::type> Args;
797  return internal::UnorderedElementsAreMatcher<Args>(Args(e1));
798}
799
800template <typename T1, typename T2>
801inline internal::UnorderedElementsAreMatcher<
802    ::testing::tuple<
803        typename internal::DecayArray<T1>::type,
804        typename internal::DecayArray<T2>::type> >
805UnorderedElementsAre(const T1& e1, const T2& e2) {
806  typedef ::testing::tuple<
807      typename internal::DecayArray<T1>::type,
808      typename internal::DecayArray<T2>::type> Args;
809  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2));
810}
811
812template <typename T1, typename T2, typename T3>
813inline internal::UnorderedElementsAreMatcher<
814    ::testing::tuple<
815        typename internal::DecayArray<T1>::type,
816        typename internal::DecayArray<T2>::type,
817        typename internal::DecayArray<T3>::type> >
818UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3) {
819  typedef ::testing::tuple<
820      typename internal::DecayArray<T1>::type,
821      typename internal::DecayArray<T2>::type,
822      typename internal::DecayArray<T3>::type> Args;
823  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3));
824}
825
826template <typename T1, typename T2, typename T3, typename T4>
827inline internal::UnorderedElementsAreMatcher<
828    ::testing::tuple<
829        typename internal::DecayArray<T1>::type,
830        typename internal::DecayArray<T2>::type,
831        typename internal::DecayArray<T3>::type,
832        typename internal::DecayArray<T4>::type> >
833UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) {
834  typedef ::testing::tuple<
835      typename internal::DecayArray<T1>::type,
836      typename internal::DecayArray<T2>::type,
837      typename internal::DecayArray<T3>::type,
838      typename internal::DecayArray<T4>::type> Args;
839  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4));
840}
841
842template <typename T1, typename T2, typename T3, typename T4, typename T5>
843inline internal::UnorderedElementsAreMatcher<
844    ::testing::tuple<
845        typename internal::DecayArray<T1>::type,
846        typename internal::DecayArray<T2>::type,
847        typename internal::DecayArray<T3>::type,
848        typename internal::DecayArray<T4>::type,
849        typename internal::DecayArray<T5>::type> >
850UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
851    const T5& e5) {
852  typedef ::testing::tuple<
853      typename internal::DecayArray<T1>::type,
854      typename internal::DecayArray<T2>::type,
855      typename internal::DecayArray<T3>::type,
856      typename internal::DecayArray<T4>::type,
857      typename internal::DecayArray<T5>::type> Args;
858  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5));
859}
860
861template <typename T1, typename T2, typename T3, typename T4, typename T5,
862    typename T6>
863inline internal::UnorderedElementsAreMatcher<
864    ::testing::tuple<
865        typename internal::DecayArray<T1>::type,
866        typename internal::DecayArray<T2>::type,
867        typename internal::DecayArray<T3>::type,
868        typename internal::DecayArray<T4>::type,
869        typename internal::DecayArray<T5>::type,
870        typename internal::DecayArray<T6>::type> >
871UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
872    const T5& e5, const T6& e6) {
873  typedef ::testing::tuple<
874      typename internal::DecayArray<T1>::type,
875      typename internal::DecayArray<T2>::type,
876      typename internal::DecayArray<T3>::type,
877      typename internal::DecayArray<T4>::type,
878      typename internal::DecayArray<T5>::type,
879      typename internal::DecayArray<T6>::type> Args;
880  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
881      e6));
882}
883
884template <typename T1, typename T2, typename T3, typename T4, typename T5,
885    typename T6, typename T7>
886inline internal::UnorderedElementsAreMatcher<
887    ::testing::tuple<
888        typename internal::DecayArray<T1>::type,
889        typename internal::DecayArray<T2>::type,
890        typename internal::DecayArray<T3>::type,
891        typename internal::DecayArray<T4>::type,
892        typename internal::DecayArray<T5>::type,
893        typename internal::DecayArray<T6>::type,
894        typename internal::DecayArray<T7>::type> >
895UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
896    const T5& e5, const T6& e6, const T7& e7) {
897  typedef ::testing::tuple<
898      typename internal::DecayArray<T1>::type,
899      typename internal::DecayArray<T2>::type,
900      typename internal::DecayArray<T3>::type,
901      typename internal::DecayArray<T4>::type,
902      typename internal::DecayArray<T5>::type,
903      typename internal::DecayArray<T6>::type,
904      typename internal::DecayArray<T7>::type> Args;
905  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
906      e6, e7));
907}
908
909template <typename T1, typename T2, typename T3, typename T4, typename T5,
910    typename T6, typename T7, typename T8>
911inline internal::UnorderedElementsAreMatcher<
912    ::testing::tuple<
913        typename internal::DecayArray<T1>::type,
914        typename internal::DecayArray<T2>::type,
915        typename internal::DecayArray<T3>::type,
916        typename internal::DecayArray<T4>::type,
917        typename internal::DecayArray<T5>::type,
918        typename internal::DecayArray<T6>::type,
919        typename internal::DecayArray<T7>::type,
920        typename internal::DecayArray<T8>::type> >
921UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
922    const T5& e5, const T6& e6, const T7& e7, const T8& e8) {
923  typedef ::testing::tuple<
924      typename internal::DecayArray<T1>::type,
925      typename internal::DecayArray<T2>::type,
926      typename internal::DecayArray<T3>::type,
927      typename internal::DecayArray<T4>::type,
928      typename internal::DecayArray<T5>::type,
929      typename internal::DecayArray<T6>::type,
930      typename internal::DecayArray<T7>::type,
931      typename internal::DecayArray<T8>::type> Args;
932  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
933      e6, e7, e8));
934}
935
936template <typename T1, typename T2, typename T3, typename T4, typename T5,
937    typename T6, typename T7, typename T8, typename T9>
938inline internal::UnorderedElementsAreMatcher<
939    ::testing::tuple<
940        typename internal::DecayArray<T1>::type,
941        typename internal::DecayArray<T2>::type,
942        typename internal::DecayArray<T3>::type,
943        typename internal::DecayArray<T4>::type,
944        typename internal::DecayArray<T5>::type,
945        typename internal::DecayArray<T6>::type,
946        typename internal::DecayArray<T7>::type,
947        typename internal::DecayArray<T8>::type,
948        typename internal::DecayArray<T9>::type> >
949UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
950    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) {
951  typedef ::testing::tuple<
952      typename internal::DecayArray<T1>::type,
953      typename internal::DecayArray<T2>::type,
954      typename internal::DecayArray<T3>::type,
955      typename internal::DecayArray<T4>::type,
956      typename internal::DecayArray<T5>::type,
957      typename internal::DecayArray<T6>::type,
958      typename internal::DecayArray<T7>::type,
959      typename internal::DecayArray<T8>::type,
960      typename internal::DecayArray<T9>::type> Args;
961  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
962      e6, e7, e8, e9));
963}
964
965template <typename T1, typename T2, typename T3, typename T4, typename T5,
966    typename T6, typename T7, typename T8, typename T9, typename T10>
967inline internal::UnorderedElementsAreMatcher<
968    ::testing::tuple<
969        typename internal::DecayArray<T1>::type,
970        typename internal::DecayArray<T2>::type,
971        typename internal::DecayArray<T3>::type,
972        typename internal::DecayArray<T4>::type,
973        typename internal::DecayArray<T5>::type,
974        typename internal::DecayArray<T6>::type,
975        typename internal::DecayArray<T7>::type,
976        typename internal::DecayArray<T8>::type,
977        typename internal::DecayArray<T9>::type,
978        typename internal::DecayArray<T10>::type> >
979UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
980    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9,
981    const T10& e10) {
982  typedef ::testing::tuple<
983      typename internal::DecayArray<T1>::type,
984      typename internal::DecayArray<T2>::type,
985      typename internal::DecayArray<T3>::type,
986      typename internal::DecayArray<T4>::type,
987      typename internal::DecayArray<T5>::type,
988      typename internal::DecayArray<T6>::type,
989      typename internal::DecayArray<T7>::type,
990      typename internal::DecayArray<T8>::type,
991      typename internal::DecayArray<T9>::type,
992      typename internal::DecayArray<T10>::type> Args;
993  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
994      e6, e7, e8, e9, e10));
995}
996
997// AllOf(m1, m2, ..., mk) matches any value that matches all of the given
998// sub-matchers.  AllOf is called fully qualified to prevent ADL from firing.
999
1000template <typename M1, typename M2>
1001inline typename internal::AllOfResult2<M1, M2>::type
1002AllOf(M1 m1, M2 m2) {
1003  return typename internal::AllOfResult2<M1, M2>::type(
1004      m1,
1005      m2);
1006}
1007
1008template <typename M1, typename M2, typename M3>
1009inline typename internal::AllOfResult3<M1, M2, M3>::type
1010AllOf(M1 m1, M2 m2, M3 m3) {
1011  return typename internal::AllOfResult3<M1, M2, M3>::type(
1012      m1,
1013      ::testing::AllOf(m2, m3));
1014}
1015
1016template <typename M1, typename M2, typename M3, typename M4>
1017inline typename internal::AllOfResult4<M1, M2, M3, M4>::type
1018AllOf(M1 m1, M2 m2, M3 m3, M4 m4) {
1019  return typename internal::AllOfResult4<M1, M2, M3, M4>::type(
1020      ::testing::AllOf(m1, m2),
1021      ::testing::AllOf(m3, m4));
1022}
1023
1024template <typename M1, typename M2, typename M3, typename M4, typename M5>
1025inline typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type
1026AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) {
1027  return typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type(
1028      ::testing::AllOf(m1, m2),
1029      ::testing::AllOf(m3, m4, m5));
1030}
1031
1032template <typename M1, typename M2, typename M3, typename M4, typename M5,
1033    typename M6>
1034inline typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type
1035AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) {
1036  return typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type(
1037      ::testing::AllOf(m1, m2, m3),
1038      ::testing::AllOf(m4, m5, m6));
1039}
1040
1041template <typename M1, typename M2, typename M3, typename M4, typename M5,
1042    typename M6, typename M7>
1043inline typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type
1044AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) {
1045  return typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type(
1046      ::testing::AllOf(m1, m2, m3),
1047      ::testing::AllOf(m4, m5, m6, m7));
1048}
1049
1050template <typename M1, typename M2, typename M3, typename M4, typename M5,
1051    typename M6, typename M7, typename M8>
1052inline typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type
1053AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) {
1054  return typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type(
1055      ::testing::AllOf(m1, m2, m3, m4),
1056      ::testing::AllOf(m5, m6, m7, m8));
1057}
1058
1059template <typename M1, typename M2, typename M3, typename M4, typename M5,
1060    typename M6, typename M7, typename M8, typename M9>
1061inline typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type
1062AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) {
1063  return typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8,
1064      M9>::type(
1065      ::testing::AllOf(m1, m2, m3, m4),
1066      ::testing::AllOf(m5, m6, m7, m8, m9));
1067}
1068
1069template <typename M1, typename M2, typename M3, typename M4, typename M5,
1070    typename M6, typename M7, typename M8, typename M9, typename M10>
1071inline typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
1072    M10>::type
1073AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) {
1074  return typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
1075      M10>::type(
1076      ::testing::AllOf(m1, m2, m3, m4, m5),
1077      ::testing::AllOf(m6, m7, m8, m9, m10));
1078}
1079
1080// AnyOf(m1, m2, ..., mk) matches any value that matches any of the given
1081// sub-matchers.  AnyOf is called fully qualified to prevent ADL from firing.
1082
1083template <typename M1, typename M2>
1084inline typename internal::AnyOfResult2<M1, M2>::type
1085AnyOf(M1 m1, M2 m2) {
1086  return typename internal::AnyOfResult2<M1, M2>::type(
1087      m1,
1088      m2);
1089}
1090
1091template <typename M1, typename M2, typename M3>
1092inline typename internal::AnyOfResult3<M1, M2, M3>::type
1093AnyOf(M1 m1, M2 m2, M3 m3) {
1094  return typename internal::AnyOfResult3<M1, M2, M3>::type(
1095      m1,
1096      ::testing::AnyOf(m2, m3));
1097}
1098
1099template <typename M1, typename M2, typename M3, typename M4>
1100inline typename internal::AnyOfResult4<M1, M2, M3, M4>::type
1101AnyOf(M1 m1, M2 m2, M3 m3, M4 m4) {
1102  return typename internal::AnyOfResult4<M1, M2, M3, M4>::type(
1103      ::testing::AnyOf(m1, m2),
1104      ::testing::AnyOf(m3, m4));
1105}
1106
1107template <typename M1, typename M2, typename M3, typename M4, typename M5>
1108inline typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type
1109AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) {
1110  return typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type(
1111      ::testing::AnyOf(m1, m2),
1112      ::testing::AnyOf(m3, m4, m5));
1113}
1114
1115template <typename M1, typename M2, typename M3, typename M4, typename M5,
1116    typename M6>
1117inline typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type
1118AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) {
1119  return typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type(
1120      ::testing::AnyOf(m1, m2, m3),
1121      ::testing::AnyOf(m4, m5, m6));
1122}
1123
1124template <typename M1, typename M2, typename M3, typename M4, typename M5,
1125    typename M6, typename M7>
1126inline typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type
1127AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) {
1128  return typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type(
1129      ::testing::AnyOf(m1, m2, m3),
1130      ::testing::AnyOf(m4, m5, m6, m7));
1131}
1132
1133template <typename M1, typename M2, typename M3, typename M4, typename M5,
1134    typename M6, typename M7, typename M8>
1135inline typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type
1136AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) {
1137  return typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type(
1138      ::testing::AnyOf(m1, m2, m3, m4),
1139      ::testing::AnyOf(m5, m6, m7, m8));
1140}
1141
1142template <typename M1, typename M2, typename M3, typename M4, typename M5,
1143    typename M6, typename M7, typename M8, typename M9>
1144inline typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type
1145AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) {
1146  return typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8,
1147      M9>::type(
1148      ::testing::AnyOf(m1, m2, m3, m4),
1149      ::testing::AnyOf(m5, m6, m7, m8, m9));
1150}
1151
1152template <typename M1, typename M2, typename M3, typename M4, typename M5,
1153    typename M6, typename M7, typename M8, typename M9, typename M10>
1154inline typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
1155    M10>::type
1156AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) {
1157  return typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
1158      M10>::type(
1159      ::testing::AnyOf(m1, m2, m3, m4, m5),
1160      ::testing::AnyOf(m6, m7, m8, m9, m10));
1161}
1162
1163}  // namespace testing
1164
1165
1166// The MATCHER* family of macros can be used in a namespace scope to
1167// define custom matchers easily.
1168//
1169// Basic Usage
1170// ===========
1171//
1172// The syntax
1173//
1174//   MATCHER(name, description_string) { statements; }
1175//
1176// defines a matcher with the given name that executes the statements,
1177// which must return a bool to indicate if the match succeeds.  Inside
1178// the statements, you can refer to the value being matched by 'arg',
1179// and refer to its type by 'arg_type'.
1180//
1181// The description string documents what the matcher does, and is used
1182// to generate the failure message when the match fails.  Since a
1183// MATCHER() is usually defined in a header file shared by multiple
1184// C++ source files, we require the description to be a C-string
1185// literal to avoid possible side effects.  It can be empty, in which
1186// case we'll use the sequence of words in the matcher name as the
1187// description.
1188//
1189// For example:
1190//
1191//   MATCHER(IsEven, "") { return (arg % 2) == 0; }
1192//
1193// allows you to write
1194//
1195//   // Expects mock_foo.Bar(n) to be called where n is even.
1196//   EXPECT_CALL(mock_foo, Bar(IsEven()));
1197//
1198// or,
1199//
1200//   // Verifies that the value of some_expression is even.
1201//   EXPECT_THAT(some_expression, IsEven());
1202//
1203// If the above assertion fails, it will print something like:
1204//
1205//   Value of: some_expression
1206//   Expected: is even
1207//     Actual: 7
1208//
1209// where the description "is even" is automatically calculated from the
1210// matcher name IsEven.
1211//
1212// Argument Type
1213// =============
1214//
1215// Note that the type of the value being matched (arg_type) is
1216// determined by the context in which you use the matcher and is
1217// supplied to you by the compiler, so you don't need to worry about
1218// declaring it (nor can you).  This allows the matcher to be
1219// polymorphic.  For example, IsEven() can be used to match any type
1220// where the value of "(arg % 2) == 0" can be implicitly converted to
1221// a bool.  In the "Bar(IsEven())" example above, if method Bar()
1222// takes an int, 'arg_type' will be int; if it takes an unsigned long,
1223// 'arg_type' will be unsigned long; and so on.
1224//
1225// Parameterizing Matchers
1226// =======================
1227//
1228// Sometimes you'll want to parameterize the matcher.  For that you
1229// can use another macro:
1230//
1231//   MATCHER_P(name, param_name, description_string) { statements; }
1232//
1233// For example:
1234//
1235//   MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
1236//
1237// will allow you to write:
1238//
1239//   EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
1240//
1241// which may lead to this message (assuming n is 10):
1242//
1243//   Value of: Blah("a")
1244//   Expected: has absolute value 10
1245//     Actual: -9
1246//
1247// Note that both the matcher description and its parameter are
1248// printed, making the message human-friendly.
1249//
1250// In the matcher definition body, you can write 'foo_type' to
1251// reference the type of a parameter named 'foo'.  For example, in the
1252// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
1253// 'value_type' to refer to the type of 'value'.
1254//
1255// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to
1256// support multi-parameter matchers.
1257//
1258// Describing Parameterized Matchers
1259// =================================
1260//
1261// The last argument to MATCHER*() is a string-typed expression.  The
1262// expression can reference all of the matcher's parameters and a
1263// special bool-typed variable named 'negation'.  When 'negation' is
1264// false, the expression should evaluate to the matcher's description;
1265// otherwise it should evaluate to the description of the negation of
1266// the matcher.  For example,
1267//
1268//   using testing::PrintToString;
1269//
1270//   MATCHER_P2(InClosedRange, low, hi,
1271//       string(negation ? "is not" : "is") + " in range [" +
1272//       PrintToString(low) + ", " + PrintToString(hi) + "]") {
1273//     return low <= arg && arg <= hi;
1274//   }
1275//   ...
1276//   EXPECT_THAT(3, InClosedRange(4, 6));
1277//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
1278//
1279// would generate two failures that contain the text:
1280//
1281//   Expected: is in range [4, 6]
1282//   ...
1283//   Expected: is not in range [2, 4]
1284//
1285// If you specify "" as the description, the failure message will
1286// contain the sequence of words in the matcher name followed by the
1287// parameter values printed as a tuple.  For example,
1288//
1289//   MATCHER_P2(InClosedRange, low, hi, "") { ... }
1290//   ...
1291//   EXPECT_THAT(3, InClosedRange(4, 6));
1292//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
1293//
1294// would generate two failures that contain the text:
1295//
1296//   Expected: in closed range (4, 6)
1297//   ...
1298//   Expected: not (in closed range (2, 4))
1299//
1300// Types of Matcher Parameters
1301// ===========================
1302//
1303// For the purpose of typing, you can view
1304//
1305//   MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
1306//
1307// as shorthand for
1308//
1309//   template <typename p1_type, ..., typename pk_type>
1310//   FooMatcherPk<p1_type, ..., pk_type>
1311//   Foo(p1_type p1, ..., pk_type pk) { ... }
1312//
1313// When you write Foo(v1, ..., vk), the compiler infers the types of
1314// the parameters v1, ..., and vk for you.  If you are not happy with
1315// the result of the type inference, you can specify the types by
1316// explicitly instantiating the template, as in Foo<long, bool>(5,
1317// false).  As said earlier, you don't get to (or need to) specify
1318// 'arg_type' as that's determined by the context in which the matcher
1319// is used.  You can assign the result of expression Foo(p1, ..., pk)
1320// to a variable of type FooMatcherPk<p1_type, ..., pk_type>.  This
1321// can be useful when composing matchers.
1322//
1323// While you can instantiate a matcher template with reference types,
1324// passing the parameters by pointer usually makes your code more
1325// readable.  If, however, you still want to pass a parameter by
1326// reference, be aware that in the failure message generated by the
1327// matcher you will see the value of the referenced object but not its
1328// address.
1329//
1330// Explaining Match Results
1331// ========================
1332//
1333// Sometimes the matcher description alone isn't enough to explain why
1334// the match has failed or succeeded.  For example, when expecting a
1335// long string, it can be very helpful to also print the diff between
1336// the expected string and the actual one.  To achieve that, you can
1337// optionally stream additional information to a special variable
1338// named result_listener, whose type is a pointer to class
1339// MatchResultListener:
1340//
1341//   MATCHER_P(EqualsLongString, str, "") {
1342//     if (arg == str) return true;
1343//
1344//     *result_listener << "the difference: "
1345///                     << DiffStrings(str, arg);
1346//     return false;
1347//   }
1348//
1349// Overloading Matchers
1350// ====================
1351//
1352// You can overload matchers with different numbers of parameters:
1353//
1354//   MATCHER_P(Blah, a, description_string1) { ... }
1355//   MATCHER_P2(Blah, a, b, description_string2) { ... }
1356//
1357// Caveats
1358// =======
1359//
1360// When defining a new matcher, you should also consider implementing
1361// MatcherInterface or using MakePolymorphicMatcher().  These
1362// approaches require more work than the MATCHER* macros, but also
1363// give you more control on the types of the value being matched and
1364// the matcher parameters, which may leads to better compiler error
1365// messages when the matcher is used wrong.  They also allow
1366// overloading matchers based on parameter types (as opposed to just
1367// based on the number of parameters).
1368//
1369// MATCHER*() can only be used in a namespace scope.  The reason is
1370// that C++ doesn't yet allow function-local types to be used to
1371// instantiate templates.  The up-coming C++0x standard will fix this.
1372// Once that's done, we'll consider supporting using MATCHER*() inside
1373// a function.
1374//
1375// More Information
1376// ================
1377//
1378// To learn more about using these macros, please search for 'MATCHER'
1379// on http://code.google.com/p/googlemock/wiki/CookBook.
1380
1381#define MATCHER(name, description)\
1382  class name##Matcher {\
1383   public:\
1384    template <typename arg_type>\
1385    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1386     public:\
1387      gmock_Impl()\
1388           {}\
1389      virtual bool MatchAndExplain(\
1390          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1391      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1392        *gmock_os << FormatDescription(false);\
1393      }\
1394      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1395        *gmock_os << FormatDescription(true);\
1396      }\
1397     private:\
1398      ::testing::internal::string FormatDescription(bool negation) const {\
1399        const ::testing::internal::string gmock_description = (description);\
1400        if (!gmock_description.empty())\
1401          return gmock_description;\
1402        return ::testing::internal::FormatMatcherDescription(\
1403            negation, #name, \
1404            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1405                ::testing::tuple<>()));\
1406      }\
1407      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1408    };\
1409    template <typename arg_type>\
1410    operator ::testing::Matcher<arg_type>() const {\
1411      return ::testing::Matcher<arg_type>(\
1412          new gmock_Impl<arg_type>());\
1413    }\
1414    name##Matcher() {\
1415    }\
1416   private:\
1417    GTEST_DISALLOW_ASSIGN_(name##Matcher);\
1418  };\
1419  inline name##Matcher name() {\
1420    return name##Matcher();\
1421  }\
1422  template <typename arg_type>\
1423  bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\
1424      arg_type arg, \
1425      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1426          const
1427
1428#define MATCHER_P(name, p0, description)\
1429  template <typename p0##_type>\
1430  class name##MatcherP {\
1431   public:\
1432    template <typename arg_type>\
1433    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1434     public:\
1435      explicit gmock_Impl(p0##_type gmock_p0)\
1436           : p0(gmock_p0) {}\
1437      virtual bool MatchAndExplain(\
1438          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1439      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1440        *gmock_os << FormatDescription(false);\
1441      }\
1442      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1443        *gmock_os << FormatDescription(true);\
1444      }\
1445      p0##_type p0;\
1446     private:\
1447      ::testing::internal::string FormatDescription(bool negation) const {\
1448        const ::testing::internal::string gmock_description = (description);\
1449        if (!gmock_description.empty())\
1450          return gmock_description;\
1451        return ::testing::internal::FormatMatcherDescription(\
1452            negation, #name, \
1453            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1454                ::testing::tuple<p0##_type>(p0)));\
1455      }\
1456      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1457    };\
1458    template <typename arg_type>\
1459    operator ::testing::Matcher<arg_type>() const {\
1460      return ::testing::Matcher<arg_type>(\
1461          new gmock_Impl<arg_type>(p0));\
1462    }\
1463    explicit name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {\
1464    }\
1465    p0##_type p0;\
1466   private:\
1467    GTEST_DISALLOW_ASSIGN_(name##MatcherP);\
1468  };\
1469  template <typename p0##_type>\
1470  inline name##MatcherP<p0##_type> name(p0##_type p0) {\
1471    return name##MatcherP<p0##_type>(p0);\
1472  }\
1473  template <typename p0##_type>\
1474  template <typename arg_type>\
1475  bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1476      arg_type arg, \
1477      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1478          const
1479
1480#define MATCHER_P2(name, p0, p1, description)\
1481  template <typename p0##_type, typename p1##_type>\
1482  class name##MatcherP2 {\
1483   public:\
1484    template <typename arg_type>\
1485    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1486     public:\
1487      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\
1488           : p0(gmock_p0), p1(gmock_p1) {}\
1489      virtual bool MatchAndExplain(\
1490          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1491      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1492        *gmock_os << FormatDescription(false);\
1493      }\
1494      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1495        *gmock_os << FormatDescription(true);\
1496      }\
1497      p0##_type p0;\
1498      p1##_type p1;\
1499     private:\
1500      ::testing::internal::string FormatDescription(bool negation) const {\
1501        const ::testing::internal::string gmock_description = (description);\
1502        if (!gmock_description.empty())\
1503          return gmock_description;\
1504        return ::testing::internal::FormatMatcherDescription(\
1505            negation, #name, \
1506            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1507                ::testing::tuple<p0##_type, p1##_type>(p0, p1)));\
1508      }\
1509      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1510    };\
1511    template <typename arg_type>\
1512    operator ::testing::Matcher<arg_type>() const {\
1513      return ::testing::Matcher<arg_type>(\
1514          new gmock_Impl<arg_type>(p0, p1));\
1515    }\
1516    name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
1517        p1(gmock_p1) {\
1518    }\
1519    p0##_type p0;\
1520    p1##_type p1;\
1521   private:\
1522    GTEST_DISALLOW_ASSIGN_(name##MatcherP2);\
1523  };\
1524  template <typename p0##_type, typename p1##_type>\
1525  inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \
1526      p1##_type p1) {\
1527    return name##MatcherP2<p0##_type, p1##_type>(p0, p1);\
1528  }\
1529  template <typename p0##_type, typename p1##_type>\
1530  template <typename arg_type>\
1531  bool name##MatcherP2<p0##_type, \
1532      p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1533      arg_type arg, \
1534      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1535          const
1536
1537#define MATCHER_P3(name, p0, p1, p2, description)\
1538  template <typename p0##_type, typename p1##_type, typename p2##_type>\
1539  class name##MatcherP3 {\
1540   public:\
1541    template <typename arg_type>\
1542    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1543     public:\
1544      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\
1545           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
1546      virtual bool MatchAndExplain(\
1547          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1548      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1549        *gmock_os << FormatDescription(false);\
1550      }\
1551      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1552        *gmock_os << FormatDescription(true);\
1553      }\
1554      p0##_type p0;\
1555      p1##_type p1;\
1556      p2##_type p2;\
1557     private:\
1558      ::testing::internal::string FormatDescription(bool negation) const {\
1559        const ::testing::internal::string gmock_description = (description);\
1560        if (!gmock_description.empty())\
1561          return gmock_description;\
1562        return ::testing::internal::FormatMatcherDescription(\
1563            negation, #name, \
1564            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1565                ::testing::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, \
1566                    p2)));\
1567      }\
1568      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1569    };\
1570    template <typename arg_type>\
1571    operator ::testing::Matcher<arg_type>() const {\
1572      return ::testing::Matcher<arg_type>(\
1573          new gmock_Impl<arg_type>(p0, p1, p2));\
1574    }\
1575    name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \
1576        p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {\
1577    }\
1578    p0##_type p0;\
1579    p1##_type p1;\
1580    p2##_type p2;\
1581   private:\
1582    GTEST_DISALLOW_ASSIGN_(name##MatcherP3);\
1583  };\
1584  template <typename p0##_type, typename p1##_type, typename p2##_type>\
1585  inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
1586      p1##_type p1, p2##_type p2) {\
1587    return name##MatcherP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
1588  }\
1589  template <typename p0##_type, typename p1##_type, typename p2##_type>\
1590  template <typename arg_type>\
1591  bool name##MatcherP3<p0##_type, p1##_type, \
1592      p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1593      arg_type arg, \
1594      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1595          const
1596
1597#define MATCHER_P4(name, p0, p1, p2, p3, description)\
1598  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1599      typename p3##_type>\
1600  class name##MatcherP4 {\
1601   public:\
1602    template <typename arg_type>\
1603    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1604     public:\
1605      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1606          p3##_type gmock_p3)\
1607           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {}\
1608      virtual bool MatchAndExplain(\
1609          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1610      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1611        *gmock_os << FormatDescription(false);\
1612      }\
1613      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1614        *gmock_os << FormatDescription(true);\
1615      }\
1616      p0##_type p0;\
1617      p1##_type p1;\
1618      p2##_type p2;\
1619      p3##_type p3;\
1620     private:\
1621      ::testing::internal::string FormatDescription(bool negation) const {\
1622        const ::testing::internal::string gmock_description = (description);\
1623        if (!gmock_description.empty())\
1624          return gmock_description;\
1625        return ::testing::internal::FormatMatcherDescription(\
1626            negation, #name, \
1627            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1628                ::testing::tuple<p0##_type, p1##_type, p2##_type, \
1629                    p3##_type>(p0, p1, p2, p3)));\
1630      }\
1631      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1632    };\
1633    template <typename arg_type>\
1634    operator ::testing::Matcher<arg_type>() const {\
1635      return ::testing::Matcher<arg_type>(\
1636          new gmock_Impl<arg_type>(p0, p1, p2, p3));\
1637    }\
1638    name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \
1639        p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \
1640        p2(gmock_p2), p3(gmock_p3) {\
1641    }\
1642    p0##_type p0;\
1643    p1##_type p1;\
1644    p2##_type p2;\
1645    p3##_type p3;\
1646   private:\
1647    GTEST_DISALLOW_ASSIGN_(name##MatcherP4);\
1648  };\
1649  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1650      typename p3##_type>\
1651  inline name##MatcherP4<p0##_type, p1##_type, p2##_type, \
1652      p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
1653      p3##_type p3) {\
1654    return name##MatcherP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \
1655        p1, p2, p3);\
1656  }\
1657  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1658      typename p3##_type>\
1659  template <typename arg_type>\
1660  bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \
1661      p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1662      arg_type arg, \
1663      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1664          const
1665
1666#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\
1667  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1668      typename p3##_type, typename p4##_type>\
1669  class name##MatcherP5 {\
1670   public:\
1671    template <typename arg_type>\
1672    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1673     public:\
1674      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1675          p3##_type gmock_p3, p4##_type gmock_p4)\
1676           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
1677               p4(gmock_p4) {}\
1678      virtual bool MatchAndExplain(\
1679          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1680      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1681        *gmock_os << FormatDescription(false);\
1682      }\
1683      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1684        *gmock_os << FormatDescription(true);\
1685      }\
1686      p0##_type p0;\
1687      p1##_type p1;\
1688      p2##_type p2;\
1689      p3##_type p3;\
1690      p4##_type p4;\
1691     private:\
1692      ::testing::internal::string FormatDescription(bool negation) const {\
1693        const ::testing::internal::string gmock_description = (description);\
1694        if (!gmock_description.empty())\
1695          return gmock_description;\
1696        return ::testing::internal::FormatMatcherDescription(\
1697            negation, #name, \
1698            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1699                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
1700                    p4##_type>(p0, p1, p2, p3, p4)));\
1701      }\
1702      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1703    };\
1704    template <typename arg_type>\
1705    operator ::testing::Matcher<arg_type>() const {\
1706      return ::testing::Matcher<arg_type>(\
1707          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4));\
1708    }\
1709    name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \
1710        p2##_type gmock_p2, p3##_type gmock_p3, \
1711        p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1712        p3(gmock_p3), p4(gmock_p4) {\
1713    }\
1714    p0##_type p0;\
1715    p1##_type p1;\
1716    p2##_type p2;\
1717    p3##_type p3;\
1718    p4##_type p4;\
1719   private:\
1720    GTEST_DISALLOW_ASSIGN_(name##MatcherP5);\
1721  };\
1722  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1723      typename p3##_type, typename p4##_type>\
1724  inline name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
1725      p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
1726      p4##_type p4) {\
1727    return name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
1728        p4##_type>(p0, p1, p2, p3, p4);\
1729  }\
1730  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1731      typename p3##_type, typename p4##_type>\
1732  template <typename arg_type>\
1733  bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
1734      p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1735      arg_type arg, \
1736      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1737          const
1738
1739#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\
1740  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1741      typename p3##_type, typename p4##_type, typename p5##_type>\
1742  class name##MatcherP6 {\
1743   public:\
1744    template <typename arg_type>\
1745    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1746     public:\
1747      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1748          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\
1749           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
1750               p4(gmock_p4), p5(gmock_p5) {}\
1751      virtual bool MatchAndExplain(\
1752          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1753      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1754        *gmock_os << FormatDescription(false);\
1755      }\
1756      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1757        *gmock_os << FormatDescription(true);\
1758      }\
1759      p0##_type p0;\
1760      p1##_type p1;\
1761      p2##_type p2;\
1762      p3##_type p3;\
1763      p4##_type p4;\
1764      p5##_type p5;\
1765     private:\
1766      ::testing::internal::string FormatDescription(bool negation) const {\
1767        const ::testing::internal::string gmock_description = (description);\
1768        if (!gmock_description.empty())\
1769          return gmock_description;\
1770        return ::testing::internal::FormatMatcherDescription(\
1771            negation, #name, \
1772            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1773                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
1774                    p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\
1775      }\
1776      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1777    };\
1778    template <typename arg_type>\
1779    operator ::testing::Matcher<arg_type>() const {\
1780      return ::testing::Matcher<arg_type>(\
1781          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5));\
1782    }\
1783    name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \
1784        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1785        p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1786        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {\
1787    }\
1788    p0##_type p0;\
1789    p1##_type p1;\
1790    p2##_type p2;\
1791    p3##_type p3;\
1792    p4##_type p4;\
1793    p5##_type p5;\
1794   private:\
1795    GTEST_DISALLOW_ASSIGN_(name##MatcherP6);\
1796  };\
1797  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1798      typename p3##_type, typename p4##_type, typename p5##_type>\
1799  inline name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
1800      p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
1801      p3##_type p3, p4##_type p4, p5##_type p5) {\
1802    return name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
1803        p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
1804  }\
1805  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1806      typename p3##_type, typename p4##_type, typename p5##_type>\
1807  template <typename arg_type>\
1808  bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1809      p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1810      arg_type arg, \
1811      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1812          const
1813
1814#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\
1815  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1816      typename p3##_type, typename p4##_type, typename p5##_type, \
1817      typename p6##_type>\
1818  class name##MatcherP7 {\
1819   public:\
1820    template <typename arg_type>\
1821    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1822     public:\
1823      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1824          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1825          p6##_type gmock_p6)\
1826           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
1827               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\
1828      virtual bool MatchAndExplain(\
1829          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1830      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1831        *gmock_os << FormatDescription(false);\
1832      }\
1833      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1834        *gmock_os << FormatDescription(true);\
1835      }\
1836      p0##_type p0;\
1837      p1##_type p1;\
1838      p2##_type p2;\
1839      p3##_type p3;\
1840      p4##_type p4;\
1841      p5##_type p5;\
1842      p6##_type p6;\
1843     private:\
1844      ::testing::internal::string FormatDescription(bool negation) const {\
1845        const ::testing::internal::string gmock_description = (description);\
1846        if (!gmock_description.empty())\
1847          return gmock_description;\
1848        return ::testing::internal::FormatMatcherDescription(\
1849            negation, #name, \
1850            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1851                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
1852                    p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \
1853                    p6)));\
1854      }\
1855      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1856    };\
1857    template <typename arg_type>\
1858    operator ::testing::Matcher<arg_type>() const {\
1859      return ::testing::Matcher<arg_type>(\
1860          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6));\
1861    }\
1862    name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \
1863        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1864        p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \
1865        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \
1866        p6(gmock_p6) {\
1867    }\
1868    p0##_type p0;\
1869    p1##_type p1;\
1870    p2##_type p2;\
1871    p3##_type p3;\
1872    p4##_type p4;\
1873    p5##_type p5;\
1874    p6##_type p6;\
1875   private:\
1876    GTEST_DISALLOW_ASSIGN_(name##MatcherP7);\
1877  };\
1878  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1879      typename p3##_type, typename p4##_type, typename p5##_type, \
1880      typename p6##_type>\
1881  inline name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
1882      p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
1883      p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
1884      p6##_type p6) {\
1885    return name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
1886        p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
1887  }\
1888  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1889      typename p3##_type, typename p4##_type, typename p5##_type, \
1890      typename p6##_type>\
1891  template <typename arg_type>\
1892  bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1893      p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1894      arg_type arg, \
1895      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1896          const
1897
1898#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\
1899  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1900      typename p3##_type, typename p4##_type, typename p5##_type, \
1901      typename p6##_type, typename p7##_type>\
1902  class name##MatcherP8 {\
1903   public:\
1904    template <typename arg_type>\
1905    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1906     public:\
1907      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1908          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1909          p6##_type gmock_p6, p7##_type gmock_p7)\
1910           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
1911               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\
1912      virtual bool MatchAndExplain(\
1913          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
1914      virtual void DescribeTo(::std::ostream* gmock_os) const {\
1915        *gmock_os << FormatDescription(false);\
1916      }\
1917      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
1918        *gmock_os << FormatDescription(true);\
1919      }\
1920      p0##_type p0;\
1921      p1##_type p1;\
1922      p2##_type p2;\
1923      p3##_type p3;\
1924      p4##_type p4;\
1925      p5##_type p5;\
1926      p6##_type p6;\
1927      p7##_type p7;\
1928     private:\
1929      ::testing::internal::string FormatDescription(bool negation) const {\
1930        const ::testing::internal::string gmock_description = (description);\
1931        if (!gmock_description.empty())\
1932          return gmock_description;\
1933        return ::testing::internal::FormatMatcherDescription(\
1934            negation, #name, \
1935            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
1936                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
1937                    p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \
1938                    p3, p4, p5, p6, p7)));\
1939      }\
1940      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
1941    };\
1942    template <typename arg_type>\
1943    operator ::testing::Matcher<arg_type>() const {\
1944      return ::testing::Matcher<arg_type>(\
1945          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7));\
1946    }\
1947    name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \
1948        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
1949        p5##_type gmock_p5, p6##_type gmock_p6, \
1950        p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
1951        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
1952        p7(gmock_p7) {\
1953    }\
1954    p0##_type p0;\
1955    p1##_type p1;\
1956    p2##_type p2;\
1957    p3##_type p3;\
1958    p4##_type p4;\
1959    p5##_type p5;\
1960    p6##_type p6;\
1961    p7##_type p7;\
1962   private:\
1963    GTEST_DISALLOW_ASSIGN_(name##MatcherP8);\
1964  };\
1965  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1966      typename p3##_type, typename p4##_type, typename p5##_type, \
1967      typename p6##_type, typename p7##_type>\
1968  inline name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
1969      p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
1970      p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
1971      p6##_type p6, p7##_type p7) {\
1972    return name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
1973        p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
1974        p6, p7);\
1975  }\
1976  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1977      typename p3##_type, typename p4##_type, typename p5##_type, \
1978      typename p6##_type, typename p7##_type>\
1979  template <typename arg_type>\
1980  bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
1981      p5##_type, p6##_type, \
1982      p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
1983      arg_type arg, \
1984      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
1985          const
1986
1987#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\
1988  template <typename p0##_type, typename p1##_type, typename p2##_type, \
1989      typename p3##_type, typename p4##_type, typename p5##_type, \
1990      typename p6##_type, typename p7##_type, typename p8##_type>\
1991  class name##MatcherP9 {\
1992   public:\
1993    template <typename arg_type>\
1994    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
1995     public:\
1996      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
1997          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
1998          p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\
1999           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
2000               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
2001               p8(gmock_p8) {}\
2002      virtual bool MatchAndExplain(\
2003          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
2004      virtual void DescribeTo(::std::ostream* gmock_os) const {\
2005        *gmock_os << FormatDescription(false);\
2006      }\
2007      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
2008        *gmock_os << FormatDescription(true);\
2009      }\
2010      p0##_type p0;\
2011      p1##_type p1;\
2012      p2##_type p2;\
2013      p3##_type p3;\
2014      p4##_type p4;\
2015      p5##_type p5;\
2016      p6##_type p6;\
2017      p7##_type p7;\
2018      p8##_type p8;\
2019     private:\
2020      ::testing::internal::string FormatDescription(bool negation) const {\
2021        const ::testing::internal::string gmock_description = (description);\
2022        if (!gmock_description.empty())\
2023          return gmock_description;\
2024        return ::testing::internal::FormatMatcherDescription(\
2025            negation, #name, \
2026            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
2027                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
2028                    p4##_type, p5##_type, p6##_type, p7##_type, \
2029                    p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\
2030      }\
2031      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
2032    };\
2033    template <typename arg_type>\
2034    operator ::testing::Matcher<arg_type>() const {\
2035      return ::testing::Matcher<arg_type>(\
2036          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8));\
2037    }\
2038    name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \
2039        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
2040        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
2041        p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
2042        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
2043        p8(gmock_p8) {\
2044    }\
2045    p0##_type p0;\
2046    p1##_type p1;\
2047    p2##_type p2;\
2048    p3##_type p3;\
2049    p4##_type p4;\
2050    p5##_type p5;\
2051    p6##_type p6;\
2052    p7##_type p7;\
2053    p8##_type p8;\
2054   private:\
2055    GTEST_DISALLOW_ASSIGN_(name##MatcherP9);\
2056  };\
2057  template <typename p0##_type, typename p1##_type, typename p2##_type, \
2058      typename p3##_type, typename p4##_type, typename p5##_type, \
2059      typename p6##_type, typename p7##_type, typename p8##_type>\
2060  inline name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
2061      p4##_type, p5##_type, p6##_type, p7##_type, \
2062      p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
2063      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \
2064      p8##_type p8) {\
2065    return name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
2066        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
2067        p3, p4, p5, p6, p7, p8);\
2068  }\
2069  template <typename p0##_type, typename p1##_type, typename p2##_type, \
2070      typename p3##_type, typename p4##_type, typename p5##_type, \
2071      typename p6##_type, typename p7##_type, typename p8##_type>\
2072  template <typename arg_type>\
2073  bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
2074      p5##_type, p6##_type, p7##_type, \
2075      p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
2076      arg_type arg, \
2077      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
2078          const
2079
2080#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\
2081  template <typename p0##_type, typename p1##_type, typename p2##_type, \
2082      typename p3##_type, typename p4##_type, typename p5##_type, \
2083      typename p6##_type, typename p7##_type, typename p8##_type, \
2084      typename p9##_type>\
2085  class name##MatcherP10 {\
2086   public:\
2087    template <typename arg_type>\
2088    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
2089     public:\
2090      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
2091          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
2092          p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
2093          p9##_type gmock_p9)\
2094           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
2095               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
2096               p8(gmock_p8), p9(gmock_p9) {}\
2097      virtual bool MatchAndExplain(\
2098          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
2099      virtual void DescribeTo(::std::ostream* gmock_os) const {\
2100        *gmock_os << FormatDescription(false);\
2101      }\
2102      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
2103        *gmock_os << FormatDescription(true);\
2104      }\
2105      p0##_type p0;\
2106      p1##_type p1;\
2107      p2##_type p2;\
2108      p3##_type p3;\
2109      p4##_type p4;\
2110      p5##_type p5;\
2111      p6##_type p6;\
2112      p7##_type p7;\
2113      p8##_type p8;\
2114      p9##_type p9;\
2115     private:\
2116      ::testing::internal::string FormatDescription(bool negation) const {\
2117        const ::testing::internal::string gmock_description = (description);\
2118        if (!gmock_description.empty())\
2119          return gmock_description;\
2120        return ::testing::internal::FormatMatcherDescription(\
2121            negation, #name, \
2122            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
2123                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
2124                    p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
2125                    p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\
2126      }\
2127      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
2128    };\
2129    template <typename arg_type>\
2130    operator ::testing::Matcher<arg_type>() const {\
2131      return ::testing::Matcher<arg_type>(\
2132          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\
2133    }\
2134    name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \
2135        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
2136        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
2137        p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \
2138        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
2139        p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {\
2140    }\
2141    p0##_type p0;\
2142    p1##_type p1;\
2143    p2##_type p2;\
2144    p3##_type p3;\
2145    p4##_type p4;\
2146    p5##_type p5;\
2147    p6##_type p6;\
2148    p7##_type p7;\
2149    p8##_type p8;\
2150    p9##_type p9;\
2151   private:\
2152    GTEST_DISALLOW_ASSIGN_(name##MatcherP10);\
2153  };\
2154  template <typename p0##_type, typename p1##_type, typename p2##_type, \
2155      typename p3##_type, typename p4##_type, typename p5##_type, \
2156      typename p6##_type, typename p7##_type, typename p8##_type, \
2157      typename p9##_type>\
2158  inline name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
2159      p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
2160      p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
2161      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
2162      p9##_type p9) {\
2163    return name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
2164        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
2165        p1, p2, p3, p4, p5, p6, p7, p8, p9);\
2166  }\
2167  template <typename p0##_type, typename p1##_type, typename p2##_type, \
2168      typename p3##_type, typename p4##_type, typename p5##_type, \
2169      typename p6##_type, typename p7##_type, typename p8##_type, \
2170      typename p9##_type>\
2171  template <typename arg_type>\
2172  bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
2173      p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
2174      p9##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
2175      arg_type arg, \
2176      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
2177          const
2178
2179#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-matchers.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$$ This is a Pump source file.  Please use Pump to convert it to
3$$ gmock-generated-actions.h.
4$$
5$var n = 10  $$ The maximum arity we support.
6$$ }} This line fixes auto-indentation of the following code in Emacs.
7// Copyright 2008, Google Inc.
8// All rights reserved.
9//
10// Redistribution and use in source and binary forms, with or without
11// modification, are permitted provided that the following conditions are
12// met:
13//
14//     * Redistributions of source code must retain the above copyright
15// notice, this list of conditions and the following disclaimer.
16//     * Redistributions in binary form must reproduce the above
17// copyright notice, this list of conditions and the following disclaimer
18// in the documentation and/or other materials provided with the
19// distribution.
20//     * Neither the name of Google Inc. nor the names of its
21// contributors may be used to endorse or promote products derived from
22// this software without specific prior written permission.
23//
24// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
36// Google Mock - a framework for writing C++ mock classes.
37//
38// This file implements some commonly used variadic matchers.
39
40#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
41#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
42
43#include <iterator>
44#include <sstream>
45#include <string>
46#include <vector>
47#include "gmock/gmock-matchers.h"
48
49namespace testing {
50namespace internal {
51
52$range i 0..n-1
53
54// The type of the i-th (0-based) field of Tuple.
55#define GMOCK_FIELD_TYPE_(Tuple, i) \
56    typename ::testing::tuple_element<i, Tuple>::type
57
58// TupleFields<Tuple, k0, ..., kn> is for selecting fields from a
59// tuple of type Tuple.  It has two members:
60//
61//   type: a tuple type whose i-th field is the ki-th field of Tuple.
62//   GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple.
63//
64// For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have:
65//
66//   type is tuple<int, bool>, and
67//   GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true).
68
69template <class Tuple$for i [[, int k$i = -1]]>
70class TupleFields;
71
72// This generic version is used when there are $n selectors.
73template <class Tuple$for i [[, int k$i]]>
74class TupleFields {
75 public:
76  typedef ::testing::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type;
77  static type GetSelectedFields(const Tuple& t) {
78    return type($for i, [[get<k$i>(t)]]);
79  }
80};
81
82// The following specialization is used for 0 ~ $(n-1) selectors.
83
84$for i [[
85$$ }}}
86$range j 0..i-1
87$range k 0..n-1
88
89template <class Tuple$for j [[, int k$j]]>
90class TupleFields<Tuple, $for k, [[$if k < i [[k$k]] $else [[-1]]]]> {
91 public:
92  typedef ::testing::tuple<$for j, [[GMOCK_FIELD_TYPE_(Tuple, k$j)]]> type;
93  static type GetSelectedFields(const Tuple& $if i==0 [[/* t */]] $else [[t]]) {
94    return type($for j, [[get<k$j>(t)]]);
95  }
96};
97
98]]
99
100#undef GMOCK_FIELD_TYPE_
101
102// Implements the Args() matcher.
103
104$var ks = [[$for i, [[k$i]]]]
105template <class ArgsTuple$for i [[, int k$i = -1]]>
106class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
107 public:
108  // ArgsTuple may have top-level const or reference modifiers.
109  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple;
110  typedef typename internal::TupleFields<RawArgsTuple, $ks>::type SelectedArgs;
111  typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher;
112
113  template <typename InnerMatcher>
114  explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
115      : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
116
117  virtual bool MatchAndExplain(ArgsTuple args,
118                               MatchResultListener* listener) const {
119    const SelectedArgs& selected_args = GetSelectedArgs(args);
120    if (!listener->IsInterested())
121      return inner_matcher_.Matches(selected_args);
122
123    PrintIndices(listener->stream());
124    *listener << "are " << PrintToString(selected_args);
125
126    StringMatchResultListener inner_listener;
127    const bool match = inner_matcher_.MatchAndExplain(selected_args,
128                                                      &inner_listener);
129    PrintIfNotEmpty(inner_listener.str(), listener->stream());
130    return match;
131  }
132
133  virtual void DescribeTo(::std::ostream* os) const {
134    *os << "are a tuple ";
135    PrintIndices(os);
136    inner_matcher_.DescribeTo(os);
137  }
138
139  virtual void DescribeNegationTo(::std::ostream* os) const {
140    *os << "are a tuple ";
141    PrintIndices(os);
142    inner_matcher_.DescribeNegationTo(os);
143  }
144
145 private:
146  static SelectedArgs GetSelectedArgs(ArgsTuple args) {
147    return TupleFields<RawArgsTuple, $ks>::GetSelectedFields(args);
148  }
149
150  // Prints the indices of the selected fields.
151  static void PrintIndices(::std::ostream* os) {
152    *os << "whose fields (";
153    const int indices[$n] = { $ks };
154    for (int i = 0; i < $n; i++) {
155      if (indices[i] < 0)
156        break;
157
158      if (i >= 1)
159        *os << ", ";
160
161      *os << "#" << indices[i];
162    }
163    *os << ") ";
164  }
165
166  const MonomorphicInnerMatcher inner_matcher_;
167
168  GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl);
169};
170
171template <class InnerMatcher$for i [[, int k$i = -1]]>
172class ArgsMatcher {
173 public:
174  explicit ArgsMatcher(const InnerMatcher& inner_matcher)
175      : inner_matcher_(inner_matcher) {}
176
177  template <typename ArgsTuple>
178  operator Matcher<ArgsTuple>() const {
179    return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, $ks>(inner_matcher_));
180  }
181
182 private:
183  const InnerMatcher inner_matcher_;
184
185  GTEST_DISALLOW_ASSIGN_(ArgsMatcher);
186};
187
188// A set of metafunctions for computing the result type of AllOf.
189// AllOf(m1, ..., mN) returns
190// AllOfResultN<decltype(m1), ..., decltype(mN)>::type.
191
192// Although AllOf isn't defined for one argument, AllOfResult1 is defined
193// to simplify the implementation.
194template <typename M1>
195struct AllOfResult1 {
196  typedef M1 type;
197};
198
199$range i 1..n
200
201$range i 2..n
202$for i [[
203$range j 2..i
204$var m = i/2
205$range k 1..m
206$range t m+1..i
207
208template <typename M1$for j [[, typename M$j]]>
209struct AllOfResult$i {
210  typedef BothOfMatcher<
211      typename AllOfResult$m<$for k, [[M$k]]>::type,
212      typename AllOfResult$(i-m)<$for t, [[M$t]]>::type
213  > type;
214};
215
216]]
217
218// A set of metafunctions for computing the result type of AnyOf.
219// AnyOf(m1, ..., mN) returns
220// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type.
221
222// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined
223// to simplify the implementation.
224template <typename M1>
225struct AnyOfResult1 {
226  typedef M1 type;
227};
228
229$range i 1..n
230
231$range i 2..n
232$for i [[
233$range j 2..i
234$var m = i/2
235$range k 1..m
236$range t m+1..i
237
238template <typename M1$for j [[, typename M$j]]>
239struct AnyOfResult$i {
240  typedef EitherOfMatcher<
241      typename AnyOfResult$m<$for k, [[M$k]]>::type,
242      typename AnyOfResult$(i-m)<$for t, [[M$t]]>::type
243  > type;
244};
245
246]]
247
248}  // namespace internal
249
250// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
251// fields of it matches a_matcher.  C++ doesn't support default
252// arguments for function templates, so we have to overload it.
253
254$range i 0..n
255$for i [[
256$range j 1..i
257template <$for j [[int k$j, ]]typename InnerMatcher>
258inline internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>
259Args(const InnerMatcher& matcher) {
260  return internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>(matcher);
261}
262
263
264]]
265// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with
266// n elements, where the i-th element in the container must
267// match the i-th argument in the list.  Each argument of
268// ElementsAre() can be either a value or a matcher.  We support up to
269// $n arguments.
270//
271// The use of DecayArray in the implementation allows ElementsAre()
272// to accept string literals, whose type is const char[N], but we
273// want to treat them as const char*.
274//
275// NOTE: Since ElementsAre() cares about the order of the elements, it
276// must not be used with containers whose elements's order is
277// undefined (e.g. hash_map).
278
279$range i 0..n
280$for i [[
281
282$range j 1..i
283
284$if i>0 [[
285
286template <$for j, [[typename T$j]]>
287]]
288
289inline internal::ElementsAreMatcher<
290    ::testing::tuple<
291$for j, [[
292
293        typename internal::DecayArray<T$j[[]]>::type]]> >
294ElementsAre($for j, [[const T$j& e$j]]) {
295  typedef ::testing::tuple<
296$for j, [[
297
298      typename internal::DecayArray<T$j[[]]>::type]]> Args;
299  return internal::ElementsAreMatcher<Args>(Args($for j, [[e$j]]));
300}
301
302]]
303
304// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension
305// that matches n elements in any order.  We support up to n=$n arguments.
306
307$range i 0..n
308$for i [[
309
310$range j 1..i
311
312$if i>0 [[
313
314template <$for j, [[typename T$j]]>
315]]
316
317inline internal::UnorderedElementsAreMatcher<
318    ::testing::tuple<
319$for j, [[
320
321        typename internal::DecayArray<T$j[[]]>::type]]> >
322UnorderedElementsAre($for j, [[const T$j& e$j]]) {
323  typedef ::testing::tuple<
324$for j, [[
325
326      typename internal::DecayArray<T$j[[]]>::type]]> Args;
327  return internal::UnorderedElementsAreMatcher<Args>(Args($for j, [[e$j]]));
328}
329
330]]
331
332// AllOf(m1, m2, ..., mk) matches any value that matches all of the given
333// sub-matchers.  AllOf is called fully qualified to prevent ADL from firing.
334
335$range i 2..n
336$for i [[
337$range j 1..i
338$var m = i/2
339$range k 1..m
340$range t m+1..i
341
342template <$for j, [[typename M$j]]>
343inline typename internal::AllOfResult$i<$for j, [[M$j]]>::type
344AllOf($for j, [[M$j m$j]]) {
345  return typename internal::AllOfResult$i<$for j, [[M$j]]>::type(
346      $if m == 1 [[m1]] $else [[::testing::AllOf($for k, [[m$k]])]],
347      $if m+1 == i [[m$i]] $else [[::testing::AllOf($for t, [[m$t]])]]);
348}
349
350]]
351
352// AnyOf(m1, m2, ..., mk) matches any value that matches any of the given
353// sub-matchers.  AnyOf is called fully qualified to prevent ADL from firing.
354
355$range i 2..n
356$for i [[
357$range j 1..i
358$var m = i/2
359$range k 1..m
360$range t m+1..i
361
362template <$for j, [[typename M$j]]>
363inline typename internal::AnyOfResult$i<$for j, [[M$j]]>::type
364AnyOf($for j, [[M$j m$j]]) {
365  return typename internal::AnyOfResult$i<$for j, [[M$j]]>::type(
366      $if m == 1 [[m1]] $else [[::testing::AnyOf($for k, [[m$k]])]],
367      $if m+1 == i [[m$i]] $else [[::testing::AnyOf($for t, [[m$t]])]]);
368}
369
370]]
371
372}  // namespace testing
373$$ } // This Pump meta comment fixes auto-indentation in Emacs. It will not
374$$   // show up in the generated code.
375
376
377// The MATCHER* family of macros can be used in a namespace scope to
378// define custom matchers easily.
379//
380// Basic Usage
381// ===========
382//
383// The syntax
384//
385//   MATCHER(name, description_string) { statements; }
386//
387// defines a matcher with the given name that executes the statements,
388// which must return a bool to indicate if the match succeeds.  Inside
389// the statements, you can refer to the value being matched by 'arg',
390// and refer to its type by 'arg_type'.
391//
392// The description string documents what the matcher does, and is used
393// to generate the failure message when the match fails.  Since a
394// MATCHER() is usually defined in a header file shared by multiple
395// C++ source files, we require the description to be a C-string
396// literal to avoid possible side effects.  It can be empty, in which
397// case we'll use the sequence of words in the matcher name as the
398// description.
399//
400// For example:
401//
402//   MATCHER(IsEven, "") { return (arg % 2) == 0; }
403//
404// allows you to write
405//
406//   // Expects mock_foo.Bar(n) to be called where n is even.
407//   EXPECT_CALL(mock_foo, Bar(IsEven()));
408//
409// or,
410//
411//   // Verifies that the value of some_expression is even.
412//   EXPECT_THAT(some_expression, IsEven());
413//
414// If the above assertion fails, it will print something like:
415//
416//   Value of: some_expression
417//   Expected: is even
418//     Actual: 7
419//
420// where the description "is even" is automatically calculated from the
421// matcher name IsEven.
422//
423// Argument Type
424// =============
425//
426// Note that the type of the value being matched (arg_type) is
427// determined by the context in which you use the matcher and is
428// supplied to you by the compiler, so you don't need to worry about
429// declaring it (nor can you).  This allows the matcher to be
430// polymorphic.  For example, IsEven() can be used to match any type
431// where the value of "(arg % 2) == 0" can be implicitly converted to
432// a bool.  In the "Bar(IsEven())" example above, if method Bar()
433// takes an int, 'arg_type' will be int; if it takes an unsigned long,
434// 'arg_type' will be unsigned long; and so on.
435//
436// Parameterizing Matchers
437// =======================
438//
439// Sometimes you'll want to parameterize the matcher.  For that you
440// can use another macro:
441//
442//   MATCHER_P(name, param_name, description_string) { statements; }
443//
444// For example:
445//
446//   MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
447//
448// will allow you to write:
449//
450//   EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
451//
452// which may lead to this message (assuming n is 10):
453//
454//   Value of: Blah("a")
455//   Expected: has absolute value 10
456//     Actual: -9
457//
458// Note that both the matcher description and its parameter are
459// printed, making the message human-friendly.
460//
461// In the matcher definition body, you can write 'foo_type' to
462// reference the type of a parameter named 'foo'.  For example, in the
463// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
464// 'value_type' to refer to the type of 'value'.
465//
466// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
467// support multi-parameter matchers.
468//
469// Describing Parameterized Matchers
470// =================================
471//
472// The last argument to MATCHER*() is a string-typed expression.  The
473// expression can reference all of the matcher's parameters and a
474// special bool-typed variable named 'negation'.  When 'negation' is
475// false, the expression should evaluate to the matcher's description;
476// otherwise it should evaluate to the description of the negation of
477// the matcher.  For example,
478//
479//   using testing::PrintToString;
480//
481//   MATCHER_P2(InClosedRange, low, hi,
482//       string(negation ? "is not" : "is") + " in range [" +
483//       PrintToString(low) + ", " + PrintToString(hi) + "]") {
484//     return low <= arg && arg <= hi;
485//   }
486//   ...
487//   EXPECT_THAT(3, InClosedRange(4, 6));
488//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
489//
490// would generate two failures that contain the text:
491//
492//   Expected: is in range [4, 6]
493//   ...
494//   Expected: is not in range [2, 4]
495//
496// If you specify "" as the description, the failure message will
497// contain the sequence of words in the matcher name followed by the
498// parameter values printed as a tuple.  For example,
499//
500//   MATCHER_P2(InClosedRange, low, hi, "") { ... }
501//   ...
502//   EXPECT_THAT(3, InClosedRange(4, 6));
503//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
504//
505// would generate two failures that contain the text:
506//
507//   Expected: in closed range (4, 6)
508//   ...
509//   Expected: not (in closed range (2, 4))
510//
511// Types of Matcher Parameters
512// ===========================
513//
514// For the purpose of typing, you can view
515//
516//   MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
517//
518// as shorthand for
519//
520//   template <typename p1_type, ..., typename pk_type>
521//   FooMatcherPk<p1_type, ..., pk_type>
522//   Foo(p1_type p1, ..., pk_type pk) { ... }
523//
524// When you write Foo(v1, ..., vk), the compiler infers the types of
525// the parameters v1, ..., and vk for you.  If you are not happy with
526// the result of the type inference, you can specify the types by
527// explicitly instantiating the template, as in Foo<long, bool>(5,
528// false).  As said earlier, you don't get to (or need to) specify
529// 'arg_type' as that's determined by the context in which the matcher
530// is used.  You can assign the result of expression Foo(p1, ..., pk)
531// to a variable of type FooMatcherPk<p1_type, ..., pk_type>.  This
532// can be useful when composing matchers.
533//
534// While you can instantiate a matcher template with reference types,
535// passing the parameters by pointer usually makes your code more
536// readable.  If, however, you still want to pass a parameter by
537// reference, be aware that in the failure message generated by the
538// matcher you will see the value of the referenced object but not its
539// address.
540//
541// Explaining Match Results
542// ========================
543//
544// Sometimes the matcher description alone isn't enough to explain why
545// the match has failed or succeeded.  For example, when expecting a
546// long string, it can be very helpful to also print the diff between
547// the expected string and the actual one.  To achieve that, you can
548// optionally stream additional information to a special variable
549// named result_listener, whose type is a pointer to class
550// MatchResultListener:
551//
552//   MATCHER_P(EqualsLongString, str, "") {
553//     if (arg == str) return true;
554//
555//     *result_listener << "the difference: "
556///                     << DiffStrings(str, arg);
557//     return false;
558//   }
559//
560// Overloading Matchers
561// ====================
562//
563// You can overload matchers with different numbers of parameters:
564//
565//   MATCHER_P(Blah, a, description_string1) { ... }
566//   MATCHER_P2(Blah, a, b, description_string2) { ... }
567//
568// Caveats
569// =======
570//
571// When defining a new matcher, you should also consider implementing
572// MatcherInterface or using MakePolymorphicMatcher().  These
573// approaches require more work than the MATCHER* macros, but also
574// give you more control on the types of the value being matched and
575// the matcher parameters, which may leads to better compiler error
576// messages when the matcher is used wrong.  They also allow
577// overloading matchers based on parameter types (as opposed to just
578// based on the number of parameters).
579//
580// MATCHER*() can only be used in a namespace scope.  The reason is
581// that C++ doesn't yet allow function-local types to be used to
582// instantiate templates.  The up-coming C++0x standard will fix this.
583// Once that's done, we'll consider supporting using MATCHER*() inside
584// a function.
585//
586// More Information
587// ================
588//
589// To learn more about using these macros, please search for 'MATCHER'
590// on http://code.google.com/p/googlemock/wiki/CookBook.
591
592$range i 0..n
593$for i
594
595[[
596$var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]]
597                                         $else [[MATCHER_P$i]]]]
598$var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]]
599                                                 $else [[P$i]]]]]]
600$range j 0..i-1
601$var template = [[$if i==0 [[]] $else [[
602
603  template <$for j, [[typename p$j##_type]]>\
604]]]]
605$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
606$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
607$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
608$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
609$var params = [[$for j, [[p$j]]]]
610$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
611$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
612$var param_field_decls = [[$for j
613[[
614
615      p$j##_type p$j;\
616]]]]
617$var param_field_decls2 = [[$for j
618[[
619
620    p$j##_type p$j;\
621]]]]
622
623#define $macro_name(name$for j [[, p$j]], description)\$template
624  class $class_name {\
625   public:\
626    template <typename arg_type>\
627    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
628     public:\
629      [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
630          $impl_inits {}\
631      virtual bool MatchAndExplain(\
632          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
633      virtual void DescribeTo(::std::ostream* gmock_os) const {\
634        *gmock_os << FormatDescription(false);\
635      }\
636      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
637        *gmock_os << FormatDescription(true);\
638      }\$param_field_decls
639     private:\
640      ::testing::internal::string FormatDescription(bool negation) const {\
641        const ::testing::internal::string gmock_description = (description);\
642        if (!gmock_description.empty())\
643          return gmock_description;\
644        return ::testing::internal::FormatMatcherDescription(\
645            negation, #name, \
646            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
647                ::testing::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
648      }\
649      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
650    };\
651    template <typename arg_type>\
652    operator ::testing::Matcher<arg_type>() const {\
653      return ::testing::Matcher<arg_type>(\
654          new gmock_Impl<arg_type>($params));\
655    }\
656    [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
657    }\$param_field_decls2
658   private:\
659    GTEST_DISALLOW_ASSIGN_($class_name);\
660  };\$template
661  inline $class_name$param_types name($param_types_and_names) {\
662    return $class_name$param_types($params);\
663  }\$template
664  template <typename arg_type>\
665  bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
666      arg_type arg, \
667      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
668          const
669]]
670
671
672#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-nice-strict.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gmock-generated-nice-strict.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2008, Google Inc.
6// All rights reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33//
34// Author: wan@google.com (Zhanyong Wan)
35
36// Implements class templates NiceMock, NaggyMock, and StrictMock.
37//
38// Given a mock class MockFoo that is created using Google Mock,
39// NiceMock<MockFoo> is a subclass of MockFoo that allows
40// uninteresting calls (i.e. calls to mock methods that have no
41// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
42// that prints a warning when an uninteresting call occurs, and
43// StrictMock<MockFoo> is a subclass of MockFoo that treats all
44// uninteresting calls as errors.
45//
46// Currently a mock is naggy by default, so MockFoo and
47// NaggyMock<MockFoo> behave like the same.  However, we will soon
48// switch the default behavior of mocks to be nice, as that in general
49// leads to more maintainable tests.  When that happens, MockFoo will
50// stop behaving like NaggyMock<MockFoo> and start behaving like
51// NiceMock<MockFoo>.
52//
53// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
54// their respective base class, with up-to 10 arguments.  Therefore
55// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock
56// where MockFoo has a constructor that accepts (int, const char*),
57// for example.
58//
59// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
60// and StrictMock<MockFoo> only works for mock methods defined using
61// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
62// If a mock method is defined in a base class of MockFoo, the "nice"
63// or "strict" modifier may not affect it, depending on the compiler.
64// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
65// supported.
66//
67// Another known limitation is that the constructors of the base mock
68// cannot have arguments passed by non-const reference, which are
69// banned by the Google C++ style guide anyway.
70
71#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
72#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
73
74#include "gmock/gmock-spec-builders.h"
75#include "gmock/internal/gmock-port.h"
76
77namespace testing {
78
79template <class MockClass>
80class NiceMock : public MockClass {
81 public:
82  // We don't factor out the constructor body to a common method, as
83  // we have to avoid a possible clash with members of MockClass.
84  NiceMock() {
85    ::testing::Mock::AllowUninterestingCalls(
86        internal::ImplicitCast_<MockClass*>(this));
87  }
88
89  // C++ doesn't (yet) allow inheritance of constructors, so we have
90  // to define it for each arity.
91  template <typename A1>
92  explicit NiceMock(const A1& a1) : MockClass(a1) {
93    ::testing::Mock::AllowUninterestingCalls(
94        internal::ImplicitCast_<MockClass*>(this));
95  }
96  template <typename A1, typename A2>
97  NiceMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
98    ::testing::Mock::AllowUninterestingCalls(
99        internal::ImplicitCast_<MockClass*>(this));
100  }
101
102  template <typename A1, typename A2, typename A3>
103  NiceMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
104    ::testing::Mock::AllowUninterestingCalls(
105        internal::ImplicitCast_<MockClass*>(this));
106  }
107
108  template <typename A1, typename A2, typename A3, typename A4>
109  NiceMock(const A1& a1, const A2& a2, const A3& a3,
110      const A4& a4) : MockClass(a1, a2, a3, a4) {
111    ::testing::Mock::AllowUninterestingCalls(
112        internal::ImplicitCast_<MockClass*>(this));
113  }
114
115  template <typename A1, typename A2, typename A3, typename A4, typename A5>
116  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
117      const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
118    ::testing::Mock::AllowUninterestingCalls(
119        internal::ImplicitCast_<MockClass*>(this));
120  }
121
122  template <typename A1, typename A2, typename A3, typename A4, typename A5,
123      typename A6>
124  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
125      const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
126    ::testing::Mock::AllowUninterestingCalls(
127        internal::ImplicitCast_<MockClass*>(this));
128  }
129
130  template <typename A1, typename A2, typename A3, typename A4, typename A5,
131      typename A6, typename A7>
132  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
133      const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
134      a6, a7) {
135    ::testing::Mock::AllowUninterestingCalls(
136        internal::ImplicitCast_<MockClass*>(this));
137  }
138
139  template <typename A1, typename A2, typename A3, typename A4, typename A5,
140      typename A6, typename A7, typename A8>
141  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
142      const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
143      a2, a3, a4, a5, a6, a7, a8) {
144    ::testing::Mock::AllowUninterestingCalls(
145        internal::ImplicitCast_<MockClass*>(this));
146  }
147
148  template <typename A1, typename A2, typename A3, typename A4, typename A5,
149      typename A6, typename A7, typename A8, typename A9>
150  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
151      const A5& a5, const A6& a6, const A7& a7, const A8& a8,
152      const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
153    ::testing::Mock::AllowUninterestingCalls(
154        internal::ImplicitCast_<MockClass*>(this));
155  }
156
157  template <typename A1, typename A2, typename A3, typename A4, typename A5,
158      typename A6, typename A7, typename A8, typename A9, typename A10>
159  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
160      const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
161      const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
162    ::testing::Mock::AllowUninterestingCalls(
163        internal::ImplicitCast_<MockClass*>(this));
164  }
165
166  virtual ~NiceMock() {
167    ::testing::Mock::UnregisterCallReaction(
168        internal::ImplicitCast_<MockClass*>(this));
169  }
170
171 private:
172  GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
173};
174
175template <class MockClass>
176class NaggyMock : public MockClass {
177 public:
178  // We don't factor out the constructor body to a common method, as
179  // we have to avoid a possible clash with members of MockClass.
180  NaggyMock() {
181    ::testing::Mock::WarnUninterestingCalls(
182        internal::ImplicitCast_<MockClass*>(this));
183  }
184
185  // C++ doesn't (yet) allow inheritance of constructors, so we have
186  // to define it for each arity.
187  template <typename A1>
188  explicit NaggyMock(const A1& a1) : MockClass(a1) {
189    ::testing::Mock::WarnUninterestingCalls(
190        internal::ImplicitCast_<MockClass*>(this));
191  }
192  template <typename A1, typename A2>
193  NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
194    ::testing::Mock::WarnUninterestingCalls(
195        internal::ImplicitCast_<MockClass*>(this));
196  }
197
198  template <typename A1, typename A2, typename A3>
199  NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
200    ::testing::Mock::WarnUninterestingCalls(
201        internal::ImplicitCast_<MockClass*>(this));
202  }
203
204  template <typename A1, typename A2, typename A3, typename A4>
205  NaggyMock(const A1& a1, const A2& a2, const A3& a3,
206      const A4& a4) : MockClass(a1, a2, a3, a4) {
207    ::testing::Mock::WarnUninterestingCalls(
208        internal::ImplicitCast_<MockClass*>(this));
209  }
210
211  template <typename A1, typename A2, typename A3, typename A4, typename A5>
212  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
213      const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
214    ::testing::Mock::WarnUninterestingCalls(
215        internal::ImplicitCast_<MockClass*>(this));
216  }
217
218  template <typename A1, typename A2, typename A3, typename A4, typename A5,
219      typename A6>
220  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
221      const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
222    ::testing::Mock::WarnUninterestingCalls(
223        internal::ImplicitCast_<MockClass*>(this));
224  }
225
226  template <typename A1, typename A2, typename A3, typename A4, typename A5,
227      typename A6, typename A7>
228  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
229      const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
230      a6, a7) {
231    ::testing::Mock::WarnUninterestingCalls(
232        internal::ImplicitCast_<MockClass*>(this));
233  }
234
235  template <typename A1, typename A2, typename A3, typename A4, typename A5,
236      typename A6, typename A7, typename A8>
237  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
238      const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
239      a2, a3, a4, a5, a6, a7, a8) {
240    ::testing::Mock::WarnUninterestingCalls(
241        internal::ImplicitCast_<MockClass*>(this));
242  }
243
244  template <typename A1, typename A2, typename A3, typename A4, typename A5,
245      typename A6, typename A7, typename A8, typename A9>
246  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
247      const A5& a5, const A6& a6, const A7& a7, const A8& a8,
248      const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
249    ::testing::Mock::WarnUninterestingCalls(
250        internal::ImplicitCast_<MockClass*>(this));
251  }
252
253  template <typename A1, typename A2, typename A3, typename A4, typename A5,
254      typename A6, typename A7, typename A8, typename A9, typename A10>
255  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
256      const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
257      const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
258    ::testing::Mock::WarnUninterestingCalls(
259        internal::ImplicitCast_<MockClass*>(this));
260  }
261
262  virtual ~NaggyMock() {
263    ::testing::Mock::UnregisterCallReaction(
264        internal::ImplicitCast_<MockClass*>(this));
265  }
266
267 private:
268  GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
269};
270
271template <class MockClass>
272class StrictMock : public MockClass {
273 public:
274  // We don't factor out the constructor body to a common method, as
275  // we have to avoid a possible clash with members of MockClass.
276  StrictMock() {
277    ::testing::Mock::FailUninterestingCalls(
278        internal::ImplicitCast_<MockClass*>(this));
279  }
280
281  // C++ doesn't (yet) allow inheritance of constructors, so we have
282  // to define it for each arity.
283  template <typename A1>
284  explicit StrictMock(const A1& a1) : MockClass(a1) {
285    ::testing::Mock::FailUninterestingCalls(
286        internal::ImplicitCast_<MockClass*>(this));
287  }
288  template <typename A1, typename A2>
289  StrictMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
290    ::testing::Mock::FailUninterestingCalls(
291        internal::ImplicitCast_<MockClass*>(this));
292  }
293
294  template <typename A1, typename A2, typename A3>
295  StrictMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
296    ::testing::Mock::FailUninterestingCalls(
297        internal::ImplicitCast_<MockClass*>(this));
298  }
299
300  template <typename A1, typename A2, typename A3, typename A4>
301  StrictMock(const A1& a1, const A2& a2, const A3& a3,
302      const A4& a4) : MockClass(a1, a2, a3, a4) {
303    ::testing::Mock::FailUninterestingCalls(
304        internal::ImplicitCast_<MockClass*>(this));
305  }
306
307  template <typename A1, typename A2, typename A3, typename A4, typename A5>
308  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
309      const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
310    ::testing::Mock::FailUninterestingCalls(
311        internal::ImplicitCast_<MockClass*>(this));
312  }
313
314  template <typename A1, typename A2, typename A3, typename A4, typename A5,
315      typename A6>
316  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
317      const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
318    ::testing::Mock::FailUninterestingCalls(
319        internal::ImplicitCast_<MockClass*>(this));
320  }
321
322  template <typename A1, typename A2, typename A3, typename A4, typename A5,
323      typename A6, typename A7>
324  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
325      const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
326      a6, a7) {
327    ::testing::Mock::FailUninterestingCalls(
328        internal::ImplicitCast_<MockClass*>(this));
329  }
330
331  template <typename A1, typename A2, typename A3, typename A4, typename A5,
332      typename A6, typename A7, typename A8>
333  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
334      const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
335      a2, a3, a4, a5, a6, a7, a8) {
336    ::testing::Mock::FailUninterestingCalls(
337        internal::ImplicitCast_<MockClass*>(this));
338  }
339
340  template <typename A1, typename A2, typename A3, typename A4, typename A5,
341      typename A6, typename A7, typename A8, typename A9>
342  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
343      const A5& a5, const A6& a6, const A7& a7, const A8& a8,
344      const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
345    ::testing::Mock::FailUninterestingCalls(
346        internal::ImplicitCast_<MockClass*>(this));
347  }
348
349  template <typename A1, typename A2, typename A3, typename A4, typename A5,
350      typename A6, typename A7, typename A8, typename A9, typename A10>
351  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
352      const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
353      const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
354    ::testing::Mock::FailUninterestingCalls(
355        internal::ImplicitCast_<MockClass*>(this));
356  }
357
358  virtual ~StrictMock() {
359    ::testing::Mock::UnregisterCallReaction(
360        internal::ImplicitCast_<MockClass*>(this));
361  }
362
363 private:
364  GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
365};
366
367// The following specializations catch some (relatively more common)
368// user errors of nesting nice and strict mocks.  They do NOT catch
369// all possible errors.
370
371// These specializations are declared but not defined, as NiceMock,
372// NaggyMock, and StrictMock cannot be nested.
373
374template <typename MockClass>
375class NiceMock<NiceMock<MockClass> >;
376template <typename MockClass>
377class NiceMock<NaggyMock<MockClass> >;
378template <typename MockClass>
379class NiceMock<StrictMock<MockClass> >;
380
381template <typename MockClass>
382class NaggyMock<NiceMock<MockClass> >;
383template <typename MockClass>
384class NaggyMock<NaggyMock<MockClass> >;
385template <typename MockClass>
386class NaggyMock<StrictMock<MockClass> >;
387
388template <typename MockClass>
389class StrictMock<NiceMock<MockClass> >;
390template <typename MockClass>
391class StrictMock<NaggyMock<MockClass> >;
392template <typename MockClass>
393class StrictMock<StrictMock<MockClass> >;
394
395}  // namespace testing
396
397#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-generated-nice-strict.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$$ This is a Pump source file.  Please use Pump to convert it to
3$$ gmock-generated-nice-strict.h.
4$$
5$var n = 10  $$ The maximum arity we support.
6// Copyright 2008, Google Inc.
7// All rights reserved.
8//
9// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions are
11// met:
12//
13//     * Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//     * Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following disclaimer
17// in the documentation and/or other materials provided with the
18// distribution.
19//     * Neither the name of Google Inc. nor the names of its
20// contributors may be used to endorse or promote products derived from
21// this software without specific prior written permission.
22//
23// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34//
35// Author: wan@google.com (Zhanyong Wan)
36
37// Implements class templates NiceMock, NaggyMock, and StrictMock.
38//
39// Given a mock class MockFoo that is created using Google Mock,
40// NiceMock<MockFoo> is a subclass of MockFoo that allows
41// uninteresting calls (i.e. calls to mock methods that have no
42// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
43// that prints a warning when an uninteresting call occurs, and
44// StrictMock<MockFoo> is a subclass of MockFoo that treats all
45// uninteresting calls as errors.
46//
47// Currently a mock is naggy by default, so MockFoo and
48// NaggyMock<MockFoo> behave like the same.  However, we will soon
49// switch the default behavior of mocks to be nice, as that in general
50// leads to more maintainable tests.  When that happens, MockFoo will
51// stop behaving like NaggyMock<MockFoo> and start behaving like
52// NiceMock<MockFoo>.
53//
54// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
55// their respective base class, with up-to $n arguments.  Therefore
56// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock
57// where MockFoo has a constructor that accepts (int, const char*),
58// for example.
59//
60// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
61// and StrictMock<MockFoo> only works for mock methods defined using
62// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
63// If a mock method is defined in a base class of MockFoo, the "nice"
64// or "strict" modifier may not affect it, depending on the compiler.
65// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
66// supported.
67//
68// Another known limitation is that the constructors of the base mock
69// cannot have arguments passed by non-const reference, which are
70// banned by the Google C++ style guide anyway.
71
72#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
73#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
74
75#include "gmock/gmock-spec-builders.h"
76#include "gmock/internal/gmock-port.h"
77
78namespace testing {
79
80$range kind 0..2
81$for kind [[
82
83$var clazz=[[$if kind==0 [[NiceMock]]
84             $elif kind==1 [[NaggyMock]]
85             $else [[StrictMock]]]]
86
87$var method=[[$if kind==0 [[AllowUninterestingCalls]]
88             $elif kind==1 [[WarnUninterestingCalls]]
89             $else [[FailUninterestingCalls]]]]
90
91template <class MockClass>
92class $clazz : public MockClass {
93 public:
94  // We don't factor out the constructor body to a common method, as
95  // we have to avoid a possible clash with members of MockClass.
96  $clazz() {
97    ::testing::Mock::$method(
98        internal::ImplicitCast_<MockClass*>(this));
99  }
100
101  // C++ doesn't (yet) allow inheritance of constructors, so we have
102  // to define it for each arity.
103  template <typename A1>
104  explicit $clazz(const A1& a1) : MockClass(a1) {
105    ::testing::Mock::$method(
106        internal::ImplicitCast_<MockClass*>(this));
107  }
108
109$range i 2..n
110$for i [[
111$range j 1..i
112  template <$for j, [[typename A$j]]>
113  $clazz($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) {
114    ::testing::Mock::$method(
115        internal::ImplicitCast_<MockClass*>(this));
116  }
117
118
119]]
120  virtual ~$clazz() {
121    ::testing::Mock::UnregisterCallReaction(
122        internal::ImplicitCast_<MockClass*>(this));
123  }
124
125 private:
126  GTEST_DISALLOW_COPY_AND_ASSIGN_($clazz);
127};
128
129]]
130
131// The following specializations catch some (relatively more common)
132// user errors of nesting nice and strict mocks.  They do NOT catch
133// all possible errors.
134
135// These specializations are declared but not defined, as NiceMock,
136// NaggyMock, and StrictMock cannot be nested.
137
138template <typename MockClass>
139class NiceMock<NiceMock<MockClass> >;
140template <typename MockClass>
141class NiceMock<NaggyMock<MockClass> >;
142template <typename MockClass>
143class NiceMock<StrictMock<MockClass> >;
144
145template <typename MockClass>
146class NaggyMock<NiceMock<MockClass> >;
147template <typename MockClass>
148class NaggyMock<NaggyMock<MockClass> >;
149template <typename MockClass>
150class NaggyMock<StrictMock<MockClass> >;
151
152template <typename MockClass>
153class StrictMock<NiceMock<MockClass> >;
154template <typename MockClass>
155class StrictMock<NaggyMock<MockClass> >;
156template <typename MockClass>
157class StrictMock<StrictMock<MockClass> >;
158
159}  // namespace testing
160
161#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-matchers.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers.  More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
41#include <math.h>
42#include <algorithm>
43#include <iterator>
44#include <limits>
45#include <ostream>  // NOLINT
46#include <sstream>
47#include <string>
48#include <utility>
49#include <vector>
50
51#include "gmock/internal/gmock-internal-utils.h"
52#include "gmock/internal/gmock-port.h"
53#include "gtest/gtest.h"
54
55#if GTEST_HAS_STD_INITIALIZER_LIST_
56# include <initializer_list>  // NOLINT -- must be after gtest.h
57#endif
58
59namespace testing {
60
61// To implement a matcher Foo for type T, define:
62//   1. a class FooMatcherImpl that implements the
63//      MatcherInterface<T> interface, and
64//   2. a factory function that creates a Matcher<T> object from a
65//      FooMatcherImpl*.
66//
67// The two-level delegation design makes it possible to allow a user
68// to write "v" instead of "Eq(v)" where a Matcher is expected, which
69// is impossible if we pass matchers by pointers.  It also eases
70// ownership management as Matcher objects can now be copied like
71// plain values.
72
73// MatchResultListener is an abstract class.  Its << operator can be
74// used by a matcher to explain why a value matches or doesn't match.
75//
76// TODO(wan@google.com): add method
77//   bool InterestedInWhy(bool result) const;
78// to indicate whether the listener is interested in why the match
79// result is 'result'.
80class MatchResultListener {
81 public:
82  // Creates a listener object with the given underlying ostream.  The
83  // listener does not own the ostream, and does not dereference it
84  // in the constructor or destructor.
85  explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
86  virtual ~MatchResultListener() = 0;  // Makes this class abstract.
87
88  // Streams x to the underlying ostream; does nothing if the ostream
89  // is NULL.
90  template <typename T>
91  MatchResultListener& operator<<(const T& x) {
92    if (stream_ != NULL)
93      *stream_ << x;
94    return *this;
95  }
96
97  // Returns the underlying ostream.
98  ::std::ostream* stream() { return stream_; }
99
100  // Returns true iff the listener is interested in an explanation of
101  // the match result.  A matcher's MatchAndExplain() method can use
102  // this information to avoid generating the explanation when no one
103  // intends to hear it.
104  bool IsInterested() const { return stream_ != NULL; }
105
106 private:
107  ::std::ostream* const stream_;
108
109  GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
110};
111
112inline MatchResultListener::~MatchResultListener() {
113}
114
115// An instance of a subclass of this knows how to describe itself as a
116// matcher.
117class MatcherDescriberInterface {
118 public:
119  virtual ~MatcherDescriberInterface() {}
120
121  // Describes this matcher to an ostream.  The function should print
122  // a verb phrase that describes the property a value matching this
123  // matcher should have.  The subject of the verb phrase is the value
124  // being matched.  For example, the DescribeTo() method of the Gt(7)
125  // matcher prints "is greater than 7".
126  virtual void DescribeTo(::std::ostream* os) const = 0;
127
128  // Describes the negation of this matcher to an ostream.  For
129  // example, if the description of this matcher is "is greater than
130  // 7", the negated description could be "is not greater than 7".
131  // You are not required to override this when implementing
132  // MatcherInterface, but it is highly advised so that your matcher
133  // can produce good error messages.
134  virtual void DescribeNegationTo(::std::ostream* os) const {
135    *os << "not (";
136    DescribeTo(os);
137    *os << ")";
138  }
139};
140
141// The implementation of a matcher.
142template <typename T>
143class MatcherInterface : public MatcherDescriberInterface {
144 public:
145  // Returns true iff the matcher matches x; also explains the match
146  // result to 'listener' if necessary (see the next paragraph), in
147  // the form of a non-restrictive relative clause ("which ...",
148  // "whose ...", etc) that describes x.  For example, the
149  // MatchAndExplain() method of the Pointee(...) matcher should
150  // generate an explanation like "which points to ...".
151  //
152  // Implementations of MatchAndExplain() should add an explanation of
153  // the match result *if and only if* they can provide additional
154  // information that's not already present (or not obvious) in the
155  // print-out of x and the matcher's description.  Whether the match
156  // succeeds is not a factor in deciding whether an explanation is
157  // needed, as sometimes the caller needs to print a failure message
158  // when the match succeeds (e.g. when the matcher is used inside
159  // Not()).
160  //
161  // For example, a "has at least 10 elements" matcher should explain
162  // what the actual element count is, regardless of the match result,
163  // as it is useful information to the reader; on the other hand, an
164  // "is empty" matcher probably only needs to explain what the actual
165  // size is when the match fails, as it's redundant to say that the
166  // size is 0 when the value is already known to be empty.
167  //
168  // You should override this method when defining a new matcher.
169  //
170  // It's the responsibility of the caller (Google Mock) to guarantee
171  // that 'listener' is not NULL.  This helps to simplify a matcher's
172  // implementation when it doesn't care about the performance, as it
173  // can talk to 'listener' without checking its validity first.
174  // However, in order to implement dummy listeners efficiently,
175  // listener->stream() may be NULL.
176  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
177
178  // Inherits these methods from MatcherDescriberInterface:
179  //   virtual void DescribeTo(::std::ostream* os) const = 0;
180  //   virtual void DescribeNegationTo(::std::ostream* os) const;
181};
182
183// A match result listener that stores the explanation in a string.
184class StringMatchResultListener : public MatchResultListener {
185 public:
186  StringMatchResultListener() : MatchResultListener(&ss_) {}
187
188  // Returns the explanation accumulated so far.
189  internal::string str() const { return ss_.str(); }
190
191  // Clears the explanation accumulated so far.
192  void Clear() { ss_.str(""); }
193
194 private:
195  ::std::stringstream ss_;
196
197  GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
198};
199
200namespace internal {
201
202struct AnyEq {
203  template <typename A, typename B>
204  bool operator()(const A& a, const B& b) const { return a == b; }
205};
206struct AnyNe {
207  template <typename A, typename B>
208  bool operator()(const A& a, const B& b) const { return a != b; }
209};
210struct AnyLt {
211  template <typename A, typename B>
212  bool operator()(const A& a, const B& b) const { return a < b; }
213};
214struct AnyGt {
215  template <typename A, typename B>
216  bool operator()(const A& a, const B& b) const { return a > b; }
217};
218struct AnyLe {
219  template <typename A, typename B>
220  bool operator()(const A& a, const B& b) const { return a <= b; }
221};
222struct AnyGe {
223  template <typename A, typename B>
224  bool operator()(const A& a, const B& b) const { return a >= b; }
225};
226
227// A match result listener that ignores the explanation.
228class DummyMatchResultListener : public MatchResultListener {
229 public:
230  DummyMatchResultListener() : MatchResultListener(NULL) {}
231
232 private:
233  GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
234};
235
236// A match result listener that forwards the explanation to a given
237// ostream.  The difference between this and MatchResultListener is
238// that the former is concrete.
239class StreamMatchResultListener : public MatchResultListener {
240 public:
241  explicit StreamMatchResultListener(::std::ostream* os)
242      : MatchResultListener(os) {}
243
244 private:
245  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
246};
247
248// An internal class for implementing Matcher<T>, which will derive
249// from it.  We put functionalities common to all Matcher<T>
250// specializations here to avoid code duplication.
251template <typename T>
252class MatcherBase {
253 public:
254  // Returns true iff the matcher matches x; also explains the match
255  // result to 'listener'.
256  bool MatchAndExplain(T x, MatchResultListener* listener) const {
257    return impl_->MatchAndExplain(x, listener);
258  }
259
260  // Returns true iff this matcher matches x.
261  bool Matches(T x) const {
262    DummyMatchResultListener dummy;
263    return MatchAndExplain(x, &dummy);
264  }
265
266  // Describes this matcher to an ostream.
267  void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
268
269  // Describes the negation of this matcher to an ostream.
270  void DescribeNegationTo(::std::ostream* os) const {
271    impl_->DescribeNegationTo(os);
272  }
273
274  // Explains why x matches, or doesn't match, the matcher.
275  void ExplainMatchResultTo(T x, ::std::ostream* os) const {
276    StreamMatchResultListener listener(os);
277    MatchAndExplain(x, &listener);
278  }
279
280  // Returns the describer for this matcher object; retains ownership
281  // of the describer, which is only guaranteed to be alive when
282  // this matcher object is alive.
283  const MatcherDescriberInterface* GetDescriber() const {
284    return impl_.get();
285  }
286
287 protected:
288  MatcherBase() {}
289
290  // Constructs a matcher from its implementation.
291  explicit MatcherBase(const MatcherInterface<T>* impl)
292      : impl_(impl) {}
293
294  virtual ~MatcherBase() {}
295
296 private:
297  // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
298  // interfaces.  The former dynamically allocates a chunk of memory
299  // to hold the reference count, while the latter tracks all
300  // references using a circular linked list without allocating
301  // memory.  It has been observed that linked_ptr performs better in
302  // typical scenarios.  However, shared_ptr can out-perform
303  // linked_ptr when there are many more uses of the copy constructor
304  // than the default constructor.
305  //
306  // If performance becomes a problem, we should see if using
307  // shared_ptr helps.
308  ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
309};
310
311}  // namespace internal
312
313// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
314// object that can check whether a value of type T matches.  The
315// implementation of Matcher<T> is just a linked_ptr to const
316// MatcherInterface<T>, so copying is fairly cheap.  Don't inherit
317// from Matcher!
318template <typename T>
319class Matcher : public internal::MatcherBase<T> {
320 public:
321  // Constructs a null matcher.  Needed for storing Matcher objects in STL
322  // containers.  A default-constructed matcher is not yet initialized.  You
323  // cannot use it until a valid value has been assigned to it.
324  explicit Matcher() {}  // NOLINT
325
326  // Constructs a matcher from its implementation.
327  explicit Matcher(const MatcherInterface<T>* impl)
328      : internal::MatcherBase<T>(impl) {}
329
330  // Implicit constructor here allows people to write
331  // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
332  Matcher(T value);  // NOLINT
333};
334
335// The following two specializations allow the user to write str
336// instead of Eq(str) and "foo" instead of Eq("foo") when a string
337// matcher is expected.
338template <>
339class GTEST_API_ Matcher<const internal::string&>
340    : public internal::MatcherBase<const internal::string&> {
341 public:
342  Matcher() {}
343
344  explicit Matcher(const MatcherInterface<const internal::string&>* impl)
345      : internal::MatcherBase<const internal::string&>(impl) {}
346
347  // Allows the user to write str instead of Eq(str) sometimes, where
348  // str is a string object.
349  Matcher(const internal::string& s);  // NOLINT
350
351  // Allows the user to write "foo" instead of Eq("foo") sometimes.
352  Matcher(const char* s);  // NOLINT
353};
354
355template <>
356class GTEST_API_ Matcher<internal::string>
357    : public internal::MatcherBase<internal::string> {
358 public:
359  Matcher() {}
360
361  explicit Matcher(const MatcherInterface<internal::string>* impl)
362      : internal::MatcherBase<internal::string>(impl) {}
363
364  // Allows the user to write str instead of Eq(str) sometimes, where
365  // str is a string object.
366  Matcher(const internal::string& s);  // NOLINT
367
368  // Allows the user to write "foo" instead of Eq("foo") sometimes.
369  Matcher(const char* s);  // NOLINT
370};
371
372#if GTEST_HAS_STRING_PIECE_
373// The following two specializations allow the user to write str
374// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
375// matcher is expected.
376template <>
377class GTEST_API_ Matcher<const StringPiece&>
378    : public internal::MatcherBase<const StringPiece&> {
379 public:
380  Matcher() {}
381
382  explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
383      : internal::MatcherBase<const StringPiece&>(impl) {}
384
385  // Allows the user to write str instead of Eq(str) sometimes, where
386  // str is a string object.
387  Matcher(const internal::string& s);  // NOLINT
388
389  // Allows the user to write "foo" instead of Eq("foo") sometimes.
390  Matcher(const char* s);  // NOLINT
391
392  // Allows the user to pass StringPieces directly.
393  Matcher(StringPiece s);  // NOLINT
394};
395
396template <>
397class GTEST_API_ Matcher<StringPiece>
398    : public internal::MatcherBase<StringPiece> {
399 public:
400  Matcher() {}
401
402  explicit Matcher(const MatcherInterface<StringPiece>* impl)
403      : internal::MatcherBase<StringPiece>(impl) {}
404
405  // Allows the user to write str instead of Eq(str) sometimes, where
406  // str is a string object.
407  Matcher(const internal::string& s);  // NOLINT
408
409  // Allows the user to write "foo" instead of Eq("foo") sometimes.
410  Matcher(const char* s);  // NOLINT
411
412  // Allows the user to pass StringPieces directly.
413  Matcher(StringPiece s);  // NOLINT
414};
415#endif  // GTEST_HAS_STRING_PIECE_
416
417// The PolymorphicMatcher class template makes it easy to implement a
418// polymorphic matcher (i.e. a matcher that can match values of more
419// than one type, e.g. Eq(n) and NotNull()).
420//
421// To define a polymorphic matcher, a user should provide an Impl
422// class that has a DescribeTo() method and a DescribeNegationTo()
423// method, and define a member function (or member function template)
424//
425//   bool MatchAndExplain(const Value& value,
426//                        MatchResultListener* listener) const;
427//
428// See the definition of NotNull() for a complete example.
429template <class Impl>
430class PolymorphicMatcher {
431 public:
432  explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
433
434  // Returns a mutable reference to the underlying matcher
435  // implementation object.
436  Impl& mutable_impl() { return impl_; }
437
438  // Returns an immutable reference to the underlying matcher
439  // implementation object.
440  const Impl& impl() const { return impl_; }
441
442  template <typename T>
443  operator Matcher<T>() const {
444    return Matcher<T>(new MonomorphicImpl<T>(impl_));
445  }
446
447 private:
448  template <typename T>
449  class MonomorphicImpl : public MatcherInterface<T> {
450   public:
451    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
452
453    virtual void DescribeTo(::std::ostream* os) const {
454      impl_.DescribeTo(os);
455    }
456
457    virtual void DescribeNegationTo(::std::ostream* os) const {
458      impl_.DescribeNegationTo(os);
459    }
460
461    virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
462      return impl_.MatchAndExplain(x, listener);
463    }
464
465   private:
466    const Impl impl_;
467
468    GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
469  };
470
471  Impl impl_;
472
473  GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
474};
475
476// Creates a matcher from its implementation.  This is easier to use
477// than the Matcher<T> constructor as it doesn't require you to
478// explicitly write the template argument, e.g.
479//
480//   MakeMatcher(foo);
481// vs
482//   Matcher<const string&>(foo);
483template <typename T>
484inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
485  return Matcher<T>(impl);
486}
487
488// Creates a polymorphic matcher from its implementation.  This is
489// easier to use than the PolymorphicMatcher<Impl> constructor as it
490// doesn't require you to explicitly write the template argument, e.g.
491//
492//   MakePolymorphicMatcher(foo);
493// vs
494//   PolymorphicMatcher<TypeOfFoo>(foo);
495template <class Impl>
496inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
497  return PolymorphicMatcher<Impl>(impl);
498}
499
500// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
501// and MUST NOT BE USED IN USER CODE!!!
502namespace internal {
503
504// The MatcherCastImpl class template is a helper for implementing
505// MatcherCast().  We need this helper in order to partially
506// specialize the implementation of MatcherCast() (C++ allows
507// class/struct templates to be partially specialized, but not
508// function templates.).
509
510// This general version is used when MatcherCast()'s argument is a
511// polymorphic matcher (i.e. something that can be converted to a
512// Matcher but is not one yet; for example, Eq(value)) or a value (for
513// example, "hello").
514template <typename T, typename M>
515class MatcherCastImpl {
516 public:
517  static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
518    // M can be a polymorhic matcher, in which case we want to use
519    // its conversion operator to create Matcher<T>.  Or it can be a value
520    // that should be passed to the Matcher<T>'s constructor.
521    //
522    // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
523    // polymorphic matcher because it'll be ambiguous if T has an implicit
524    // constructor from M (this usually happens when T has an implicit
525    // constructor from any type).
526    //
527    // It won't work to unconditionally implict_cast
528    // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
529    // a user-defined conversion from M to T if one exists (assuming M is
530    // a value).
531    return CastImpl(
532        polymorphic_matcher_or_value,
533        BooleanConstant<
534            internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
535  }
536
537 private:
538  static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
539    // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
540    // matcher.  It must be a value then.  Use direct initialization to create
541    // a matcher.
542    return Matcher<T>(ImplicitCast_<T>(value));
543  }
544
545  static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
546                             BooleanConstant<true>) {
547    // M is implicitly convertible to Matcher<T>, which means that either
548    // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
549    // from M.  In both cases using the implicit conversion will produce a
550    // matcher.
551    //
552    // Even if T has an implicit constructor from M, it won't be called because
553    // creating Matcher<T> would require a chain of two user-defined conversions
554    // (first to create T from M and then to create Matcher<T> from T).
555    return polymorphic_matcher_or_value;
556  }
557};
558
559// This more specialized version is used when MatcherCast()'s argument
560// is already a Matcher.  This only compiles when type T can be
561// statically converted to type U.
562template <typename T, typename U>
563class MatcherCastImpl<T, Matcher<U> > {
564 public:
565  static Matcher<T> Cast(const Matcher<U>& source_matcher) {
566    return Matcher<T>(new Impl(source_matcher));
567  }
568
569 private:
570  class Impl : public MatcherInterface<T> {
571   public:
572    explicit Impl(const Matcher<U>& source_matcher)
573        : source_matcher_(source_matcher) {}
574
575    // We delegate the matching logic to the source matcher.
576    virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
577      return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
578    }
579
580    virtual void DescribeTo(::std::ostream* os) const {
581      source_matcher_.DescribeTo(os);
582    }
583
584    virtual void DescribeNegationTo(::std::ostream* os) const {
585      source_matcher_.DescribeNegationTo(os);
586    }
587
588   private:
589    const Matcher<U> source_matcher_;
590
591    GTEST_DISALLOW_ASSIGN_(Impl);
592  };
593};
594
595// This even more specialized version is used for efficiently casting
596// a matcher to its own type.
597template <typename T>
598class MatcherCastImpl<T, Matcher<T> > {
599 public:
600  static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
601};
602
603}  // namespace internal
604
605// In order to be safe and clear, casting between different matcher
606// types is done explicitly via MatcherCast<T>(m), which takes a
607// matcher m and returns a Matcher<T>.  It compiles only when T can be
608// statically converted to the argument type of m.
609template <typename T, typename M>
610inline Matcher<T> MatcherCast(const M& matcher) {
611  return internal::MatcherCastImpl<T, M>::Cast(matcher);
612}
613
614// Implements SafeMatcherCast().
615//
616// We use an intermediate class to do the actual safe casting as Nokia's
617// Symbian compiler cannot decide between
618// template <T, M> ... (M) and
619// template <T, U> ... (const Matcher<U>&)
620// for function templates but can for member function templates.
621template <typename T>
622class SafeMatcherCastImpl {
623 public:
624  // This overload handles polymorphic matchers and values only since
625  // monomorphic matchers are handled by the next one.
626  template <typename M>
627  static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
628    return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
629  }
630
631  // This overload handles monomorphic matchers.
632  //
633  // In general, if type T can be implicitly converted to type U, we can
634  // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
635  // contravariant): just keep a copy of the original Matcher<U>, convert the
636  // argument from type T to U, and then pass it to the underlying Matcher<U>.
637  // The only exception is when U is a reference and T is not, as the
638  // underlying Matcher<U> may be interested in the argument's address, which
639  // is not preserved in the conversion from T to U.
640  template <typename U>
641  static inline Matcher<T> Cast(const Matcher<U>& matcher) {
642    // Enforce that T can be implicitly converted to U.
643    GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
644                          T_must_be_implicitly_convertible_to_U);
645    // Enforce that we are not converting a non-reference type T to a reference
646    // type U.
647    GTEST_COMPILE_ASSERT_(
648        internal::is_reference<T>::value || !internal::is_reference<U>::value,
649        cannot_convert_non_referentce_arg_to_reference);
650    // In case both T and U are arithmetic types, enforce that the
651    // conversion is not lossy.
652    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
653    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
654    const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
655    const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
656    GTEST_COMPILE_ASSERT_(
657        kTIsOther || kUIsOther ||
658        (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
659        conversion_of_arithmetic_types_must_be_lossless);
660    return MatcherCast<T>(matcher);
661  }
662};
663
664template <typename T, typename M>
665inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
666  return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
667}
668
669// A<T>() returns a matcher that matches any value of type T.
670template <typename T>
671Matcher<T> A();
672
673// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
674// and MUST NOT BE USED IN USER CODE!!!
675namespace internal {
676
677// If the explanation is not empty, prints it to the ostream.
678inline void PrintIfNotEmpty(const internal::string& explanation,
679                            ::std::ostream* os) {
680  if (explanation != "" && os != NULL) {
681    *os << ", " << explanation;
682  }
683}
684
685// Returns true if the given type name is easy to read by a human.
686// This is used to decide whether printing the type of a value might
687// be helpful.
688inline bool IsReadableTypeName(const string& type_name) {
689  // We consider a type name readable if it's short or doesn't contain
690  // a template or function type.
691  return (type_name.length() <= 20 ||
692          type_name.find_first_of("<(") == string::npos);
693}
694
695// Matches the value against the given matcher, prints the value and explains
696// the match result to the listener. Returns the match result.
697// 'listener' must not be NULL.
698// Value cannot be passed by const reference, because some matchers take a
699// non-const argument.
700template <typename Value, typename T>
701bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
702                          MatchResultListener* listener) {
703  if (!listener->IsInterested()) {
704    // If the listener is not interested, we do not need to construct the
705    // inner explanation.
706    return matcher.Matches(value);
707  }
708
709  StringMatchResultListener inner_listener;
710  const bool match = matcher.MatchAndExplain(value, &inner_listener);
711
712  UniversalPrint(value, listener->stream());
713#if GTEST_HAS_RTTI
714  const string& type_name = GetTypeName<Value>();
715  if (IsReadableTypeName(type_name))
716    *listener->stream() << " (of type " << type_name << ")";
717#endif
718  PrintIfNotEmpty(inner_listener.str(), listener->stream());
719
720  return match;
721}
722
723// An internal helper class for doing compile-time loop on a tuple's
724// fields.
725template <size_t N>
726class TuplePrefix {
727 public:
728  // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
729  // iff the first N fields of matcher_tuple matches the first N
730  // fields of value_tuple, respectively.
731  template <typename MatcherTuple, typename ValueTuple>
732  static bool Matches(const MatcherTuple& matcher_tuple,
733                      const ValueTuple& value_tuple) {
734    return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
735        && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
736  }
737
738  // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
739  // describes failures in matching the first N fields of matchers
740  // against the first N fields of values.  If there is no failure,
741  // nothing will be streamed to os.
742  template <typename MatcherTuple, typename ValueTuple>
743  static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
744                                     const ValueTuple& values,
745                                     ::std::ostream* os) {
746    // First, describes failures in the first N - 1 fields.
747    TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
748
749    // Then describes the failure (if any) in the (N - 1)-th (0-based)
750    // field.
751    typename tuple_element<N - 1, MatcherTuple>::type matcher =
752        get<N - 1>(matchers);
753    typedef typename tuple_element<N - 1, ValueTuple>::type Value;
754    Value value = get<N - 1>(values);
755    StringMatchResultListener listener;
756    if (!matcher.MatchAndExplain(value, &listener)) {
757      // TODO(wan): include in the message the name of the parameter
758      // as used in MOCK_METHOD*() when possible.
759      *os << "  Expected arg #" << N - 1 << ": ";
760      get<N - 1>(matchers).DescribeTo(os);
761      *os << "\n           Actual: ";
762      // We remove the reference in type Value to prevent the
763      // universal printer from printing the address of value, which
764      // isn't interesting to the user most of the time.  The
765      // matcher's MatchAndExplain() method handles the case when
766      // the address is interesting.
767      internal::UniversalPrint(value, os);
768      PrintIfNotEmpty(listener.str(), os);
769      *os << "\n";
770    }
771  }
772};
773
774// The base case.
775template <>
776class TuplePrefix<0> {
777 public:
778  template <typename MatcherTuple, typename ValueTuple>
779  static bool Matches(const MatcherTuple& /* matcher_tuple */,
780                      const ValueTuple& /* value_tuple */) {
781    return true;
782  }
783
784  template <typename MatcherTuple, typename ValueTuple>
785  static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
786                                     const ValueTuple& /* values */,
787                                     ::std::ostream* /* os */) {}
788};
789
790// TupleMatches(matcher_tuple, value_tuple) returns true iff all
791// matchers in matcher_tuple match the corresponding fields in
792// value_tuple.  It is a compiler error if matcher_tuple and
793// value_tuple have different number of fields or incompatible field
794// types.
795template <typename MatcherTuple, typename ValueTuple>
796bool TupleMatches(const MatcherTuple& matcher_tuple,
797                  const ValueTuple& value_tuple) {
798  // Makes sure that matcher_tuple and value_tuple have the same
799  // number of fields.
800  GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
801                        tuple_size<ValueTuple>::value,
802                        matcher_and_value_have_different_numbers_of_fields);
803  return TuplePrefix<tuple_size<ValueTuple>::value>::
804      Matches(matcher_tuple, value_tuple);
805}
806
807// Describes failures in matching matchers against values.  If there
808// is no failure, nothing will be streamed to os.
809template <typename MatcherTuple, typename ValueTuple>
810void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
811                                const ValueTuple& values,
812                                ::std::ostream* os) {
813  TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
814      matchers, values, os);
815}
816
817// TransformTupleValues and its helper.
818//
819// TransformTupleValuesHelper hides the internal machinery that
820// TransformTupleValues uses to implement a tuple traversal.
821template <typename Tuple, typename Func, typename OutIter>
822class TransformTupleValuesHelper {
823 private:
824  typedef ::testing::tuple_size<Tuple> TupleSize;
825
826 public:
827  // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
828  // Returns the final value of 'out' in case the caller needs it.
829  static OutIter Run(Func f, const Tuple& t, OutIter out) {
830    return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
831  }
832
833 private:
834  template <typename Tup, size_t kRemainingSize>
835  struct IterateOverTuple {
836    OutIter operator() (Func f, const Tup& t, OutIter out) const {
837      *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
838      return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
839    }
840  };
841  template <typename Tup>
842  struct IterateOverTuple<Tup, 0> {
843    OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
844      return out;
845    }
846  };
847};
848
849// Successively invokes 'f(element)' on each element of the tuple 't',
850// appending each result to the 'out' iterator. Returns the final value
851// of 'out'.
852template <typename Tuple, typename Func, typename OutIter>
853OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
854  return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
855}
856
857// Implements A<T>().
858template <typename T>
859class AnyMatcherImpl : public MatcherInterface<T> {
860 public:
861  virtual bool MatchAndExplain(
862      T /* x */, MatchResultListener* /* listener */) const { return true; }
863  virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
864  virtual void DescribeNegationTo(::std::ostream* os) const {
865    // This is mostly for completeness' safe, as it's not very useful
866    // to write Not(A<bool>()).  However we cannot completely rule out
867    // such a possibility, and it doesn't hurt to be prepared.
868    *os << "never matches";
869  }
870};
871
872// Implements _, a matcher that matches any value of any
873// type.  This is a polymorphic matcher, so we need a template type
874// conversion operator to make it appearing as a Matcher<T> for any
875// type T.
876class AnythingMatcher {
877 public:
878  template <typename T>
879  operator Matcher<T>() const { return A<T>(); }
880};
881
882// Implements a matcher that compares a given value with a
883// pre-supplied value using one of the ==, <=, <, etc, operators.  The
884// two values being compared don't have to have the same type.
885//
886// The matcher defined here is polymorphic (for example, Eq(5) can be
887// used to match an int, a short, a double, etc).  Therefore we use
888// a template type conversion operator in the implementation.
889//
890// The following template definition assumes that the Rhs parameter is
891// a "bare" type (i.e. neither 'const T' nor 'T&').
892template <typename D, typename Rhs, typename Op>
893class ComparisonBase {
894 public:
895  explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
896  template <typename Lhs>
897  operator Matcher<Lhs>() const {
898    return MakeMatcher(new Impl<Lhs>(rhs_));
899  }
900
901 private:
902  template <typename Lhs>
903  class Impl : public MatcherInterface<Lhs> {
904   public:
905    explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
906    virtual bool MatchAndExplain(
907        Lhs lhs, MatchResultListener* /* listener */) const {
908      return Op()(lhs, rhs_);
909    }
910    virtual void DescribeTo(::std::ostream* os) const {
911      *os << D::Desc() << " ";
912      UniversalPrint(rhs_, os);
913    }
914    virtual void DescribeNegationTo(::std::ostream* os) const {
915      *os << D::NegatedDesc() <<  " ";
916      UniversalPrint(rhs_, os);
917    }
918   private:
919    Rhs rhs_;
920    GTEST_DISALLOW_ASSIGN_(Impl);
921  };
922  Rhs rhs_;
923  GTEST_DISALLOW_ASSIGN_(ComparisonBase);
924};
925
926template <typename Rhs>
927class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
928 public:
929  explicit EqMatcher(const Rhs& rhs)
930      : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
931  static const char* Desc() { return "is equal to"; }
932  static const char* NegatedDesc() { return "isn't equal to"; }
933};
934template <typename Rhs>
935class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
936 public:
937  explicit NeMatcher(const Rhs& rhs)
938      : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
939  static const char* Desc() { return "isn't equal to"; }
940  static const char* NegatedDesc() { return "is equal to"; }
941};
942template <typename Rhs>
943class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
944 public:
945  explicit LtMatcher(const Rhs& rhs)
946      : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
947  static const char* Desc() { return "is <"; }
948  static const char* NegatedDesc() { return "isn't <"; }
949};
950template <typename Rhs>
951class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
952 public:
953  explicit GtMatcher(const Rhs& rhs)
954      : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
955  static const char* Desc() { return "is >"; }
956  static const char* NegatedDesc() { return "isn't >"; }
957};
958template <typename Rhs>
959class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
960 public:
961  explicit LeMatcher(const Rhs& rhs)
962      : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
963  static const char* Desc() { return "is <="; }
964  static const char* NegatedDesc() { return "isn't <="; }
965};
966template <typename Rhs>
967class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
968 public:
969  explicit GeMatcher(const Rhs& rhs)
970      : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
971  static const char* Desc() { return "is >="; }
972  static const char* NegatedDesc() { return "isn't >="; }
973};
974
975// Implements the polymorphic IsNull() matcher, which matches any raw or smart
976// pointer that is NULL.
977class IsNullMatcher {
978 public:
979  template <typename Pointer>
980  bool MatchAndExplain(const Pointer& p,
981                       MatchResultListener* /* listener */) const {
982#if GTEST_LANG_CXX11
983    return p == nullptr;
984#else  // GTEST_LANG_CXX11
985    return GetRawPointer(p) == NULL;
986#endif  // GTEST_LANG_CXX11
987  }
988
989  void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
990  void DescribeNegationTo(::std::ostream* os) const {
991    *os << "isn't NULL";
992  }
993};
994
995// Implements the polymorphic NotNull() matcher, which matches any raw or smart
996// pointer that is not NULL.
997class NotNullMatcher {
998 public:
999  template <typename Pointer>
1000  bool MatchAndExplain(const Pointer& p,
1001                       MatchResultListener* /* listener */) const {
1002#if GTEST_LANG_CXX11
1003    return p != nullptr;
1004#else  // GTEST_LANG_CXX11
1005    return GetRawPointer(p) != NULL;
1006#endif  // GTEST_LANG_CXX11
1007  }
1008
1009  void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
1010  void DescribeNegationTo(::std::ostream* os) const {
1011    *os << "is NULL";
1012  }
1013};
1014
1015// Ref(variable) matches any argument that is a reference to
1016// 'variable'.  This matcher is polymorphic as it can match any
1017// super type of the type of 'variable'.
1018//
1019// The RefMatcher template class implements Ref(variable).  It can
1020// only be instantiated with a reference type.  This prevents a user
1021// from mistakenly using Ref(x) to match a non-reference function
1022// argument.  For example, the following will righteously cause a
1023// compiler error:
1024//
1025//   int n;
1026//   Matcher<int> m1 = Ref(n);   // This won't compile.
1027//   Matcher<int&> m2 = Ref(n);  // This will compile.
1028template <typename T>
1029class RefMatcher;
1030
1031template <typename T>
1032class RefMatcher<T&> {
1033  // Google Mock is a generic framework and thus needs to support
1034  // mocking any function types, including those that take non-const
1035  // reference arguments.  Therefore the template parameter T (and
1036  // Super below) can be instantiated to either a const type or a
1037  // non-const type.
1038 public:
1039  // RefMatcher() takes a T& instead of const T&, as we want the
1040  // compiler to catch using Ref(const_value) as a matcher for a
1041  // non-const reference.
1042  explicit RefMatcher(T& x) : object_(x) {}  // NOLINT
1043
1044  template <typename Super>
1045  operator Matcher<Super&>() const {
1046    // By passing object_ (type T&) to Impl(), which expects a Super&,
1047    // we make sure that Super is a super type of T.  In particular,
1048    // this catches using Ref(const_value) as a matcher for a
1049    // non-const reference, as you cannot implicitly convert a const
1050    // reference to a non-const reference.
1051    return MakeMatcher(new Impl<Super>(object_));
1052  }
1053
1054 private:
1055  template <typename Super>
1056  class Impl : public MatcherInterface<Super&> {
1057   public:
1058    explicit Impl(Super& x) : object_(x) {}  // NOLINT
1059
1060    // MatchAndExplain() takes a Super& (as opposed to const Super&)
1061    // in order to match the interface MatcherInterface<Super&>.
1062    virtual bool MatchAndExplain(
1063        Super& x, MatchResultListener* listener) const {
1064      *listener << "which is located @" << static_cast<const void*>(&x);
1065      return &x == &object_;
1066    }
1067
1068    virtual void DescribeTo(::std::ostream* os) const {
1069      *os << "references the variable ";
1070      UniversalPrinter<Super&>::Print(object_, os);
1071    }
1072
1073    virtual void DescribeNegationTo(::std::ostream* os) const {
1074      *os << "does not reference the variable ";
1075      UniversalPrinter<Super&>::Print(object_, os);
1076    }
1077
1078   private:
1079    const Super& object_;
1080
1081    GTEST_DISALLOW_ASSIGN_(Impl);
1082  };
1083
1084  T& object_;
1085
1086  GTEST_DISALLOW_ASSIGN_(RefMatcher);
1087};
1088
1089// Polymorphic helper functions for narrow and wide string matchers.
1090inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1091  return String::CaseInsensitiveCStringEquals(lhs, rhs);
1092}
1093
1094inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1095                                         const wchar_t* rhs) {
1096  return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1097}
1098
1099// String comparison for narrow or wide strings that can have embedded NUL
1100// characters.
1101template <typename StringType>
1102bool CaseInsensitiveStringEquals(const StringType& s1,
1103                                 const StringType& s2) {
1104  // Are the heads equal?
1105  if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1106    return false;
1107  }
1108
1109  // Skip the equal heads.
1110  const typename StringType::value_type nul = 0;
1111  const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1112
1113  // Are we at the end of either s1 or s2?
1114  if (i1 == StringType::npos || i2 == StringType::npos) {
1115    return i1 == i2;
1116  }
1117
1118  // Are the tails equal?
1119  return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1120}
1121
1122// String matchers.
1123
1124// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1125template <typename StringType>
1126class StrEqualityMatcher {
1127 public:
1128  StrEqualityMatcher(const StringType& str, bool expect_eq,
1129                     bool case_sensitive)
1130      : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1131
1132  // Accepts pointer types, particularly:
1133  //   const char*
1134  //   char*
1135  //   const wchar_t*
1136  //   wchar_t*
1137  template <typename CharType>
1138  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1139    if (s == NULL) {
1140      return !expect_eq_;
1141    }
1142    return MatchAndExplain(StringType(s), listener);
1143  }
1144
1145  // Matches anything that can convert to StringType.
1146  //
1147  // This is a template, not just a plain function with const StringType&,
1148  // because StringPiece has some interfering non-explicit constructors.
1149  template <typename MatcheeStringType>
1150  bool MatchAndExplain(const MatcheeStringType& s,
1151                       MatchResultListener* /* listener */) const {
1152    const StringType& s2(s);
1153    const bool eq = case_sensitive_ ? s2 == string_ :
1154        CaseInsensitiveStringEquals(s2, string_);
1155    return expect_eq_ == eq;
1156  }
1157
1158  void DescribeTo(::std::ostream* os) const {
1159    DescribeToHelper(expect_eq_, os);
1160  }
1161
1162  void DescribeNegationTo(::std::ostream* os) const {
1163    DescribeToHelper(!expect_eq_, os);
1164  }
1165
1166 private:
1167  void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
1168    *os << (expect_eq ? "is " : "isn't ");
1169    *os << "equal to ";
1170    if (!case_sensitive_) {
1171      *os << "(ignoring case) ";
1172    }
1173    UniversalPrint(string_, os);
1174  }
1175
1176  const StringType string_;
1177  const bool expect_eq_;
1178  const bool case_sensitive_;
1179
1180  GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
1181};
1182
1183// Implements the polymorphic HasSubstr(substring) matcher, which
1184// can be used as a Matcher<T> as long as T can be converted to a
1185// string.
1186template <typename StringType>
1187class HasSubstrMatcher {
1188 public:
1189  explicit HasSubstrMatcher(const StringType& substring)
1190      : substring_(substring) {}
1191
1192  // Accepts pointer types, particularly:
1193  //   const char*
1194  //   char*
1195  //   const wchar_t*
1196  //   wchar_t*
1197  template <typename CharType>
1198  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1199    return s != NULL && MatchAndExplain(StringType(s), listener);
1200  }
1201
1202  // Matches anything that can convert to StringType.
1203  //
1204  // This is a template, not just a plain function with const StringType&,
1205  // because StringPiece has some interfering non-explicit constructors.
1206  template <typename MatcheeStringType>
1207  bool MatchAndExplain(const MatcheeStringType& s,
1208                       MatchResultListener* /* listener */) const {
1209    const StringType& s2(s);
1210    return s2.find(substring_) != StringType::npos;
1211  }
1212
1213  // Describes what this matcher matches.
1214  void DescribeTo(::std::ostream* os) const {
1215    *os << "has substring ";
1216    UniversalPrint(substring_, os);
1217  }
1218
1219  void DescribeNegationTo(::std::ostream* os) const {
1220    *os << "has no substring ";
1221    UniversalPrint(substring_, os);
1222  }
1223
1224 private:
1225  const StringType substring_;
1226
1227  GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
1228};
1229
1230// Implements the polymorphic StartsWith(substring) matcher, which
1231// can be used as a Matcher<T> as long as T can be converted to a
1232// string.
1233template <typename StringType>
1234class StartsWithMatcher {
1235 public:
1236  explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1237  }
1238
1239  // Accepts pointer types, particularly:
1240  //   const char*
1241  //   char*
1242  //   const wchar_t*
1243  //   wchar_t*
1244  template <typename CharType>
1245  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1246    return s != NULL && MatchAndExplain(StringType(s), listener);
1247  }
1248
1249  // Matches anything that can convert to StringType.
1250  //
1251  // This is a template, not just a plain function with const StringType&,
1252  // because StringPiece has some interfering non-explicit constructors.
1253  template <typename MatcheeStringType>
1254  bool MatchAndExplain(const MatcheeStringType& s,
1255                       MatchResultListener* /* listener */) const {
1256    const StringType& s2(s);
1257    return s2.length() >= prefix_.length() &&
1258        s2.substr(0, prefix_.length()) == prefix_;
1259  }
1260
1261  void DescribeTo(::std::ostream* os) const {
1262    *os << "starts with ";
1263    UniversalPrint(prefix_, os);
1264  }
1265
1266  void DescribeNegationTo(::std::ostream* os) const {
1267    *os << "doesn't start with ";
1268    UniversalPrint(prefix_, os);
1269  }
1270
1271 private:
1272  const StringType prefix_;
1273
1274  GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
1275};
1276
1277// Implements the polymorphic EndsWith(substring) matcher, which
1278// can be used as a Matcher<T> as long as T can be converted to a
1279// string.
1280template <typename StringType>
1281class EndsWithMatcher {
1282 public:
1283  explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1284
1285  // Accepts pointer types, particularly:
1286  //   const char*
1287  //   char*
1288  //   const wchar_t*
1289  //   wchar_t*
1290  template <typename CharType>
1291  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1292    return s != NULL && MatchAndExplain(StringType(s), listener);
1293  }
1294
1295  // Matches anything that can convert to StringType.
1296  //
1297  // This is a template, not just a plain function with const StringType&,
1298  // because StringPiece has some interfering non-explicit constructors.
1299  template <typename MatcheeStringType>
1300  bool MatchAndExplain(const MatcheeStringType& s,
1301                       MatchResultListener* /* listener */) const {
1302    const StringType& s2(s);
1303    return s2.length() >= suffix_.length() &&
1304        s2.substr(s2.length() - suffix_.length()) == suffix_;
1305  }
1306
1307  void DescribeTo(::std::ostream* os) const {
1308    *os << "ends with ";
1309    UniversalPrint(suffix_, os);
1310  }
1311
1312  void DescribeNegationTo(::std::ostream* os) const {
1313    *os << "doesn't end with ";
1314    UniversalPrint(suffix_, os);
1315  }
1316
1317 private:
1318  const StringType suffix_;
1319
1320  GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
1321};
1322
1323// Implements polymorphic matchers MatchesRegex(regex) and
1324// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1325// T can be converted to a string.
1326class MatchesRegexMatcher {
1327 public:
1328  MatchesRegexMatcher(const RE* regex, bool full_match)
1329      : regex_(regex), full_match_(full_match) {}
1330
1331  // Accepts pointer types, particularly:
1332  //   const char*
1333  //   char*
1334  //   const wchar_t*
1335  //   wchar_t*
1336  template <typename CharType>
1337  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1338    return s != NULL && MatchAndExplain(internal::string(s), listener);
1339  }
1340
1341  // Matches anything that can convert to internal::string.
1342  //
1343  // This is a template, not just a plain function with const internal::string&,
1344  // because StringPiece has some interfering non-explicit constructors.
1345  template <class MatcheeStringType>
1346  bool MatchAndExplain(const MatcheeStringType& s,
1347                       MatchResultListener* /* listener */) const {
1348    const internal::string& s2(s);
1349    return full_match_ ? RE::FullMatch(s2, *regex_) :
1350        RE::PartialMatch(s2, *regex_);
1351  }
1352
1353  void DescribeTo(::std::ostream* os) const {
1354    *os << (full_match_ ? "matches" : "contains")
1355        << " regular expression ";
1356    UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1357  }
1358
1359  void DescribeNegationTo(::std::ostream* os) const {
1360    *os << "doesn't " << (full_match_ ? "match" : "contain")
1361        << " regular expression ";
1362    UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1363  }
1364
1365 private:
1366  const internal::linked_ptr<const RE> regex_;
1367  const bool full_match_;
1368
1369  GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
1370};
1371
1372// Implements a matcher that compares the two fields of a 2-tuple
1373// using one of the ==, <=, <, etc, operators.  The two fields being
1374// compared don't have to have the same type.
1375//
1376// The matcher defined here is polymorphic (for example, Eq() can be
1377// used to match a tuple<int, short>, a tuple<const long&, double>,
1378// etc).  Therefore we use a template type conversion operator in the
1379// implementation.
1380template <typename D, typename Op>
1381class PairMatchBase {
1382 public:
1383  template <typename T1, typename T2>
1384  operator Matcher< ::testing::tuple<T1, T2> >() const {
1385    return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1386  }
1387  template <typename T1, typename T2>
1388  operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1389    return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
1390  }
1391
1392 private:
1393  static ::std::ostream& GetDesc(::std::ostream& os) {  // NOLINT
1394    return os << D::Desc();
1395  }
1396
1397  template <typename Tuple>
1398  class Impl : public MatcherInterface<Tuple> {
1399   public:
1400    virtual bool MatchAndExplain(
1401        Tuple args,
1402        MatchResultListener* /* listener */) const {
1403      return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1404    }
1405    virtual void DescribeTo(::std::ostream* os) const {
1406      *os << "are " << GetDesc;
1407    }
1408    virtual void DescribeNegationTo(::std::ostream* os) const {
1409      *os << "aren't " << GetDesc;
1410    }
1411  };
1412};
1413
1414class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1415 public:
1416  static const char* Desc() { return "an equal pair"; }
1417};
1418class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1419 public:
1420  static const char* Desc() { return "an unequal pair"; }
1421};
1422class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1423 public:
1424  static const char* Desc() { return "a pair where the first < the second"; }
1425};
1426class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1427 public:
1428  static const char* Desc() { return "a pair where the first > the second"; }
1429};
1430class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1431 public:
1432  static const char* Desc() { return "a pair where the first <= the second"; }
1433};
1434class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1435 public:
1436  static const char* Desc() { return "a pair where the first >= the second"; }
1437};
1438
1439// Implements the Not(...) matcher for a particular argument type T.
1440// We do not nest it inside the NotMatcher class template, as that
1441// will prevent different instantiations of NotMatcher from sharing
1442// the same NotMatcherImpl<T> class.
1443template <typename T>
1444class NotMatcherImpl : public MatcherInterface<T> {
1445 public:
1446  explicit NotMatcherImpl(const Matcher<T>& matcher)
1447      : matcher_(matcher) {}
1448
1449  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1450    return !matcher_.MatchAndExplain(x, listener);
1451  }
1452
1453  virtual void DescribeTo(::std::ostream* os) const {
1454    matcher_.DescribeNegationTo(os);
1455  }
1456
1457  virtual void DescribeNegationTo(::std::ostream* os) const {
1458    matcher_.DescribeTo(os);
1459  }
1460
1461 private:
1462  const Matcher<T> matcher_;
1463
1464  GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
1465};
1466
1467// Implements the Not(m) matcher, which matches a value that doesn't
1468// match matcher m.
1469template <typename InnerMatcher>
1470class NotMatcher {
1471 public:
1472  explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1473
1474  // This template type conversion operator allows Not(m) to be used
1475  // to match any type m can match.
1476  template <typename T>
1477  operator Matcher<T>() const {
1478    return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1479  }
1480
1481 private:
1482  InnerMatcher matcher_;
1483
1484  GTEST_DISALLOW_ASSIGN_(NotMatcher);
1485};
1486
1487// Implements the AllOf(m1, m2) matcher for a particular argument type
1488// T. We do not nest it inside the BothOfMatcher class template, as
1489// that will prevent different instantiations of BothOfMatcher from
1490// sharing the same BothOfMatcherImpl<T> class.
1491template <typename T>
1492class BothOfMatcherImpl : public MatcherInterface<T> {
1493 public:
1494  BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1495      : matcher1_(matcher1), matcher2_(matcher2) {}
1496
1497  virtual void DescribeTo(::std::ostream* os) const {
1498    *os << "(";
1499    matcher1_.DescribeTo(os);
1500    *os << ") and (";
1501    matcher2_.DescribeTo(os);
1502    *os << ")";
1503  }
1504
1505  virtual void DescribeNegationTo(::std::ostream* os) const {
1506    *os << "(";
1507    matcher1_.DescribeNegationTo(os);
1508    *os << ") or (";
1509    matcher2_.DescribeNegationTo(os);
1510    *os << ")";
1511  }
1512
1513  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1514    // If either matcher1_ or matcher2_ doesn't match x, we only need
1515    // to explain why one of them fails.
1516    StringMatchResultListener listener1;
1517    if (!matcher1_.MatchAndExplain(x, &listener1)) {
1518      *listener << listener1.str();
1519      return false;
1520    }
1521
1522    StringMatchResultListener listener2;
1523    if (!matcher2_.MatchAndExplain(x, &listener2)) {
1524      *listener << listener2.str();
1525      return false;
1526    }
1527
1528    // Otherwise we need to explain why *both* of them match.
1529    const internal::string s1 = listener1.str();
1530    const internal::string s2 = listener2.str();
1531
1532    if (s1 == "") {
1533      *listener << s2;
1534    } else {
1535      *listener << s1;
1536      if (s2 != "") {
1537        *listener << ", and " << s2;
1538      }
1539    }
1540    return true;
1541  }
1542
1543 private:
1544  const Matcher<T> matcher1_;
1545  const Matcher<T> matcher2_;
1546
1547  GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
1548};
1549
1550#if GTEST_LANG_CXX11
1551// MatcherList provides mechanisms for storing a variable number of matchers in
1552// a list structure (ListType) and creating a combining matcher from such a
1553// list.
1554// The template is defined recursively using the following template paramters:
1555//   * kSize is the length of the MatcherList.
1556//   * Head is the type of the first matcher of the list.
1557//   * Tail denotes the types of the remaining matchers of the list.
1558template <int kSize, typename Head, typename... Tail>
1559struct MatcherList {
1560  typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
1561  typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
1562
1563  // BuildList stores variadic type values in a nested pair structure.
1564  // Example:
1565  // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1566  // the corresponding result of type pair<int, pair<string, float>>.
1567  static ListType BuildList(const Head& matcher, const Tail&... tail) {
1568    return ListType(matcher, MatcherListTail::BuildList(tail...));
1569  }
1570
1571  // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1572  // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1573  // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1574  // constructor taking two Matcher<T>s as input.
1575  template <typename T, template <typename /* T */> class CombiningMatcher>
1576  static Matcher<T> CreateMatcher(const ListType& matchers) {
1577    return Matcher<T>(new CombiningMatcher<T>(
1578        SafeMatcherCast<T>(matchers.first),
1579        MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1580            matchers.second)));
1581  }
1582};
1583
1584// The following defines the base case for the recursive definition of
1585// MatcherList.
1586template <typename Matcher1, typename Matcher2>
1587struct MatcherList<2, Matcher1, Matcher2> {
1588  typedef ::std::pair<Matcher1, Matcher2> ListType;
1589
1590  static ListType BuildList(const Matcher1& matcher1,
1591                            const Matcher2& matcher2) {
1592    return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
1593  }
1594
1595  template <typename T, template <typename /* T */> class CombiningMatcher>
1596  static Matcher<T> CreateMatcher(const ListType& matchers) {
1597    return Matcher<T>(new CombiningMatcher<T>(
1598        SafeMatcherCast<T>(matchers.first),
1599        SafeMatcherCast<T>(matchers.second)));
1600  }
1601};
1602
1603// VariadicMatcher is used for the variadic implementation of
1604// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1605// CombiningMatcher<T> is used to recursively combine the provided matchers
1606// (of type Args...).
1607template <template <typename T> class CombiningMatcher, typename... Args>
1608class VariadicMatcher {
1609 public:
1610  VariadicMatcher(const Args&... matchers)  // NOLINT
1611      : matchers_(MatcherListType::BuildList(matchers...)) {}
1612
1613  // This template type conversion operator allows an
1614  // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1615  // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1616  template <typename T>
1617  operator Matcher<T>() const {
1618    return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1619        matchers_);
1620  }
1621
1622 private:
1623  typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1624
1625  const typename MatcherListType::ListType matchers_;
1626
1627  GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1628};
1629
1630template <typename... Args>
1631using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1632
1633#endif  // GTEST_LANG_CXX11
1634
1635// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1636// matches a value that matches all of the matchers m_1, ..., and m_n.
1637template <typename Matcher1, typename Matcher2>
1638class BothOfMatcher {
1639 public:
1640  BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1641      : matcher1_(matcher1), matcher2_(matcher2) {}
1642
1643  // This template type conversion operator allows a
1644  // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1645  // both Matcher1 and Matcher2 can match.
1646  template <typename T>
1647  operator Matcher<T>() const {
1648    return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1649                                               SafeMatcherCast<T>(matcher2_)));
1650  }
1651
1652 private:
1653  Matcher1 matcher1_;
1654  Matcher2 matcher2_;
1655
1656  GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
1657};
1658
1659// Implements the AnyOf(m1, m2) matcher for a particular argument type
1660// T.  We do not nest it inside the AnyOfMatcher class template, as
1661// that will prevent different instantiations of AnyOfMatcher from
1662// sharing the same EitherOfMatcherImpl<T> class.
1663template <typename T>
1664class EitherOfMatcherImpl : public MatcherInterface<T> {
1665 public:
1666  EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1667      : matcher1_(matcher1), matcher2_(matcher2) {}
1668
1669  virtual void DescribeTo(::std::ostream* os) const {
1670    *os << "(";
1671    matcher1_.DescribeTo(os);
1672    *os << ") or (";
1673    matcher2_.DescribeTo(os);
1674    *os << ")";
1675  }
1676
1677  virtual void DescribeNegationTo(::std::ostream* os) const {
1678    *os << "(";
1679    matcher1_.DescribeNegationTo(os);
1680    *os << ") and (";
1681    matcher2_.DescribeNegationTo(os);
1682    *os << ")";
1683  }
1684
1685  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1686    // If either matcher1_ or matcher2_ matches x, we just need to
1687    // explain why *one* of them matches.
1688    StringMatchResultListener listener1;
1689    if (matcher1_.MatchAndExplain(x, &listener1)) {
1690      *listener << listener1.str();
1691      return true;
1692    }
1693
1694    StringMatchResultListener listener2;
1695    if (matcher2_.MatchAndExplain(x, &listener2)) {
1696      *listener << listener2.str();
1697      return true;
1698    }
1699
1700    // Otherwise we need to explain why *both* of them fail.
1701    const internal::string s1 = listener1.str();
1702    const internal::string s2 = listener2.str();
1703
1704    if (s1 == "") {
1705      *listener << s2;
1706    } else {
1707      *listener << s1;
1708      if (s2 != "") {
1709        *listener << ", and " << s2;
1710      }
1711    }
1712    return false;
1713  }
1714
1715 private:
1716  const Matcher<T> matcher1_;
1717  const Matcher<T> matcher2_;
1718
1719  GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
1720};
1721
1722#if GTEST_LANG_CXX11
1723// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1724template <typename... Args>
1725using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1726
1727#endif  // GTEST_LANG_CXX11
1728
1729// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1730// matches a value that matches at least one of the matchers m_1, ...,
1731// and m_n.
1732template <typename Matcher1, typename Matcher2>
1733class EitherOfMatcher {
1734 public:
1735  EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1736      : matcher1_(matcher1), matcher2_(matcher2) {}
1737
1738  // This template type conversion operator allows a
1739  // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1740  // both Matcher1 and Matcher2 can match.
1741  template <typename T>
1742  operator Matcher<T>() const {
1743    return Matcher<T>(new EitherOfMatcherImpl<T>(
1744        SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
1745  }
1746
1747 private:
1748  Matcher1 matcher1_;
1749  Matcher2 matcher2_;
1750
1751  GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
1752};
1753
1754// Used for implementing Truly(pred), which turns a predicate into a
1755// matcher.
1756template <typename Predicate>
1757class TrulyMatcher {
1758 public:
1759  explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1760
1761  // This method template allows Truly(pred) to be used as a matcher
1762  // for type T where T is the argument type of predicate 'pred'.  The
1763  // argument is passed by reference as the predicate may be
1764  // interested in the address of the argument.
1765  template <typename T>
1766  bool MatchAndExplain(T& x,  // NOLINT
1767                       MatchResultListener* /* listener */) const {
1768    // Without the if-statement, MSVC sometimes warns about converting
1769    // a value to bool (warning 4800).
1770    //
1771    // We cannot write 'return !!predicate_(x);' as that doesn't work
1772    // when predicate_(x) returns a class convertible to bool but
1773    // having no operator!().
1774    if (predicate_(x))
1775      return true;
1776    return false;
1777  }
1778
1779  void DescribeTo(::std::ostream* os) const {
1780    *os << "satisfies the given predicate";
1781  }
1782
1783  void DescribeNegationTo(::std::ostream* os) const {
1784    *os << "doesn't satisfy the given predicate";
1785  }
1786
1787 private:
1788  Predicate predicate_;
1789
1790  GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
1791};
1792
1793// Used for implementing Matches(matcher), which turns a matcher into
1794// a predicate.
1795template <typename M>
1796class MatcherAsPredicate {
1797 public:
1798  explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1799
1800  // This template operator() allows Matches(m) to be used as a
1801  // predicate on type T where m is a matcher on type T.
1802  //
1803  // The argument x is passed by reference instead of by value, as
1804  // some matcher may be interested in its address (e.g. as in
1805  // Matches(Ref(n))(x)).
1806  template <typename T>
1807  bool operator()(const T& x) const {
1808    // We let matcher_ commit to a particular type here instead of
1809    // when the MatcherAsPredicate object was constructed.  This
1810    // allows us to write Matches(m) where m is a polymorphic matcher
1811    // (e.g. Eq(5)).
1812    //
1813    // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1814    // compile when matcher_ has type Matcher<const T&>; if we write
1815    // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1816    // when matcher_ has type Matcher<T>; if we just write
1817    // matcher_.Matches(x), it won't compile when matcher_ is
1818    // polymorphic, e.g. Eq(5).
1819    //
1820    // MatcherCast<const T&>() is necessary for making the code work
1821    // in all of the above situations.
1822    return MatcherCast<const T&>(matcher_).Matches(x);
1823  }
1824
1825 private:
1826  M matcher_;
1827
1828  GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
1829};
1830
1831// For implementing ASSERT_THAT() and EXPECT_THAT().  The template
1832// argument M must be a type that can be converted to a matcher.
1833template <typename M>
1834class PredicateFormatterFromMatcher {
1835 public:
1836  explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
1837
1838  // This template () operator allows a PredicateFormatterFromMatcher
1839  // object to act as a predicate-formatter suitable for using with
1840  // Google Test's EXPECT_PRED_FORMAT1() macro.
1841  template <typename T>
1842  AssertionResult operator()(const char* value_text, const T& x) const {
1843    // We convert matcher_ to a Matcher<const T&> *now* instead of
1844    // when the PredicateFormatterFromMatcher object was constructed,
1845    // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1846    // know which type to instantiate it to until we actually see the
1847    // type of x here.
1848    //
1849    // We write SafeMatcherCast<const T&>(matcher_) instead of
1850    // Matcher<const T&>(matcher_), as the latter won't compile when
1851    // matcher_ has type Matcher<T> (e.g. An<int>()).
1852    // We don't write MatcherCast<const T&> either, as that allows
1853    // potentially unsafe downcasting of the matcher argument.
1854    const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
1855    StringMatchResultListener listener;
1856    if (MatchPrintAndExplain(x, matcher, &listener))
1857      return AssertionSuccess();
1858
1859    ::std::stringstream ss;
1860    ss << "Value of: " << value_text << "\n"
1861       << "Expected: ";
1862    matcher.DescribeTo(&ss);
1863    ss << "\n  Actual: " << listener.str();
1864    return AssertionFailure() << ss.str();
1865  }
1866
1867 private:
1868  const M matcher_;
1869
1870  GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
1871};
1872
1873// A helper function for converting a matcher to a predicate-formatter
1874// without the user needing to explicitly write the type.  This is
1875// used for implementing ASSERT_THAT() and EXPECT_THAT().
1876// Implementation detail: 'matcher' is received by-value to force decaying.
1877template <typename M>
1878inline PredicateFormatterFromMatcher<M>
1879MakePredicateFormatterFromMatcher(M matcher) {
1880  return PredicateFormatterFromMatcher<M>(internal::move(matcher));
1881}
1882
1883// Implements the polymorphic floating point equality matcher, which matches
1884// two float values using ULP-based approximation or, optionally, a
1885// user-specified epsilon.  The template is meant to be instantiated with
1886// FloatType being either float or double.
1887template <typename FloatType>
1888class FloatingEqMatcher {
1889 public:
1890  // Constructor for FloatingEqMatcher.
1891  // The matcher's input will be compared with expected.  The matcher treats two
1892  // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,
1893  // equality comparisons between NANs will always return false.  We specify a
1894  // negative max_abs_error_ term to indicate that ULP-based approximation will
1895  // be used for comparison.
1896  FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1897    expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1898  }
1899
1900  // Constructor that supports a user-specified max_abs_error that will be used
1901  // for comparison instead of ULP-based approximation.  The max absolute
1902  // should be non-negative.
1903  FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1904                    FloatType max_abs_error)
1905      : expected_(expected),
1906        nan_eq_nan_(nan_eq_nan),
1907        max_abs_error_(max_abs_error) {
1908    GTEST_CHECK_(max_abs_error >= 0)
1909        << ", where max_abs_error is" << max_abs_error;
1910  }
1911
1912  // Implements floating point equality matcher as a Matcher<T>.
1913  template <typename T>
1914  class Impl : public MatcherInterface<T> {
1915   public:
1916    Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1917        : expected_(expected),
1918          nan_eq_nan_(nan_eq_nan),
1919          max_abs_error_(max_abs_error) {}
1920
1921    virtual bool MatchAndExplain(T value,
1922                                 MatchResultListener* listener) const {
1923      const FloatingPoint<FloatType> actual(value), expected(expected_);
1924
1925      // Compares NaNs first, if nan_eq_nan_ is true.
1926      if (actual.is_nan() || expected.is_nan()) {
1927        if (actual.is_nan() && expected.is_nan()) {
1928          return nan_eq_nan_;
1929        }
1930        // One is nan; the other is not nan.
1931        return false;
1932      }
1933      if (HasMaxAbsError()) {
1934        // We perform an equality check so that inf will match inf, regardless
1935        // of error bounds.  If the result of value - expected_ would result in
1936        // overflow or if either value is inf, the default result is infinity,
1937        // which should only match if max_abs_error_ is also infinity.
1938        if (value == expected_) {
1939          return true;
1940        }
1941
1942        const FloatType diff = value - expected_;
1943        if (fabs(diff) <= max_abs_error_) {
1944          return true;
1945        }
1946
1947        if (listener->IsInterested()) {
1948          *listener << "which is " << diff << " from " << expected_;
1949        }
1950        return false;
1951      } else {
1952        return actual.AlmostEquals(expected);
1953      }
1954    }
1955
1956    virtual void DescribeTo(::std::ostream* os) const {
1957      // os->precision() returns the previously set precision, which we
1958      // store to restore the ostream to its original configuration
1959      // after outputting.
1960      const ::std::streamsize old_precision = os->precision(
1961          ::std::numeric_limits<FloatType>::digits10 + 2);
1962      if (FloatingPoint<FloatType>(expected_).is_nan()) {
1963        if (nan_eq_nan_) {
1964          *os << "is NaN";
1965        } else {
1966          *os << "never matches";
1967        }
1968      } else {
1969        *os << "is approximately " << expected_;
1970        if (HasMaxAbsError()) {
1971          *os << " (absolute error <= " << max_abs_error_ << ")";
1972        }
1973      }
1974      os->precision(old_precision);
1975    }
1976
1977    virtual void DescribeNegationTo(::std::ostream* os) const {
1978      // As before, get original precision.
1979      const ::std::streamsize old_precision = os->precision(
1980          ::std::numeric_limits<FloatType>::digits10 + 2);
1981      if (FloatingPoint<FloatType>(expected_).is_nan()) {
1982        if (nan_eq_nan_) {
1983          *os << "isn't NaN";
1984        } else {
1985          *os << "is anything";
1986        }
1987      } else {
1988        *os << "isn't approximately " << expected_;
1989        if (HasMaxAbsError()) {
1990          *os << " (absolute error > " << max_abs_error_ << ")";
1991        }
1992      }
1993      // Restore original precision.
1994      os->precision(old_precision);
1995    }
1996
1997   private:
1998    bool HasMaxAbsError() const {
1999      return max_abs_error_ >= 0;
2000    }
2001
2002    const FloatType expected_;
2003    const bool nan_eq_nan_;
2004    // max_abs_error will be used for value comparison when >= 0.
2005    const FloatType max_abs_error_;
2006
2007    GTEST_DISALLOW_ASSIGN_(Impl);
2008  };
2009
2010  // The following 3 type conversion operators allow FloatEq(expected) and
2011  // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
2012  // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2013  // (While Google's C++ coding style doesn't allow arguments passed
2014  // by non-const reference, we may see them in code not conforming to
2015  // the style.  Therefore Google Mock needs to support them.)
2016  operator Matcher<FloatType>() const {
2017    return MakeMatcher(
2018        new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
2019  }
2020
2021  operator Matcher<const FloatType&>() const {
2022    return MakeMatcher(
2023        new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2024  }
2025
2026  operator Matcher<FloatType&>() const {
2027    return MakeMatcher(
2028        new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2029  }
2030
2031 private:
2032  const FloatType expected_;
2033  const bool nan_eq_nan_;
2034  // max_abs_error will be used for value comparison when >= 0.
2035  const FloatType max_abs_error_;
2036
2037  GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
2038};
2039
2040// Implements the Pointee(m) matcher for matching a pointer whose
2041// pointee matches matcher m.  The pointer can be either raw or smart.
2042template <typename InnerMatcher>
2043class PointeeMatcher {
2044 public:
2045  explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2046
2047  // This type conversion operator template allows Pointee(m) to be
2048  // used as a matcher for any pointer type whose pointee type is
2049  // compatible with the inner matcher, where type Pointer can be
2050  // either a raw pointer or a smart pointer.
2051  //
2052  // The reason we do this instead of relying on
2053  // MakePolymorphicMatcher() is that the latter is not flexible
2054  // enough for implementing the DescribeTo() method of Pointee().
2055  template <typename Pointer>
2056  operator Matcher<Pointer>() const {
2057    return MakeMatcher(new Impl<Pointer>(matcher_));
2058  }
2059
2060 private:
2061  // The monomorphic implementation that works for a particular pointer type.
2062  template <typename Pointer>
2063  class Impl : public MatcherInterface<Pointer> {
2064   public:
2065    typedef typename PointeeOf<GTEST_REMOVE_CONST_(  // NOLINT
2066        GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
2067
2068    explicit Impl(const InnerMatcher& matcher)
2069        : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2070
2071    virtual void DescribeTo(::std::ostream* os) const {
2072      *os << "points to a value that ";
2073      matcher_.DescribeTo(os);
2074    }
2075
2076    virtual void DescribeNegationTo(::std::ostream* os) const {
2077      *os << "does not point to a value that ";
2078      matcher_.DescribeTo(os);
2079    }
2080
2081    virtual bool MatchAndExplain(Pointer pointer,
2082                                 MatchResultListener* listener) const {
2083      if (GetRawPointer(pointer) == NULL)
2084        return false;
2085
2086      *listener << "which points to ";
2087      return MatchPrintAndExplain(*pointer, matcher_, listener);
2088    }
2089
2090   private:
2091    const Matcher<const Pointee&> matcher_;
2092
2093    GTEST_DISALLOW_ASSIGN_(Impl);
2094  };
2095
2096  const InnerMatcher matcher_;
2097
2098  GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
2099};
2100
2101// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2102// reference that matches inner_matcher when dynamic_cast<T> is applied.
2103// The result of dynamic_cast<To> is forwarded to the inner matcher.
2104// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2105// If To is a reference and the cast fails, this matcher returns false
2106// immediately.
2107template <typename To>
2108class WhenDynamicCastToMatcherBase {
2109 public:
2110  explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2111      : matcher_(matcher) {}
2112
2113  void DescribeTo(::std::ostream* os) const {
2114    GetCastTypeDescription(os);
2115    matcher_.DescribeTo(os);
2116  }
2117
2118  void DescribeNegationTo(::std::ostream* os) const {
2119    GetCastTypeDescription(os);
2120    matcher_.DescribeNegationTo(os);
2121  }
2122
2123 protected:
2124  const Matcher<To> matcher_;
2125
2126  static string GetToName() {
2127#if GTEST_HAS_RTTI
2128    return GetTypeName<To>();
2129#else  // GTEST_HAS_RTTI
2130    return "the target type";
2131#endif  // GTEST_HAS_RTTI
2132  }
2133
2134 private:
2135  static void GetCastTypeDescription(::std::ostream* os) {
2136    *os << "when dynamic_cast to " << GetToName() << ", ";
2137  }
2138
2139  GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2140};
2141
2142// Primary template.
2143// To is a pointer. Cast and forward the result.
2144template <typename To>
2145class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2146 public:
2147  explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2148      : WhenDynamicCastToMatcherBase<To>(matcher) {}
2149
2150  template <typename From>
2151  bool MatchAndExplain(From from, MatchResultListener* listener) const {
2152    // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2153    To to = dynamic_cast<To>(from);
2154    return MatchPrintAndExplain(to, this->matcher_, listener);
2155  }
2156};
2157
2158// Specialize for references.
2159// In this case we return false if the dynamic_cast fails.
2160template <typename To>
2161class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2162 public:
2163  explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2164      : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2165
2166  template <typename From>
2167  bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2168    // We don't want an std::bad_cast here, so do the cast with pointers.
2169    To* to = dynamic_cast<To*>(&from);
2170    if (to == NULL) {
2171      *listener << "which cannot be dynamic_cast to " << this->GetToName();
2172      return false;
2173    }
2174    return MatchPrintAndExplain(*to, this->matcher_, listener);
2175  }
2176};
2177
2178// Implements the Field() matcher for matching a field (i.e. member
2179// variable) of an object.
2180template <typename Class, typename FieldType>
2181class FieldMatcher {
2182 public:
2183  FieldMatcher(FieldType Class::*field,
2184               const Matcher<const FieldType&>& matcher)
2185      : field_(field), matcher_(matcher) {}
2186
2187  void DescribeTo(::std::ostream* os) const {
2188    *os << "is an object whose given field ";
2189    matcher_.DescribeTo(os);
2190  }
2191
2192  void DescribeNegationTo(::std::ostream* os) const {
2193    *os << "is an object whose given field ";
2194    matcher_.DescribeNegationTo(os);
2195  }
2196
2197  template <typename T>
2198  bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2199    return MatchAndExplainImpl(
2200        typename ::testing::internal::
2201            is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2202        value, listener);
2203  }
2204
2205 private:
2206  // The first argument of MatchAndExplainImpl() is needed to help
2207  // Symbian's C++ compiler choose which overload to use.  Its type is
2208  // true_type iff the Field() matcher is used to match a pointer.
2209  bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2210                           MatchResultListener* listener) const {
2211    *listener << "whose given field is ";
2212    return MatchPrintAndExplain(obj.*field_, matcher_, listener);
2213  }
2214
2215  bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2216                           MatchResultListener* listener) const {
2217    if (p == NULL)
2218      return false;
2219
2220    *listener << "which points to an object ";
2221    // Since *p has a field, it must be a class/struct/union type and
2222    // thus cannot be a pointer.  Therefore we pass false_type() as
2223    // the first argument.
2224    return MatchAndExplainImpl(false_type(), *p, listener);
2225  }
2226
2227  const FieldType Class::*field_;
2228  const Matcher<const FieldType&> matcher_;
2229
2230  GTEST_DISALLOW_ASSIGN_(FieldMatcher);
2231};
2232
2233// Implements the Property() matcher for matching a property
2234// (i.e. return value of a getter method) of an object.
2235template <typename Class, typename PropertyType>
2236class PropertyMatcher {
2237 public:
2238  // The property may have a reference type, so 'const PropertyType&'
2239  // may cause double references and fail to compile.  That's why we
2240  // need GTEST_REFERENCE_TO_CONST, which works regardless of
2241  // PropertyType being a reference or not.
2242  typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
2243
2244  PropertyMatcher(PropertyType (Class::*property)() const,
2245                  const Matcher<RefToConstProperty>& matcher)
2246      : property_(property), matcher_(matcher) {}
2247
2248  void DescribeTo(::std::ostream* os) const {
2249    *os << "is an object whose given property ";
2250    matcher_.DescribeTo(os);
2251  }
2252
2253  void DescribeNegationTo(::std::ostream* os) const {
2254    *os << "is an object whose given property ";
2255    matcher_.DescribeNegationTo(os);
2256  }
2257
2258  template <typename T>
2259  bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2260    return MatchAndExplainImpl(
2261        typename ::testing::internal::
2262            is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2263        value, listener);
2264  }
2265
2266 private:
2267  // The first argument of MatchAndExplainImpl() is needed to help
2268  // Symbian's C++ compiler choose which overload to use.  Its type is
2269  // true_type iff the Property() matcher is used to match a pointer.
2270  bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2271                           MatchResultListener* listener) const {
2272    *listener << "whose given property is ";
2273    // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2274    // which takes a non-const reference as argument.
2275#if defined(_PREFAST_ ) && _MSC_VER == 1800
2276    // Workaround bug in VC++ 2013's /analyze parser.
2277    // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2278    posix::Abort();  // To make sure it is never run.
2279    return false;
2280#else
2281    RefToConstProperty result = (obj.*property_)();
2282    return MatchPrintAndExplain(result, matcher_, listener);
2283#endif
2284  }
2285
2286  bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2287                           MatchResultListener* listener) const {
2288    if (p == NULL)
2289      return false;
2290
2291    *listener << "which points to an object ";
2292    // Since *p has a property method, it must be a class/struct/union
2293    // type and thus cannot be a pointer.  Therefore we pass
2294    // false_type() as the first argument.
2295    return MatchAndExplainImpl(false_type(), *p, listener);
2296  }
2297
2298  PropertyType (Class::*property_)() const;
2299  const Matcher<RefToConstProperty> matcher_;
2300
2301  GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
2302};
2303
2304// Type traits specifying various features of different functors for ResultOf.
2305// The default template specifies features for functor objects.
2306// Functor classes have to typedef argument_type and result_type
2307// to be compatible with ResultOf.
2308template <typename Functor>
2309struct CallableTraits {
2310  typedef typename Functor::result_type ResultType;
2311  typedef Functor StorageType;
2312
2313  static void CheckIsValid(Functor /* functor */) {}
2314  template <typename T>
2315  static ResultType Invoke(Functor f, T arg) { return f(arg); }
2316};
2317
2318// Specialization for function pointers.
2319template <typename ArgType, typename ResType>
2320struct CallableTraits<ResType(*)(ArgType)> {
2321  typedef ResType ResultType;
2322  typedef ResType(*StorageType)(ArgType);
2323
2324  static void CheckIsValid(ResType(*f)(ArgType)) {
2325    GTEST_CHECK_(f != NULL)
2326        << "NULL function pointer is passed into ResultOf().";
2327  }
2328  template <typename T>
2329  static ResType Invoke(ResType(*f)(ArgType), T arg) {
2330    return (*f)(arg);
2331  }
2332};
2333
2334// Implements the ResultOf() matcher for matching a return value of a
2335// unary function of an object.
2336template <typename Callable>
2337class ResultOfMatcher {
2338 public:
2339  typedef typename CallableTraits<Callable>::ResultType ResultType;
2340
2341  ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2342      : callable_(callable), matcher_(matcher) {
2343    CallableTraits<Callable>::CheckIsValid(callable_);
2344  }
2345
2346  template <typename T>
2347  operator Matcher<T>() const {
2348    return Matcher<T>(new Impl<T>(callable_, matcher_));
2349  }
2350
2351 private:
2352  typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2353
2354  template <typename T>
2355  class Impl : public MatcherInterface<T> {
2356   public:
2357    Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2358        : callable_(callable), matcher_(matcher) {}
2359
2360    virtual void DescribeTo(::std::ostream* os) const {
2361      *os << "is mapped by the given callable to a value that ";
2362      matcher_.DescribeTo(os);
2363    }
2364
2365    virtual void DescribeNegationTo(::std::ostream* os) const {
2366      *os << "is mapped by the given callable to a value that ";
2367      matcher_.DescribeNegationTo(os);
2368    }
2369
2370    virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
2371      *listener << "which is mapped by the given callable to ";
2372      // Cannot pass the return value (for example, int) to
2373      // MatchPrintAndExplain, which takes a non-const reference as argument.
2374      ResultType result =
2375          CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2376      return MatchPrintAndExplain(result, matcher_, listener);
2377    }
2378
2379   private:
2380    // Functors often define operator() as non-const method even though
2381    // they are actualy stateless. But we need to use them even when
2382    // 'this' is a const pointer. It's the user's responsibility not to
2383    // use stateful callables with ResultOf(), which does't guarantee
2384    // how many times the callable will be invoked.
2385    mutable CallableStorageType callable_;
2386    const Matcher<ResultType> matcher_;
2387
2388    GTEST_DISALLOW_ASSIGN_(Impl);
2389  };  // class Impl
2390
2391  const CallableStorageType callable_;
2392  const Matcher<ResultType> matcher_;
2393
2394  GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
2395};
2396
2397// Implements a matcher that checks the size of an STL-style container.
2398template <typename SizeMatcher>
2399class SizeIsMatcher {
2400 public:
2401  explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2402       : size_matcher_(size_matcher) {
2403  }
2404
2405  template <typename Container>
2406  operator Matcher<Container>() const {
2407    return MakeMatcher(new Impl<Container>(size_matcher_));
2408  }
2409
2410  template <typename Container>
2411  class Impl : public MatcherInterface<Container> {
2412   public:
2413    typedef internal::StlContainerView<
2414         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2415    typedef typename ContainerView::type::size_type SizeType;
2416    explicit Impl(const SizeMatcher& size_matcher)
2417        : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2418
2419    virtual void DescribeTo(::std::ostream* os) const {
2420      *os << "size ";
2421      size_matcher_.DescribeTo(os);
2422    }
2423    virtual void DescribeNegationTo(::std::ostream* os) const {
2424      *os << "size ";
2425      size_matcher_.DescribeNegationTo(os);
2426    }
2427
2428    virtual bool MatchAndExplain(Container container,
2429                                 MatchResultListener* listener) const {
2430      SizeType size = container.size();
2431      StringMatchResultListener size_listener;
2432      const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2433      *listener
2434          << "whose size " << size << (result ? " matches" : " doesn't match");
2435      PrintIfNotEmpty(size_listener.str(), listener->stream());
2436      return result;
2437    }
2438
2439   private:
2440    const Matcher<SizeType> size_matcher_;
2441    GTEST_DISALLOW_ASSIGN_(Impl);
2442  };
2443
2444 private:
2445  const SizeMatcher size_matcher_;
2446  GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2447};
2448
2449// Implements a matcher that checks the begin()..end() distance of an STL-style
2450// container.
2451template <typename DistanceMatcher>
2452class BeginEndDistanceIsMatcher {
2453 public:
2454  explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2455      : distance_matcher_(distance_matcher) {}
2456
2457  template <typename Container>
2458  operator Matcher<Container>() const {
2459    return MakeMatcher(new Impl<Container>(distance_matcher_));
2460  }
2461
2462  template <typename Container>
2463  class Impl : public MatcherInterface<Container> {
2464   public:
2465    typedef internal::StlContainerView<
2466        GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2467    typedef typename std::iterator_traits<
2468        typename ContainerView::type::const_iterator>::difference_type
2469        DistanceType;
2470    explicit Impl(const DistanceMatcher& distance_matcher)
2471        : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2472
2473    virtual void DescribeTo(::std::ostream* os) const {
2474      *os << "distance between begin() and end() ";
2475      distance_matcher_.DescribeTo(os);
2476    }
2477    virtual void DescribeNegationTo(::std::ostream* os) const {
2478      *os << "distance between begin() and end() ";
2479      distance_matcher_.DescribeNegationTo(os);
2480    }
2481
2482    virtual bool MatchAndExplain(Container container,
2483                                 MatchResultListener* listener) const {
2484#if GTEST_HAS_STD_BEGIN_AND_END_
2485      using std::begin;
2486      using std::end;
2487      DistanceType distance = std::distance(begin(container), end(container));
2488#else
2489      DistanceType distance = std::distance(container.begin(), container.end());
2490#endif
2491      StringMatchResultListener distance_listener;
2492      const bool result =
2493          distance_matcher_.MatchAndExplain(distance, &distance_listener);
2494      *listener << "whose distance between begin() and end() " << distance
2495                << (result ? " matches" : " doesn't match");
2496      PrintIfNotEmpty(distance_listener.str(), listener->stream());
2497      return result;
2498    }
2499
2500   private:
2501    const Matcher<DistanceType> distance_matcher_;
2502    GTEST_DISALLOW_ASSIGN_(Impl);
2503  };
2504
2505 private:
2506  const DistanceMatcher distance_matcher_;
2507  GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2508};
2509
2510// Implements an equality matcher for any STL-style container whose elements
2511// support ==. This matcher is like Eq(), but its failure explanations provide
2512// more detailed information that is useful when the container is used as a set.
2513// The failure message reports elements that are in one of the operands but not
2514// the other. The failure messages do not report duplicate or out-of-order
2515// elements in the containers (which don't properly matter to sets, but can
2516// occur if the containers are vectors or lists, for example).
2517//
2518// Uses the container's const_iterator, value_type, operator ==,
2519// begin(), and end().
2520template <typename Container>
2521class ContainerEqMatcher {
2522 public:
2523  typedef internal::StlContainerView<Container> View;
2524  typedef typename View::type StlContainer;
2525  typedef typename View::const_reference StlContainerReference;
2526
2527  // We make a copy of expected in case the elements in it are modified
2528  // after this matcher is created.
2529  explicit ContainerEqMatcher(const Container& expected)
2530      : expected_(View::Copy(expected)) {
2531    // Makes sure the user doesn't instantiate this class template
2532    // with a const or reference type.
2533    (void)testing::StaticAssertTypeEq<Container,
2534        GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2535  }
2536
2537  void DescribeTo(::std::ostream* os) const {
2538    *os << "equals ";
2539    UniversalPrint(expected_, os);
2540  }
2541  void DescribeNegationTo(::std::ostream* os) const {
2542    *os << "does not equal ";
2543    UniversalPrint(expected_, os);
2544  }
2545
2546  template <typename LhsContainer>
2547  bool MatchAndExplain(const LhsContainer& lhs,
2548                       MatchResultListener* listener) const {
2549    // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2550    // that causes LhsContainer to be a const type sometimes.
2551    typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2552        LhsView;
2553    typedef typename LhsView::type LhsStlContainer;
2554    StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2555    if (lhs_stl_container == expected_)
2556      return true;
2557
2558    ::std::ostream* const os = listener->stream();
2559    if (os != NULL) {
2560      // Something is different. Check for extra values first.
2561      bool printed_header = false;
2562      for (typename LhsStlContainer::const_iterator it =
2563               lhs_stl_container.begin();
2564           it != lhs_stl_container.end(); ++it) {
2565        if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2566            expected_.end()) {
2567          if (printed_header) {
2568            *os << ", ";
2569          } else {
2570            *os << "which has these unexpected elements: ";
2571            printed_header = true;
2572          }
2573          UniversalPrint(*it, os);
2574        }
2575      }
2576
2577      // Now check for missing values.
2578      bool printed_header2 = false;
2579      for (typename StlContainer::const_iterator it = expected_.begin();
2580           it != expected_.end(); ++it) {
2581        if (internal::ArrayAwareFind(
2582                lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2583            lhs_stl_container.end()) {
2584          if (printed_header2) {
2585            *os << ", ";
2586          } else {
2587            *os << (printed_header ? ",\nand" : "which")
2588                << " doesn't have these expected elements: ";
2589            printed_header2 = true;
2590          }
2591          UniversalPrint(*it, os);
2592        }
2593      }
2594    }
2595
2596    return false;
2597  }
2598
2599 private:
2600  const StlContainer expected_;
2601
2602  GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2603};
2604
2605// A comparator functor that uses the < operator to compare two values.
2606struct LessComparator {
2607  template <typename T, typename U>
2608  bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2609};
2610
2611// Implements WhenSortedBy(comparator, container_matcher).
2612template <typename Comparator, typename ContainerMatcher>
2613class WhenSortedByMatcher {
2614 public:
2615  WhenSortedByMatcher(const Comparator& comparator,
2616                      const ContainerMatcher& matcher)
2617      : comparator_(comparator), matcher_(matcher) {}
2618
2619  template <typename LhsContainer>
2620  operator Matcher<LhsContainer>() const {
2621    return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2622  }
2623
2624  template <typename LhsContainer>
2625  class Impl : public MatcherInterface<LhsContainer> {
2626   public:
2627    typedef internal::StlContainerView<
2628         GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2629    typedef typename LhsView::type LhsStlContainer;
2630    typedef typename LhsView::const_reference LhsStlContainerReference;
2631    // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2632    // so that we can match associative containers.
2633    typedef typename RemoveConstFromKey<
2634        typename LhsStlContainer::value_type>::type LhsValue;
2635
2636    Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2637        : comparator_(comparator), matcher_(matcher) {}
2638
2639    virtual void DescribeTo(::std::ostream* os) const {
2640      *os << "(when sorted) ";
2641      matcher_.DescribeTo(os);
2642    }
2643
2644    virtual void DescribeNegationTo(::std::ostream* os) const {
2645      *os << "(when sorted) ";
2646      matcher_.DescribeNegationTo(os);
2647    }
2648
2649    virtual bool MatchAndExplain(LhsContainer lhs,
2650                                 MatchResultListener* listener) const {
2651      LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2652      ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2653                                               lhs_stl_container.end());
2654      ::std::sort(
2655           sorted_container.begin(), sorted_container.end(), comparator_);
2656
2657      if (!listener->IsInterested()) {
2658        // If the listener is not interested, we do not need to
2659        // construct the inner explanation.
2660        return matcher_.Matches(sorted_container);
2661      }
2662
2663      *listener << "which is ";
2664      UniversalPrint(sorted_container, listener->stream());
2665      *listener << " when sorted";
2666
2667      StringMatchResultListener inner_listener;
2668      const bool match = matcher_.MatchAndExplain(sorted_container,
2669                                                  &inner_listener);
2670      PrintIfNotEmpty(inner_listener.str(), listener->stream());
2671      return match;
2672    }
2673
2674   private:
2675    const Comparator comparator_;
2676    const Matcher<const ::std::vector<LhsValue>&> matcher_;
2677
2678    GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2679  };
2680
2681 private:
2682  const Comparator comparator_;
2683  const ContainerMatcher matcher_;
2684
2685  GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2686};
2687
2688// Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher
2689// must be able to be safely cast to Matcher<tuple<const T1&, const
2690// T2&> >, where T1 and T2 are the types of elements in the LHS
2691// container and the RHS container respectively.
2692template <typename TupleMatcher, typename RhsContainer>
2693class PointwiseMatcher {
2694 public:
2695  typedef internal::StlContainerView<RhsContainer> RhsView;
2696  typedef typename RhsView::type RhsStlContainer;
2697  typedef typename RhsStlContainer::value_type RhsValue;
2698
2699  // Like ContainerEq, we make a copy of rhs in case the elements in
2700  // it are modified after this matcher is created.
2701  PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2702      : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2703    // Makes sure the user doesn't instantiate this class template
2704    // with a const or reference type.
2705    (void)testing::StaticAssertTypeEq<RhsContainer,
2706        GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2707  }
2708
2709  template <typename LhsContainer>
2710  operator Matcher<LhsContainer>() const {
2711    return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2712  }
2713
2714  template <typename LhsContainer>
2715  class Impl : public MatcherInterface<LhsContainer> {
2716   public:
2717    typedef internal::StlContainerView<
2718         GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2719    typedef typename LhsView::type LhsStlContainer;
2720    typedef typename LhsView::const_reference LhsStlContainerReference;
2721    typedef typename LhsStlContainer::value_type LhsValue;
2722    // We pass the LHS value and the RHS value to the inner matcher by
2723    // reference, as they may be expensive to copy.  We must use tuple
2724    // instead of pair here, as a pair cannot hold references (C++ 98,
2725    // 20.2.2 [lib.pairs]).
2726    typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2727
2728    Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2729        // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2730        : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2731          rhs_(rhs) {}
2732
2733    virtual void DescribeTo(::std::ostream* os) const {
2734      *os << "contains " << rhs_.size()
2735          << " values, where each value and its corresponding value in ";
2736      UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2737      *os << " ";
2738      mono_tuple_matcher_.DescribeTo(os);
2739    }
2740    virtual void DescribeNegationTo(::std::ostream* os) const {
2741      *os << "doesn't contain exactly " << rhs_.size()
2742          << " values, or contains a value x at some index i"
2743          << " where x and the i-th value of ";
2744      UniversalPrint(rhs_, os);
2745      *os << " ";
2746      mono_tuple_matcher_.DescribeNegationTo(os);
2747    }
2748
2749    virtual bool MatchAndExplain(LhsContainer lhs,
2750                                 MatchResultListener* listener) const {
2751      LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2752      const size_t actual_size = lhs_stl_container.size();
2753      if (actual_size != rhs_.size()) {
2754        *listener << "which contains " << actual_size << " values";
2755        return false;
2756      }
2757
2758      typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2759      typename RhsStlContainer::const_iterator right = rhs_.begin();
2760      for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2761        const InnerMatcherArg value_pair(*left, *right);
2762
2763        if (listener->IsInterested()) {
2764          StringMatchResultListener inner_listener;
2765          if (!mono_tuple_matcher_.MatchAndExplain(
2766                  value_pair, &inner_listener)) {
2767            *listener << "where the value pair (";
2768            UniversalPrint(*left, listener->stream());
2769            *listener << ", ";
2770            UniversalPrint(*right, listener->stream());
2771            *listener << ") at index #" << i << " don't match";
2772            PrintIfNotEmpty(inner_listener.str(), listener->stream());
2773            return false;
2774          }
2775        } else {
2776          if (!mono_tuple_matcher_.Matches(value_pair))
2777            return false;
2778        }
2779      }
2780
2781      return true;
2782    }
2783
2784   private:
2785    const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2786    const RhsStlContainer rhs_;
2787
2788    GTEST_DISALLOW_ASSIGN_(Impl);
2789  };
2790
2791 private:
2792  const TupleMatcher tuple_matcher_;
2793  const RhsStlContainer rhs_;
2794
2795  GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2796};
2797
2798// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
2799template <typename Container>
2800class QuantifierMatcherImpl : public MatcherInterface<Container> {
2801 public:
2802  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2803  typedef StlContainerView<RawContainer> View;
2804  typedef typename View::type StlContainer;
2805  typedef typename View::const_reference StlContainerReference;
2806  typedef typename StlContainer::value_type Element;
2807
2808  template <typename InnerMatcher>
2809  explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
2810      : inner_matcher_(
2811           testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2812
2813  // Checks whether:
2814  // * All elements in the container match, if all_elements_should_match.
2815  // * Any element in the container matches, if !all_elements_should_match.
2816  bool MatchAndExplainImpl(bool all_elements_should_match,
2817                           Container container,
2818                           MatchResultListener* listener) const {
2819    StlContainerReference stl_container = View::ConstReference(container);
2820    size_t i = 0;
2821    for (typename StlContainer::const_iterator it = stl_container.begin();
2822         it != stl_container.end(); ++it, ++i) {
2823      StringMatchResultListener inner_listener;
2824      const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2825
2826      if (matches != all_elements_should_match) {
2827        *listener << "whose element #" << i
2828                  << (matches ? " matches" : " doesn't match");
2829        PrintIfNotEmpty(inner_listener.str(), listener->stream());
2830        return !all_elements_should_match;
2831      }
2832    }
2833    return all_elements_should_match;
2834  }
2835
2836 protected:
2837  const Matcher<const Element&> inner_matcher_;
2838
2839  GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2840};
2841
2842// Implements Contains(element_matcher) for the given argument type Container.
2843// Symmetric to EachMatcherImpl.
2844template <typename Container>
2845class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2846 public:
2847  template <typename InnerMatcher>
2848  explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2849      : QuantifierMatcherImpl<Container>(inner_matcher) {}
2850
2851  // Describes what this matcher does.
2852  virtual void DescribeTo(::std::ostream* os) const {
2853    *os << "contains at least one element that ";
2854    this->inner_matcher_.DescribeTo(os);
2855  }
2856
2857  virtual void DescribeNegationTo(::std::ostream* os) const {
2858    *os << "doesn't contain any element that ";
2859    this->inner_matcher_.DescribeTo(os);
2860  }
2861
2862  virtual bool MatchAndExplain(Container container,
2863                               MatchResultListener* listener) const {
2864    return this->MatchAndExplainImpl(false, container, listener);
2865  }
2866
2867 private:
2868  GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
2869};
2870
2871// Implements Each(element_matcher) for the given argument type Container.
2872// Symmetric to ContainsMatcherImpl.
2873template <typename Container>
2874class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2875 public:
2876  template <typename InnerMatcher>
2877  explicit EachMatcherImpl(InnerMatcher inner_matcher)
2878      : QuantifierMatcherImpl<Container>(inner_matcher) {}
2879
2880  // Describes what this matcher does.
2881  virtual void DescribeTo(::std::ostream* os) const {
2882    *os << "only contains elements that ";
2883    this->inner_matcher_.DescribeTo(os);
2884  }
2885
2886  virtual void DescribeNegationTo(::std::ostream* os) const {
2887    *os << "contains some element that ";
2888    this->inner_matcher_.DescribeNegationTo(os);
2889  }
2890
2891  virtual bool MatchAndExplain(Container container,
2892                               MatchResultListener* listener) const {
2893    return this->MatchAndExplainImpl(true, container, listener);
2894  }
2895
2896 private:
2897  GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2898};
2899
2900// Implements polymorphic Contains(element_matcher).
2901template <typename M>
2902class ContainsMatcher {
2903 public:
2904  explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2905
2906  template <typename Container>
2907  operator Matcher<Container>() const {
2908    return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2909  }
2910
2911 private:
2912  const M inner_matcher_;
2913
2914  GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
2915};
2916
2917// Implements polymorphic Each(element_matcher).
2918template <typename M>
2919class EachMatcher {
2920 public:
2921  explicit EachMatcher(M m) : inner_matcher_(m) {}
2922
2923  template <typename Container>
2924  operator Matcher<Container>() const {
2925    return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2926  }
2927
2928 private:
2929  const M inner_matcher_;
2930
2931  GTEST_DISALLOW_ASSIGN_(EachMatcher);
2932};
2933
2934// Implements Key(inner_matcher) for the given argument pair type.
2935// Key(inner_matcher) matches an std::pair whose 'first' field matches
2936// inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
2937// std::map that contains at least one element whose key is >= 5.
2938template <typename PairType>
2939class KeyMatcherImpl : public MatcherInterface<PairType> {
2940 public:
2941  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2942  typedef typename RawPairType::first_type KeyType;
2943
2944  template <typename InnerMatcher>
2945  explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2946      : inner_matcher_(
2947          testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2948  }
2949
2950  // Returns true iff 'key_value.first' (the key) matches the inner matcher.
2951  virtual bool MatchAndExplain(PairType key_value,
2952                               MatchResultListener* listener) const {
2953    StringMatchResultListener inner_listener;
2954    const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2955                                                      &inner_listener);
2956    const internal::string explanation = inner_listener.str();
2957    if (explanation != "") {
2958      *listener << "whose first field is a value " << explanation;
2959    }
2960    return match;
2961  }
2962
2963  // Describes what this matcher does.
2964  virtual void DescribeTo(::std::ostream* os) const {
2965    *os << "has a key that ";
2966    inner_matcher_.DescribeTo(os);
2967  }
2968
2969  // Describes what the negation of this matcher does.
2970  virtual void DescribeNegationTo(::std::ostream* os) const {
2971    *os << "doesn't have a key that ";
2972    inner_matcher_.DescribeTo(os);
2973  }
2974
2975 private:
2976  const Matcher<const KeyType&> inner_matcher_;
2977
2978  GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
2979};
2980
2981// Implements polymorphic Key(matcher_for_key).
2982template <typename M>
2983class KeyMatcher {
2984 public:
2985  explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2986
2987  template <typename PairType>
2988  operator Matcher<PairType>() const {
2989    return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2990  }
2991
2992 private:
2993  const M matcher_for_key_;
2994
2995  GTEST_DISALLOW_ASSIGN_(KeyMatcher);
2996};
2997
2998// Implements Pair(first_matcher, second_matcher) for the given argument pair
2999// type with its two matchers. See Pair() function below.
3000template <typename PairType>
3001class PairMatcherImpl : public MatcherInterface<PairType> {
3002 public:
3003  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3004  typedef typename RawPairType::first_type FirstType;
3005  typedef typename RawPairType::second_type SecondType;
3006
3007  template <typename FirstMatcher, typename SecondMatcher>
3008  PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3009      : first_matcher_(
3010            testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3011        second_matcher_(
3012            testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3013  }
3014
3015  // Describes what this matcher does.
3016  virtual void DescribeTo(::std::ostream* os) const {
3017    *os << "has a first field that ";
3018    first_matcher_.DescribeTo(os);
3019    *os << ", and has a second field that ";
3020    second_matcher_.DescribeTo(os);
3021  }
3022
3023  // Describes what the negation of this matcher does.
3024  virtual void DescribeNegationTo(::std::ostream* os) const {
3025    *os << "has a first field that ";
3026    first_matcher_.DescribeNegationTo(os);
3027    *os << ", or has a second field that ";
3028    second_matcher_.DescribeNegationTo(os);
3029  }
3030
3031  // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3032  // matches second_matcher.
3033  virtual bool MatchAndExplain(PairType a_pair,
3034                               MatchResultListener* listener) const {
3035    if (!listener->IsInterested()) {
3036      // If the listener is not interested, we don't need to construct the
3037      // explanation.
3038      return first_matcher_.Matches(a_pair.first) &&
3039             second_matcher_.Matches(a_pair.second);
3040    }
3041    StringMatchResultListener first_inner_listener;
3042    if (!first_matcher_.MatchAndExplain(a_pair.first,
3043                                        &first_inner_listener)) {
3044      *listener << "whose first field does not match";
3045      PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
3046      return false;
3047    }
3048    StringMatchResultListener second_inner_listener;
3049    if (!second_matcher_.MatchAndExplain(a_pair.second,
3050                                         &second_inner_listener)) {
3051      *listener << "whose second field does not match";
3052      PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
3053      return false;
3054    }
3055    ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3056                   listener);
3057    return true;
3058  }
3059
3060 private:
3061  void ExplainSuccess(const internal::string& first_explanation,
3062                      const internal::string& second_explanation,
3063                      MatchResultListener* listener) const {
3064    *listener << "whose both fields match";
3065    if (first_explanation != "") {
3066      *listener << ", where the first field is a value " << first_explanation;
3067    }
3068    if (second_explanation != "") {
3069      *listener << ", ";
3070      if (first_explanation != "") {
3071        *listener << "and ";
3072      } else {
3073        *listener << "where ";
3074      }
3075      *listener << "the second field is a value " << second_explanation;
3076    }
3077  }
3078
3079  const Matcher<const FirstType&> first_matcher_;
3080  const Matcher<const SecondType&> second_matcher_;
3081
3082  GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
3083};
3084
3085// Implements polymorphic Pair(first_matcher, second_matcher).
3086template <typename FirstMatcher, typename SecondMatcher>
3087class PairMatcher {
3088 public:
3089  PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3090      : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3091
3092  template <typename PairType>
3093  operator Matcher<PairType> () const {
3094    return MakeMatcher(
3095        new PairMatcherImpl<PairType>(
3096            first_matcher_, second_matcher_));
3097  }
3098
3099 private:
3100  const FirstMatcher first_matcher_;
3101  const SecondMatcher second_matcher_;
3102
3103  GTEST_DISALLOW_ASSIGN_(PairMatcher);
3104};
3105
3106// Implements ElementsAre() and ElementsAreArray().
3107template <typename Container>
3108class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3109 public:
3110  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3111  typedef internal::StlContainerView<RawContainer> View;
3112  typedef typename View::type StlContainer;
3113  typedef typename View::const_reference StlContainerReference;
3114  typedef typename StlContainer::value_type Element;
3115
3116  // Constructs the matcher from a sequence of element values or
3117  // element matchers.
3118  template <typename InputIter>
3119  ElementsAreMatcherImpl(InputIter first, InputIter last) {
3120    while (first != last) {
3121      matchers_.push_back(MatcherCast<const Element&>(*first++));
3122    }
3123  }
3124
3125  // Describes what this matcher does.
3126  virtual void DescribeTo(::std::ostream* os) const {
3127    if (count() == 0) {
3128      *os << "is empty";
3129    } else if (count() == 1) {
3130      *os << "has 1 element that ";
3131      matchers_[0].DescribeTo(os);
3132    } else {
3133      *os << "has " << Elements(count()) << " where\n";
3134      for (size_t i = 0; i != count(); ++i) {
3135        *os << "element #" << i << " ";
3136        matchers_[i].DescribeTo(os);
3137        if (i + 1 < count()) {
3138          *os << ",\n";
3139        }
3140      }
3141    }
3142  }
3143
3144  // Describes what the negation of this matcher does.
3145  virtual void DescribeNegationTo(::std::ostream* os) const {
3146    if (count() == 0) {
3147      *os << "isn't empty";
3148      return;
3149    }
3150
3151    *os << "doesn't have " << Elements(count()) << ", or\n";
3152    for (size_t i = 0; i != count(); ++i) {
3153      *os << "element #" << i << " ";
3154      matchers_[i].DescribeNegationTo(os);
3155      if (i + 1 < count()) {
3156        *os << ", or\n";
3157      }
3158    }
3159  }
3160
3161  virtual bool MatchAndExplain(Container container,
3162                               MatchResultListener* listener) const {
3163    // To work with stream-like "containers", we must only walk
3164    // through the elements in one pass.
3165
3166    const bool listener_interested = listener->IsInterested();
3167
3168    // explanations[i] is the explanation of the element at index i.
3169    ::std::vector<internal::string> explanations(count());
3170    StlContainerReference stl_container = View::ConstReference(container);
3171    typename StlContainer::const_iterator it = stl_container.begin();
3172    size_t exam_pos = 0;
3173    bool mismatch_found = false;  // Have we found a mismatched element yet?
3174
3175    // Go through the elements and matchers in pairs, until we reach
3176    // the end of either the elements or the matchers, or until we find a
3177    // mismatch.
3178    for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3179      bool match;  // Does the current element match the current matcher?
3180      if (listener_interested) {
3181        StringMatchResultListener s;
3182        match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3183        explanations[exam_pos] = s.str();
3184      } else {
3185        match = matchers_[exam_pos].Matches(*it);
3186      }
3187
3188      if (!match) {
3189        mismatch_found = true;
3190        break;
3191      }
3192    }
3193    // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3194
3195    // Find how many elements the actual container has.  We avoid
3196    // calling size() s.t. this code works for stream-like "containers"
3197    // that don't define size().
3198    size_t actual_count = exam_pos;
3199    for (; it != stl_container.end(); ++it) {
3200      ++actual_count;
3201    }
3202
3203    if (actual_count != count()) {
3204      // The element count doesn't match.  If the container is empty,
3205      // there's no need to explain anything as Google Mock already
3206      // prints the empty container.  Otherwise we just need to show
3207      // how many elements there actually are.
3208      if (listener_interested && (actual_count != 0)) {
3209        *listener << "which has " << Elements(actual_count);
3210      }
3211      return false;
3212    }
3213
3214    if (mismatch_found) {
3215      // The element count matches, but the exam_pos-th element doesn't match.
3216      if (listener_interested) {
3217        *listener << "whose element #" << exam_pos << " doesn't match";
3218        PrintIfNotEmpty(explanations[exam_pos], listener->stream());
3219      }
3220      return false;
3221    }
3222
3223    // Every element matches its expectation.  We need to explain why
3224    // (the obvious ones can be skipped).
3225    if (listener_interested) {
3226      bool reason_printed = false;
3227      for (size_t i = 0; i != count(); ++i) {
3228        const internal::string& s = explanations[i];
3229        if (!s.empty()) {
3230          if (reason_printed) {
3231            *listener << ",\nand ";
3232          }
3233          *listener << "whose element #" << i << " matches, " << s;
3234          reason_printed = true;
3235        }
3236      }
3237    }
3238    return true;
3239  }
3240
3241 private:
3242  static Message Elements(size_t count) {
3243    return Message() << count << (count == 1 ? " element" : " elements");
3244  }
3245
3246  size_t count() const { return matchers_.size(); }
3247
3248  ::std::vector<Matcher<const Element&> > matchers_;
3249
3250  GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3251};
3252
3253// Connectivity matrix of (elements X matchers), in element-major order.
3254// Initially, there are no edges.
3255// Use NextGraph() to iterate over all possible edge configurations.
3256// Use Randomize() to generate a random edge configuration.
3257class GTEST_API_ MatchMatrix {
3258 public:
3259  MatchMatrix(size_t num_elements, size_t num_matchers)
3260      : num_elements_(num_elements),
3261        num_matchers_(num_matchers),
3262        matched_(num_elements_* num_matchers_, 0) {
3263  }
3264
3265  size_t LhsSize() const { return num_elements_; }
3266  size_t RhsSize() const { return num_matchers_; }
3267  bool HasEdge(size_t ilhs, size_t irhs) const {
3268    return matched_[SpaceIndex(ilhs, irhs)] == 1;
3269  }
3270  void SetEdge(size_t ilhs, size_t irhs, bool b) {
3271    matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3272  }
3273
3274  // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3275  // adds 1 to that number; returns false if incrementing the graph left it
3276  // empty.
3277  bool NextGraph();
3278
3279  void Randomize();
3280
3281  string DebugString() const;
3282
3283 private:
3284  size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3285    return ilhs * num_matchers_ + irhs;
3286  }
3287
3288  size_t num_elements_;
3289  size_t num_matchers_;
3290
3291  // Each element is a char interpreted as bool. They are stored as a
3292  // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3293  // a (ilhs, irhs) matrix coordinate into an offset.
3294  ::std::vector<char> matched_;
3295};
3296
3297typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3298typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3299
3300// Returns a maximum bipartite matching for the specified graph 'g'.
3301// The matching is represented as a vector of {element, matcher} pairs.
3302GTEST_API_ ElementMatcherPairs
3303FindMaxBipartiteMatching(const MatchMatrix& g);
3304
3305GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3306                            MatchResultListener* listener);
3307
3308// Untyped base class for implementing UnorderedElementsAre.  By
3309// putting logic that's not specific to the element type here, we
3310// reduce binary bloat and increase compilation speed.
3311class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3312 protected:
3313  // A vector of matcher describers, one for each element matcher.
3314  // Does not own the describers (and thus can be used only when the
3315  // element matchers are alive).
3316  typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3317
3318  // Describes this UnorderedElementsAre matcher.
3319  void DescribeToImpl(::std::ostream* os) const;
3320
3321  // Describes the negation of this UnorderedElementsAre matcher.
3322  void DescribeNegationToImpl(::std::ostream* os) const;
3323
3324  bool VerifyAllElementsAndMatchersAreMatched(
3325      const ::std::vector<string>& element_printouts,
3326      const MatchMatrix& matrix,
3327      MatchResultListener* listener) const;
3328
3329  MatcherDescriberVec& matcher_describers() {
3330    return matcher_describers_;
3331  }
3332
3333  static Message Elements(size_t n) {
3334    return Message() << n << " element" << (n == 1 ? "" : "s");
3335  }
3336
3337 private:
3338  MatcherDescriberVec matcher_describers_;
3339
3340  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3341};
3342
3343// Implements unordered ElementsAre and unordered ElementsAreArray.
3344template <typename Container>
3345class UnorderedElementsAreMatcherImpl
3346    : public MatcherInterface<Container>,
3347      public UnorderedElementsAreMatcherImplBase {
3348 public:
3349  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3350  typedef internal::StlContainerView<RawContainer> View;
3351  typedef typename View::type StlContainer;
3352  typedef typename View::const_reference StlContainerReference;
3353  typedef typename StlContainer::const_iterator StlContainerConstIterator;
3354  typedef typename StlContainer::value_type Element;
3355
3356  // Constructs the matcher from a sequence of element values or
3357  // element matchers.
3358  template <typename InputIter>
3359  UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3360    for (; first != last; ++first) {
3361      matchers_.push_back(MatcherCast<const Element&>(*first));
3362      matcher_describers().push_back(matchers_.back().GetDescriber());
3363    }
3364  }
3365
3366  // Describes what this matcher does.
3367  virtual void DescribeTo(::std::ostream* os) const {
3368    return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3369  }
3370
3371  // Describes what the negation of this matcher does.
3372  virtual void DescribeNegationTo(::std::ostream* os) const {
3373    return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3374  }
3375
3376  virtual bool MatchAndExplain(Container container,
3377                               MatchResultListener* listener) const {
3378    StlContainerReference stl_container = View::ConstReference(container);
3379    ::std::vector<string> element_printouts;
3380    MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3381                                         stl_container.end(),
3382                                         &element_printouts,
3383                                         listener);
3384
3385    const size_t actual_count = matrix.LhsSize();
3386    if (actual_count == 0 && matchers_.empty()) {
3387      return true;
3388    }
3389    if (actual_count != matchers_.size()) {
3390      // The element count doesn't match.  If the container is empty,
3391      // there's no need to explain anything as Google Mock already
3392      // prints the empty container. Otherwise we just need to show
3393      // how many elements there actually are.
3394      if (actual_count != 0 && listener->IsInterested()) {
3395        *listener << "which has " << Elements(actual_count);
3396      }
3397      return false;
3398    }
3399
3400    return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3401                                                  matrix, listener) &&
3402           FindPairing(matrix, listener);
3403  }
3404
3405 private:
3406  typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3407
3408  template <typename ElementIter>
3409  MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3410                              ::std::vector<string>* element_printouts,
3411                              MatchResultListener* listener) const {
3412    element_printouts->clear();
3413    ::std::vector<char> did_match;
3414    size_t num_elements = 0;
3415    for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3416      if (listener->IsInterested()) {
3417        element_printouts->push_back(PrintToString(*elem_first));
3418      }
3419      for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3420        did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3421      }
3422    }
3423
3424    MatchMatrix matrix(num_elements, matchers_.size());
3425    ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3426    for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3427      for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3428        matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3429      }
3430    }
3431    return matrix;
3432  }
3433
3434  MatcherVec matchers_;
3435
3436  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3437};
3438
3439// Functor for use in TransformTuple.
3440// Performs MatcherCast<Target> on an input argument of any type.
3441template <typename Target>
3442struct CastAndAppendTransform {
3443  template <typename Arg>
3444  Matcher<Target> operator()(const Arg& a) const {
3445    return MatcherCast<Target>(a);
3446  }
3447};
3448
3449// Implements UnorderedElementsAre.
3450template <typename MatcherTuple>
3451class UnorderedElementsAreMatcher {
3452 public:
3453  explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3454      : matchers_(args) {}
3455
3456  template <typename Container>
3457  operator Matcher<Container>() const {
3458    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3459    typedef typename internal::StlContainerView<RawContainer>::type View;
3460    typedef typename View::value_type Element;
3461    typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3462    MatcherVec matchers;
3463    matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3464    TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3465                         ::std::back_inserter(matchers));
3466    return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3467                           matchers.begin(), matchers.end()));
3468  }
3469
3470 private:
3471  const MatcherTuple matchers_;
3472  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3473};
3474
3475// Implements ElementsAre.
3476template <typename MatcherTuple>
3477class ElementsAreMatcher {
3478 public:
3479  explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3480
3481  template <typename Container>
3482  operator Matcher<Container>() const {
3483    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3484    typedef typename internal::StlContainerView<RawContainer>::type View;
3485    typedef typename View::value_type Element;
3486    typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3487    MatcherVec matchers;
3488    matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3489    TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3490                         ::std::back_inserter(matchers));
3491    return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3492                           matchers.begin(), matchers.end()));
3493  }
3494
3495 private:
3496  const MatcherTuple matchers_;
3497  GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3498};
3499
3500// Implements UnorderedElementsAreArray().
3501template <typename T>
3502class UnorderedElementsAreArrayMatcher {
3503 public:
3504  UnorderedElementsAreArrayMatcher() {}
3505
3506  template <typename Iter>
3507  UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3508      : matchers_(first, last) {}
3509
3510  template <typename Container>
3511  operator Matcher<Container>() const {
3512    return MakeMatcher(
3513        new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3514                                                       matchers_.end()));
3515  }
3516
3517 private:
3518  ::std::vector<T> matchers_;
3519
3520  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3521};
3522
3523// Implements ElementsAreArray().
3524template <typename T>
3525class ElementsAreArrayMatcher {
3526 public:
3527  template <typename Iter>
3528  ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3529
3530  template <typename Container>
3531  operator Matcher<Container>() const {
3532    return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3533        matchers_.begin(), matchers_.end()));
3534  }
3535
3536 private:
3537  const ::std::vector<T> matchers_;
3538
3539  GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3540};
3541
3542// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3543// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3544// second) is a polymorphic matcher that matches a value x iff tm
3545// matches tuple (x, second).  Useful for implementing
3546// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3547//
3548// BoundSecondMatcher is copyable and assignable, as we need to put
3549// instances of this class in a vector when implementing
3550// UnorderedPointwise().
3551template <typename Tuple2Matcher, typename Second>
3552class BoundSecondMatcher {
3553 public:
3554  BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3555      : tuple2_matcher_(tm), second_value_(second) {}
3556
3557  template <typename T>
3558  operator Matcher<T>() const {
3559    return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3560  }
3561
3562  // We have to define this for UnorderedPointwise() to compile in
3563  // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3564  // which requires the elements to be assignable in C++98.  The
3565  // compiler cannot generate the operator= for us, as Tuple2Matcher
3566  // and Second may not be assignable.
3567  //
3568  // However, this should never be called, so the implementation just
3569  // need to assert.
3570  void operator=(const BoundSecondMatcher& /*rhs*/) {
3571    GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3572  }
3573
3574 private:
3575  template <typename T>
3576  class Impl : public MatcherInterface<T> {
3577   public:
3578    typedef ::testing::tuple<T, Second> ArgTuple;
3579
3580    Impl(const Tuple2Matcher& tm, const Second& second)
3581        : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3582          second_value_(second) {}
3583
3584    virtual void DescribeTo(::std::ostream* os) const {
3585      *os << "and ";
3586      UniversalPrint(second_value_, os);
3587      *os << " ";
3588      mono_tuple2_matcher_.DescribeTo(os);
3589    }
3590
3591    virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3592      return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3593                                                  listener);
3594    }
3595
3596   private:
3597    const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3598    const Second second_value_;
3599
3600    GTEST_DISALLOW_ASSIGN_(Impl);
3601  };
3602
3603  const Tuple2Matcher tuple2_matcher_;
3604  const Second second_value_;
3605};
3606
3607// Given a 2-tuple matcher tm and a value second,
3608// MatcherBindSecond(tm, second) returns a matcher that matches a
3609// value x iff tm matches tuple (x, second).  Useful for implementing
3610// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3611template <typename Tuple2Matcher, typename Second>
3612BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3613    const Tuple2Matcher& tm, const Second& second) {
3614  return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3615}
3616
3617// Returns the description for a matcher defined using the MATCHER*()
3618// macro where the user-supplied description string is "", if
3619// 'negation' is false; otherwise returns the description of the
3620// negation of the matcher.  'param_values' contains a list of strings
3621// that are the print-out of the matcher's parameters.
3622GTEST_API_ string FormatMatcherDescription(bool negation,
3623                                           const char* matcher_name,
3624                                           const Strings& param_values);
3625
3626}  // namespace internal
3627
3628// ElementsAreArray(first, last)
3629// ElementsAreArray(pointer, count)
3630// ElementsAreArray(array)
3631// ElementsAreArray(container)
3632// ElementsAreArray({ e1, e2, ..., en })
3633//
3634// The ElementsAreArray() functions are like ElementsAre(...), except
3635// that they are given a homogeneous sequence rather than taking each
3636// element as a function argument. The sequence can be specified as an
3637// array, a pointer and count, a vector, an initializer list, or an
3638// STL iterator range. In each of these cases, the underlying sequence
3639// can be either a sequence of values or a sequence of matchers.
3640//
3641// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3642
3643template <typename Iter>
3644inline internal::ElementsAreArrayMatcher<
3645    typename ::std::iterator_traits<Iter>::value_type>
3646ElementsAreArray(Iter first, Iter last) {
3647  typedef typename ::std::iterator_traits<Iter>::value_type T;
3648  return internal::ElementsAreArrayMatcher<T>(first, last);
3649}
3650
3651template <typename T>
3652inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3653    const T* pointer, size_t count) {
3654  return ElementsAreArray(pointer, pointer + count);
3655}
3656
3657template <typename T, size_t N>
3658inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3659    const T (&array)[N]) {
3660  return ElementsAreArray(array, N);
3661}
3662
3663template <typename Container>
3664inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3665ElementsAreArray(const Container& container) {
3666  return ElementsAreArray(container.begin(), container.end());
3667}
3668
3669#if GTEST_HAS_STD_INITIALIZER_LIST_
3670template <typename T>
3671inline internal::ElementsAreArrayMatcher<T>
3672ElementsAreArray(::std::initializer_list<T> xs) {
3673  return ElementsAreArray(xs.begin(), xs.end());
3674}
3675#endif
3676
3677// UnorderedElementsAreArray(first, last)
3678// UnorderedElementsAreArray(pointer, count)
3679// UnorderedElementsAreArray(array)
3680// UnorderedElementsAreArray(container)
3681// UnorderedElementsAreArray({ e1, e2, ..., en })
3682//
3683// The UnorderedElementsAreArray() functions are like
3684// ElementsAreArray(...), but allow matching the elements in any order.
3685template <typename Iter>
3686inline internal::UnorderedElementsAreArrayMatcher<
3687    typename ::std::iterator_traits<Iter>::value_type>
3688UnorderedElementsAreArray(Iter first, Iter last) {
3689  typedef typename ::std::iterator_traits<Iter>::value_type T;
3690  return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3691}
3692
3693template <typename T>
3694inline internal::UnorderedElementsAreArrayMatcher<T>
3695UnorderedElementsAreArray(const T* pointer, size_t count) {
3696  return UnorderedElementsAreArray(pointer, pointer + count);
3697}
3698
3699template <typename T, size_t N>
3700inline internal::UnorderedElementsAreArrayMatcher<T>
3701UnorderedElementsAreArray(const T (&array)[N]) {
3702  return UnorderedElementsAreArray(array, N);
3703}
3704
3705template <typename Container>
3706inline internal::UnorderedElementsAreArrayMatcher<
3707    typename Container::value_type>
3708UnorderedElementsAreArray(const Container& container) {
3709  return UnorderedElementsAreArray(container.begin(), container.end());
3710}
3711
3712#if GTEST_HAS_STD_INITIALIZER_LIST_
3713template <typename T>
3714inline internal::UnorderedElementsAreArrayMatcher<T>
3715UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3716  return UnorderedElementsAreArray(xs.begin(), xs.end());
3717}
3718#endif
3719
3720// _ is a matcher that matches anything of any type.
3721//
3722// This definition is fine as:
3723//
3724//   1. The C++ standard permits using the name _ in a namespace that
3725//      is not the global namespace or ::std.
3726//   2. The AnythingMatcher class has no data member or constructor,
3727//      so it's OK to create global variables of this type.
3728//   3. c-style has approved of using _ in this case.
3729const internal::AnythingMatcher _ = {};
3730// Creates a matcher that matches any value of the given type T.
3731template <typename T>
3732inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3733
3734// Creates a matcher that matches any value of the given type T.
3735template <typename T>
3736inline Matcher<T> An() { return A<T>(); }
3737
3738// Creates a polymorphic matcher that matches anything equal to x.
3739// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3740// wouldn't compile.
3741template <typename T>
3742inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3743
3744// Constructs a Matcher<T> from a 'value' of type T.  The constructed
3745// matcher matches any value that's equal to 'value'.
3746template <typename T>
3747Matcher<T>::Matcher(T value) { *this = Eq(value); }
3748
3749// Creates a monomorphic matcher that matches anything with type Lhs
3750// and equal to rhs.  A user may need to use this instead of Eq(...)
3751// in order to resolve an overloading ambiguity.
3752//
3753// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3754// or Matcher<T>(x), but more readable than the latter.
3755//
3756// We could define similar monomorphic matchers for other comparison
3757// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3758// it yet as those are used much less than Eq() in practice.  A user
3759// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3760// for example.
3761template <typename Lhs, typename Rhs>
3762inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3763
3764// Creates a polymorphic matcher that matches anything >= x.
3765template <typename Rhs>
3766inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3767  return internal::GeMatcher<Rhs>(x);
3768}
3769
3770// Creates a polymorphic matcher that matches anything > x.
3771template <typename Rhs>
3772inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3773  return internal::GtMatcher<Rhs>(x);
3774}
3775
3776// Creates a polymorphic matcher that matches anything <= x.
3777template <typename Rhs>
3778inline internal::LeMatcher<Rhs> Le(Rhs x) {
3779  return internal::LeMatcher<Rhs>(x);
3780}
3781
3782// Creates a polymorphic matcher that matches anything < x.
3783template <typename Rhs>
3784inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3785  return internal::LtMatcher<Rhs>(x);
3786}
3787
3788// Creates a polymorphic matcher that matches anything != x.
3789template <typename Rhs>
3790inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3791  return internal::NeMatcher<Rhs>(x);
3792}
3793
3794// Creates a polymorphic matcher that matches any NULL pointer.
3795inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3796  return MakePolymorphicMatcher(internal::IsNullMatcher());
3797}
3798
3799// Creates a polymorphic matcher that matches any non-NULL pointer.
3800// This is convenient as Not(NULL) doesn't compile (the compiler
3801// thinks that that expression is comparing a pointer with an integer).
3802inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3803  return MakePolymorphicMatcher(internal::NotNullMatcher());
3804}
3805
3806// Creates a polymorphic matcher that matches any argument that
3807// references variable x.
3808template <typename T>
3809inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
3810  return internal::RefMatcher<T&>(x);
3811}
3812
3813// Creates a matcher that matches any double argument approximately
3814// equal to rhs, where two NANs are considered unequal.
3815inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3816  return internal::FloatingEqMatcher<double>(rhs, false);
3817}
3818
3819// Creates a matcher that matches any double argument approximately
3820// equal to rhs, including NaN values when rhs is NaN.
3821inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3822  return internal::FloatingEqMatcher<double>(rhs, true);
3823}
3824
3825// Creates a matcher that matches any double argument approximately equal to
3826// rhs, up to the specified max absolute error bound, where two NANs are
3827// considered unequal.  The max absolute error bound must be non-negative.
3828inline internal::FloatingEqMatcher<double> DoubleNear(
3829    double rhs, double max_abs_error) {
3830  return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3831}
3832
3833// Creates a matcher that matches any double argument approximately equal to
3834// rhs, up to the specified max absolute error bound, including NaN values when
3835// rhs is NaN.  The max absolute error bound must be non-negative.
3836inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3837    double rhs, double max_abs_error) {
3838  return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3839}
3840
3841// Creates a matcher that matches any float argument approximately
3842// equal to rhs, where two NANs are considered unequal.
3843inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3844  return internal::FloatingEqMatcher<float>(rhs, false);
3845}
3846
3847// Creates a matcher that matches any float argument approximately
3848// equal to rhs, including NaN values when rhs is NaN.
3849inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3850  return internal::FloatingEqMatcher<float>(rhs, true);
3851}
3852
3853// Creates a matcher that matches any float argument approximately equal to
3854// rhs, up to the specified max absolute error bound, where two NANs are
3855// considered unequal.  The max absolute error bound must be non-negative.
3856inline internal::FloatingEqMatcher<float> FloatNear(
3857    float rhs, float max_abs_error) {
3858  return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3859}
3860
3861// Creates a matcher that matches any float argument approximately equal to
3862// rhs, up to the specified max absolute error bound, including NaN values when
3863// rhs is NaN.  The max absolute error bound must be non-negative.
3864inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3865    float rhs, float max_abs_error) {
3866  return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3867}
3868
3869// Creates a matcher that matches a pointer (raw or smart) that points
3870// to a value that matches inner_matcher.
3871template <typename InnerMatcher>
3872inline internal::PointeeMatcher<InnerMatcher> Pointee(
3873    const InnerMatcher& inner_matcher) {
3874  return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3875}
3876
3877// Creates a matcher that matches a pointer or reference that matches
3878// inner_matcher when dynamic_cast<To> is applied.
3879// The result of dynamic_cast<To> is forwarded to the inner matcher.
3880// If To is a pointer and the cast fails, the inner matcher will receive NULL.
3881// If To is a reference and the cast fails, this matcher returns false
3882// immediately.
3883template <typename To>
3884inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3885WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3886  return MakePolymorphicMatcher(
3887      internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3888}
3889
3890// Creates a matcher that matches an object whose given field matches
3891// 'matcher'.  For example,
3892//   Field(&Foo::number, Ge(5))
3893// matches a Foo object x iff x.number >= 5.
3894template <typename Class, typename FieldType, typename FieldMatcher>
3895inline PolymorphicMatcher<
3896  internal::FieldMatcher<Class, FieldType> > Field(
3897    FieldType Class::*field, const FieldMatcher& matcher) {
3898  return MakePolymorphicMatcher(
3899      internal::FieldMatcher<Class, FieldType>(
3900          field, MatcherCast<const FieldType&>(matcher)));
3901  // The call to MatcherCast() is required for supporting inner
3902  // matchers of compatible types.  For example, it allows
3903  //   Field(&Foo::bar, m)
3904  // to compile where bar is an int32 and m is a matcher for int64.
3905}
3906
3907// Creates a matcher that matches an object whose given property
3908// matches 'matcher'.  For example,
3909//   Property(&Foo::str, StartsWith("hi"))
3910// matches a Foo object x iff x.str() starts with "hi".
3911template <typename Class, typename PropertyType, typename PropertyMatcher>
3912inline PolymorphicMatcher<
3913  internal::PropertyMatcher<Class, PropertyType> > Property(
3914    PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3915  return MakePolymorphicMatcher(
3916      internal::PropertyMatcher<Class, PropertyType>(
3917          property,
3918          MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3919  // The call to MatcherCast() is required for supporting inner
3920  // matchers of compatible types.  For example, it allows
3921  //   Property(&Foo::bar, m)
3922  // to compile where bar() returns an int32 and m is a matcher for int64.
3923}
3924
3925// Creates a matcher that matches an object iff the result of applying
3926// a callable to x matches 'matcher'.
3927// For example,
3928//   ResultOf(f, StartsWith("hi"))
3929// matches a Foo object x iff f(x) starts with "hi".
3930// callable parameter can be a function, function pointer, or a functor.
3931// Callable has to satisfy the following conditions:
3932//   * It is required to keep no state affecting the results of
3933//     the calls on it and make no assumptions about how many calls
3934//     will be made. Any state it keeps must be protected from the
3935//     concurrent access.
3936//   * If it is a function object, it has to define type result_type.
3937//     We recommend deriving your functor classes from std::unary_function.
3938template <typename Callable, typename ResultOfMatcher>
3939internal::ResultOfMatcher<Callable> ResultOf(
3940    Callable callable, const ResultOfMatcher& matcher) {
3941  return internal::ResultOfMatcher<Callable>(
3942          callable,
3943          MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3944              matcher));
3945  // The call to MatcherCast() is required for supporting inner
3946  // matchers of compatible types.  For example, it allows
3947  //   ResultOf(Function, m)
3948  // to compile where Function() returns an int32 and m is a matcher for int64.
3949}
3950
3951// String matchers.
3952
3953// Matches a string equal to str.
3954inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3955    StrEq(const internal::string& str) {
3956  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3957      str, true, true));
3958}
3959
3960// Matches a string not equal to str.
3961inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3962    StrNe(const internal::string& str) {
3963  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3964      str, false, true));
3965}
3966
3967// Matches a string equal to str, ignoring case.
3968inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3969    StrCaseEq(const internal::string& str) {
3970  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3971      str, true, false));
3972}
3973
3974// Matches a string not equal to str, ignoring case.
3975inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3976    StrCaseNe(const internal::string& str) {
3977  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3978      str, false, false));
3979}
3980
3981// Creates a matcher that matches any string, std::string, or C string
3982// that contains the given substring.
3983inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3984    HasSubstr(const internal::string& substring) {
3985  return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3986      substring));
3987}
3988
3989// Matches a string that starts with 'prefix' (case-sensitive).
3990inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3991    StartsWith(const internal::string& prefix) {
3992  return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3993      prefix));
3994}
3995
3996// Matches a string that ends with 'suffix' (case-sensitive).
3997inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3998    EndsWith(const internal::string& suffix) {
3999  return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
4000      suffix));
4001}
4002
4003// Matches a string that fully matches regular expression 'regex'.
4004// The matcher takes ownership of 'regex'.
4005inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4006    const internal::RE* regex) {
4007  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4008}
4009inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4010    const internal::string& regex) {
4011  return MatchesRegex(new internal::RE(regex));
4012}
4013
4014// Matches a string that contains regular expression 'regex'.
4015// The matcher takes ownership of 'regex'.
4016inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4017    const internal::RE* regex) {
4018  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4019}
4020inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4021    const internal::string& regex) {
4022  return ContainsRegex(new internal::RE(regex));
4023}
4024
4025#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4026// Wide string matchers.
4027
4028// Matches a string equal to str.
4029inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4030    StrEq(const internal::wstring& str) {
4031  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4032      str, true, true));
4033}
4034
4035// Matches a string not equal to str.
4036inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4037    StrNe(const internal::wstring& str) {
4038  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4039      str, false, true));
4040}
4041
4042// Matches a string equal to str, ignoring case.
4043inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4044    StrCaseEq(const internal::wstring& str) {
4045  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4046      str, true, false));
4047}
4048
4049// Matches a string not equal to str, ignoring case.
4050inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4051    StrCaseNe(const internal::wstring& str) {
4052  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4053      str, false, false));
4054}
4055
4056// Creates a matcher that matches any wstring, std::wstring, or C wide string
4057// that contains the given substring.
4058inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4059    HasSubstr(const internal::wstring& substring) {
4060  return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4061      substring));
4062}
4063
4064// Matches a string that starts with 'prefix' (case-sensitive).
4065inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4066    StartsWith(const internal::wstring& prefix) {
4067  return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4068      prefix));
4069}
4070
4071// Matches a string that ends with 'suffix' (case-sensitive).
4072inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4073    EndsWith(const internal::wstring& suffix) {
4074  return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4075      suffix));
4076}
4077
4078#endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4079
4080// Creates a polymorphic matcher that matches a 2-tuple where the
4081// first field == the second field.
4082inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4083
4084// Creates a polymorphic matcher that matches a 2-tuple where the
4085// first field >= the second field.
4086inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4087
4088// Creates a polymorphic matcher that matches a 2-tuple where the
4089// first field > the second field.
4090inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4091
4092// Creates a polymorphic matcher that matches a 2-tuple where the
4093// first field <= the second field.
4094inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4095
4096// Creates a polymorphic matcher that matches a 2-tuple where the
4097// first field < the second field.
4098inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4099
4100// Creates a polymorphic matcher that matches a 2-tuple where the
4101// first field != the second field.
4102inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4103
4104// Creates a matcher that matches any value of type T that m doesn't
4105// match.
4106template <typename InnerMatcher>
4107inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4108  return internal::NotMatcher<InnerMatcher>(m);
4109}
4110
4111// Returns a matcher that matches anything that satisfies the given
4112// predicate.  The predicate can be any unary function or functor
4113// whose return type can be implicitly converted to bool.
4114template <typename Predicate>
4115inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4116Truly(Predicate pred) {
4117  return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4118}
4119
4120// Returns a matcher that matches the container size. The container must
4121// support both size() and size_type which all STL-like containers provide.
4122// Note that the parameter 'size' can be a value of type size_type as well as
4123// matcher. For instance:
4124//   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.
4125//   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.
4126template <typename SizeMatcher>
4127inline internal::SizeIsMatcher<SizeMatcher>
4128SizeIs(const SizeMatcher& size_matcher) {
4129  return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4130}
4131
4132// Returns a matcher that matches the distance between the container's begin()
4133// iterator and its end() iterator, i.e. the size of the container. This matcher
4134// can be used instead of SizeIs with containers such as std::forward_list which
4135// do not implement size(). The container must provide const_iterator (with
4136// valid iterator_traits), begin() and end().
4137template <typename DistanceMatcher>
4138inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4139BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4140  return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4141}
4142
4143// Returns a matcher that matches an equal container.
4144// This matcher behaves like Eq(), but in the event of mismatch lists the
4145// values that are included in one container but not the other. (Duplicate
4146// values and order differences are not explained.)
4147template <typename Container>
4148inline PolymorphicMatcher<internal::ContainerEqMatcher<  // NOLINT
4149                            GTEST_REMOVE_CONST_(Container)> >
4150    ContainerEq(const Container& rhs) {
4151  // This following line is for working around a bug in MSVC 8.0,
4152  // which causes Container to be a const type sometimes.
4153  typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4154  return MakePolymorphicMatcher(
4155      internal::ContainerEqMatcher<RawContainer>(rhs));
4156}
4157
4158// Returns a matcher that matches a container that, when sorted using
4159// the given comparator, matches container_matcher.
4160template <typename Comparator, typename ContainerMatcher>
4161inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4162WhenSortedBy(const Comparator& comparator,
4163             const ContainerMatcher& container_matcher) {
4164  return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4165      comparator, container_matcher);
4166}
4167
4168// Returns a matcher that matches a container that, when sorted using
4169// the < operator, matches container_matcher.
4170template <typename ContainerMatcher>
4171inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4172WhenSorted(const ContainerMatcher& container_matcher) {
4173  return
4174      internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4175          internal::LessComparator(), container_matcher);
4176}
4177
4178// Matches an STL-style container or a native array that contains the
4179// same number of elements as in rhs, where its i-th element and rhs's
4180// i-th element (as a pair) satisfy the given pair matcher, for all i.
4181// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4182// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4183// LHS container and the RHS container respectively.
4184template <typename TupleMatcher, typename Container>
4185inline internal::PointwiseMatcher<TupleMatcher,
4186                                  GTEST_REMOVE_CONST_(Container)>
4187Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4188  // This following line is for working around a bug in MSVC 8.0,
4189  // which causes Container to be a const type sometimes (e.g. when
4190  // rhs is a const int[])..
4191  typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4192  return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4193      tuple_matcher, rhs);
4194}
4195
4196#if GTEST_HAS_STD_INITIALIZER_LIST_
4197
4198// Supports the Pointwise(m, {a, b, c}) syntax.
4199template <typename TupleMatcher, typename T>
4200inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4201    const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4202  return Pointwise(tuple_matcher, std::vector<T>(rhs));
4203}
4204
4205#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4206
4207// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4208// container or a native array that contains the same number of
4209// elements as in rhs, where in some permutation of the container, its
4210// i-th element and rhs's i-th element (as a pair) satisfy the given
4211// pair matcher, for all i.  Tuple2Matcher must be able to be safely
4212// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4213// the types of elements in the LHS container and the RHS container
4214// respectively.
4215//
4216// This is like Pointwise(pair_matcher, rhs), except that the element
4217// order doesn't matter.
4218template <typename Tuple2Matcher, typename RhsContainer>
4219inline internal::UnorderedElementsAreArrayMatcher<
4220    typename internal::BoundSecondMatcher<
4221        Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4222                           RhsContainer)>::type::value_type> >
4223UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4224                   const RhsContainer& rhs_container) {
4225  // This following line is for working around a bug in MSVC 8.0,
4226  // which causes RhsContainer to be a const type sometimes (e.g. when
4227  // rhs_container is a const int[]).
4228  typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4229
4230  // RhsView allows the same code to handle RhsContainer being a
4231  // STL-style container and it being a native C-style array.
4232  typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4233  typedef typename RhsView::type RhsStlContainer;
4234  typedef typename RhsStlContainer::value_type Second;
4235  const RhsStlContainer& rhs_stl_container =
4236      RhsView::ConstReference(rhs_container);
4237
4238  // Create a matcher for each element in rhs_container.
4239  ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4240  for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4241       it != rhs_stl_container.end(); ++it) {
4242    matchers.push_back(
4243        internal::MatcherBindSecond(tuple2_matcher, *it));
4244  }
4245
4246  // Delegate the work to UnorderedElementsAreArray().
4247  return UnorderedElementsAreArray(matchers);
4248}
4249
4250#if GTEST_HAS_STD_INITIALIZER_LIST_
4251
4252// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4253template <typename Tuple2Matcher, typename T>
4254inline internal::UnorderedElementsAreArrayMatcher<
4255    typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4256UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4257                   std::initializer_list<T> rhs) {
4258  return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4259}
4260
4261#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4262
4263// Matches an STL-style container or a native array that contains at
4264// least one element matching the given value or matcher.
4265//
4266// Examples:
4267//   ::std::set<int> page_ids;
4268//   page_ids.insert(3);
4269//   page_ids.insert(1);
4270//   EXPECT_THAT(page_ids, Contains(1));
4271//   EXPECT_THAT(page_ids, Contains(Gt(2)));
4272//   EXPECT_THAT(page_ids, Not(Contains(4)));
4273//
4274//   ::std::map<int, size_t> page_lengths;
4275//   page_lengths[1] = 100;
4276//   EXPECT_THAT(page_lengths,
4277//               Contains(::std::pair<const int, size_t>(1, 100)));
4278//
4279//   const char* user_ids[] = { "joe", "mike", "tom" };
4280//   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4281template <typename M>
4282inline internal::ContainsMatcher<M> Contains(M matcher) {
4283  return internal::ContainsMatcher<M>(matcher);
4284}
4285
4286// Matches an STL-style container or a native array that contains only
4287// elements matching the given value or matcher.
4288//
4289// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4290// the messages are different.
4291//
4292// Examples:
4293//   ::std::set<int> page_ids;
4294//   // Each(m) matches an empty container, regardless of what m is.
4295//   EXPECT_THAT(page_ids, Each(Eq(1)));
4296//   EXPECT_THAT(page_ids, Each(Eq(77)));
4297//
4298//   page_ids.insert(3);
4299//   EXPECT_THAT(page_ids, Each(Gt(0)));
4300//   EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4301//   page_ids.insert(1);
4302//   EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4303//
4304//   ::std::map<int, size_t> page_lengths;
4305//   page_lengths[1] = 100;
4306//   page_lengths[2] = 200;
4307//   page_lengths[3] = 300;
4308//   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4309//   EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4310//
4311//   const char* user_ids[] = { "joe", "mike", "tom" };
4312//   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4313template <typename M>
4314inline internal::EachMatcher<M> Each(M matcher) {
4315  return internal::EachMatcher<M>(matcher);
4316}
4317
4318// Key(inner_matcher) matches an std::pair whose 'first' field matches
4319// inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
4320// std::map that contains at least one element whose key is >= 5.
4321template <typename M>
4322inline internal::KeyMatcher<M> Key(M inner_matcher) {
4323  return internal::KeyMatcher<M>(inner_matcher);
4324}
4325
4326// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4327// matches first_matcher and whose 'second' field matches second_matcher.  For
4328// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4329// to match a std::map<int, string> that contains exactly one element whose key
4330// is >= 5 and whose value equals "foo".
4331template <typename FirstMatcher, typename SecondMatcher>
4332inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4333Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4334  return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4335      first_matcher, second_matcher);
4336}
4337
4338// Returns a predicate that is satisfied by anything that matches the
4339// given matcher.
4340template <typename M>
4341inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4342  return internal::MatcherAsPredicate<M>(matcher);
4343}
4344
4345// Returns true iff the value matches the matcher.
4346template <typename T, typename M>
4347inline bool Value(const T& value, M matcher) {
4348  return testing::Matches(matcher)(value);
4349}
4350
4351// Matches the value against the given matcher and explains the match
4352// result to listener.
4353template <typename T, typename M>
4354inline bool ExplainMatchResult(
4355    M matcher, const T& value, MatchResultListener* listener) {
4356  return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4357}
4358
4359#if GTEST_LANG_CXX11
4360// Define variadic matcher versions. They are overloaded in
4361// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4362template <typename... Args>
4363inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4364  return internal::AllOfMatcher<Args...>(matchers...);
4365}
4366
4367template <typename... Args>
4368inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4369  return internal::AnyOfMatcher<Args...>(matchers...);
4370}
4371
4372#endif  // GTEST_LANG_CXX11
4373
4374// AllArgs(m) is a synonym of m.  This is useful in
4375//
4376//   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4377//
4378// which is easier to read than
4379//
4380//   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4381template <typename InnerMatcher>
4382inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4383
4384// These macros allow using matchers to check values in Google Test
4385// tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4386// succeed iff the value matches the matcher.  If the assertion fails,
4387// the value and the description of the matcher will be printed.
4388#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4389    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4390#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4391    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4392
4393}  // namespace testing
4394
4395// Include any custom callback matchers added by the local installation.
4396// We must include this header at the end to make sure it can use the
4397// declarations from this file.
4398#include "gmock/internal/custom/gmock-matchers.h"
4399#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-more-actions.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some actions that depend on gmock-generated-actions.h.
35
36#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
37#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
38
39#include <algorithm>
40
41#include "gmock/gmock-generated-actions.h"
42
43namespace testing {
44namespace internal {
45
46// Implements the Invoke(f) action.  The template argument
47// FunctionImpl is the implementation type of f, which can be either a
48// function pointer or a functor.  Invoke(f) can be used as an
49// Action<F> as long as f's type is compatible with F (i.e. f can be
50// assigned to a tr1::function<F>).
51template <typename FunctionImpl>
52class InvokeAction {
53 public:
54  // The c'tor makes a copy of function_impl (either a function
55  // pointer or a functor).
56  explicit InvokeAction(FunctionImpl function_impl)
57      : function_impl_(function_impl) {}
58
59  template <typename Result, typename ArgumentTuple>
60  Result Perform(const ArgumentTuple& args) {
61    return InvokeHelper<Result, ArgumentTuple>::Invoke(function_impl_, args);
62  }
63
64 private:
65  FunctionImpl function_impl_;
66
67  GTEST_DISALLOW_ASSIGN_(InvokeAction);
68};
69
70// Implements the Invoke(object_ptr, &Class::Method) action.
71template <class Class, typename MethodPtr>
72class InvokeMethodAction {
73 public:
74  InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr)
75      : method_ptr_(method_ptr), obj_ptr_(obj_ptr) {}
76
77  template <typename Result, typename ArgumentTuple>
78  Result Perform(const ArgumentTuple& args) const {
79    return InvokeHelper<Result, ArgumentTuple>::InvokeMethod(
80        obj_ptr_, method_ptr_, args);
81  }
82
83 private:
84  // The order of these members matters.  Reversing the order can trigger
85  // warning C4121 in MSVC (see
86  // http://computer-programming-forum.com/7-vc.net/6fbc30265f860ad1.htm ).
87  const MethodPtr method_ptr_;
88  Class* const obj_ptr_;
89
90  GTEST_DISALLOW_ASSIGN_(InvokeMethodAction);
91};
92
93// An internal replacement for std::copy which mimics its behavior. This is
94// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996.
95// However Visual Studio 2010 and later do not honor #pragmas which disable that
96// warning.
97template<typename InputIterator, typename OutputIterator>
98inline OutputIterator CopyElements(InputIterator first,
99                                   InputIterator last,
100                                   OutputIterator output) {
101  for (; first != last; ++first, ++output) {
102    *output = *first;
103  }
104  return output;
105}
106
107}  // namespace internal
108
109// Various overloads for Invoke().
110
111// Creates an action that invokes 'function_impl' with the mock
112// function's arguments.
113template <typename FunctionImpl>
114PolymorphicAction<internal::InvokeAction<FunctionImpl> > Invoke(
115    FunctionImpl function_impl) {
116  return MakePolymorphicAction(
117      internal::InvokeAction<FunctionImpl>(function_impl));
118}
119
120// Creates an action that invokes the given method on the given object
121// with the mock function's arguments.
122template <class Class, typename MethodPtr>
123PolymorphicAction<internal::InvokeMethodAction<Class, MethodPtr> > Invoke(
124    Class* obj_ptr, MethodPtr method_ptr) {
125  return MakePolymorphicAction(
126      internal::InvokeMethodAction<Class, MethodPtr>(obj_ptr, method_ptr));
127}
128
129// WithoutArgs(inner_action) can be used in a mock function with a
130// non-empty argument list to perform inner_action, which takes no
131// argument.  In other words, it adapts an action accepting no
132// argument to one that accepts (and ignores) arguments.
133template <typename InnerAction>
134inline internal::WithArgsAction<InnerAction>
135WithoutArgs(const InnerAction& action) {
136  return internal::WithArgsAction<InnerAction>(action);
137}
138
139// WithArg<k>(an_action) creates an action that passes the k-th
140// (0-based) argument of the mock function to an_action and performs
141// it.  It adapts an action accepting one argument to one that accepts
142// multiple arguments.  For convenience, we also provide
143// WithArgs<k>(an_action) (defined below) as a synonym.
144template <int k, typename InnerAction>
145inline internal::WithArgsAction<InnerAction, k>
146WithArg(const InnerAction& action) {
147  return internal::WithArgsAction<InnerAction, k>(action);
148}
149
150// The ACTION*() macros trigger warning C4100 (unreferenced formal
151// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
152// the macro definition, as the warnings are generated when the macro
153// is expanded and macro expansion cannot contain #pragma.  Therefore
154// we suppress them here.
155#ifdef _MSC_VER
156# pragma warning(push)
157# pragma warning(disable:4100)
158#endif
159
160// Action ReturnArg<k>() returns the k-th argument of the mock function.
161ACTION_TEMPLATE(ReturnArg,
162                HAS_1_TEMPLATE_PARAMS(int, k),
163                AND_0_VALUE_PARAMS()) {
164  return ::testing::get<k>(args);
165}
166
167// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
168// mock function to *pointer.
169ACTION_TEMPLATE(SaveArg,
170                HAS_1_TEMPLATE_PARAMS(int, k),
171                AND_1_VALUE_PARAMS(pointer)) {
172  *pointer = ::testing::get<k>(args);
173}
174
175// Action SaveArgPointee<k>(pointer) saves the value pointed to
176// by the k-th (0-based) argument of the mock function to *pointer.
177ACTION_TEMPLATE(SaveArgPointee,
178                HAS_1_TEMPLATE_PARAMS(int, k),
179                AND_1_VALUE_PARAMS(pointer)) {
180  *pointer = *::testing::get<k>(args);
181}
182
183// Action SetArgReferee<k>(value) assigns 'value' to the variable
184// referenced by the k-th (0-based) argument of the mock function.
185ACTION_TEMPLATE(SetArgReferee,
186                HAS_1_TEMPLATE_PARAMS(int, k),
187                AND_1_VALUE_PARAMS(value)) {
188  typedef typename ::testing::tuple_element<k, args_type>::type argk_type;
189  // Ensures that argument #k is a reference.  If you get a compiler
190  // error on the next line, you are using SetArgReferee<k>(value) in
191  // a mock function whose k-th (0-based) argument is not a reference.
192  GTEST_COMPILE_ASSERT_(internal::is_reference<argk_type>::value,
193                        SetArgReferee_must_be_used_with_a_reference_argument);
194  ::testing::get<k>(args) = value;
195}
196
197// Action SetArrayArgument<k>(first, last) copies the elements in
198// source range [first, last) to the array pointed to by the k-th
199// (0-based) argument, which can be either a pointer or an
200// iterator. The action does not take ownership of the elements in the
201// source range.
202ACTION_TEMPLATE(SetArrayArgument,
203                HAS_1_TEMPLATE_PARAMS(int, k),
204                AND_2_VALUE_PARAMS(first, last)) {
205  // Visual Studio deprecates ::std::copy, so we use our own copy in that case.
206#ifdef _MSC_VER
207  internal::CopyElements(first, last, ::testing::get<k>(args));
208#else
209  ::std::copy(first, last, ::testing::get<k>(args));
210#endif
211}
212
213// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
214// function.
215ACTION_TEMPLATE(DeleteArg,
216                HAS_1_TEMPLATE_PARAMS(int, k),
217                AND_0_VALUE_PARAMS()) {
218  delete ::testing::get<k>(args);
219}
220
221// This action returns the value pointed to by 'pointer'.
222ACTION_P(ReturnPointee, pointer) { return *pointer; }
223
224// Action Throw(exception) can be used in a mock function of any type
225// to throw the given exception.  Any copyable value can be thrown.
226#if GTEST_HAS_EXCEPTIONS
227
228// Suppresses the 'unreachable code' warning that VC generates in opt modes.
229# ifdef _MSC_VER
230#  pragma warning(push)          // Saves the current warning state.
231#  pragma warning(disable:4702)  // Temporarily disables warning 4702.
232# endif
233ACTION_P(Throw, exception) { throw exception; }
234# ifdef _MSC_VER
235#  pragma warning(pop)           // Restores the warning state.
236# endif
237
238#endif  // GTEST_HAS_EXCEPTIONS
239
240#ifdef _MSC_VER
241# pragma warning(pop)
242#endif
243
244}  // namespace testing
245
246#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-more-matchers.h
r0r249096
1// Copyright 2013, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: marcus.boerger@google.com (Marcus Boerger)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some matchers that depend on gmock-generated-matchers.h.
35//
36// Note that tests are implemented in gmock-matchers_test.cc rather than
37// gmock-more-matchers-test.cc.
38
39#ifndef GMOCK_GMOCK_MORE_MATCHERS_H_
40#define GMOCK_GMOCK_MORE_MATCHERS_H_
41
42#include "gmock/gmock-generated-matchers.h"
43
44namespace testing {
45
46// Defines a matcher that matches an empty container. The container must
47// support both size() and empty(), which all STL-like containers provide.
48MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
49  if (arg.empty()) {
50    return true;
51  }
52  *result_listener << "whose size is " << arg.size();
53  return false;
54}
55
56}  // namespace testing
57
58#endif  // GMOCK_GMOCK_MORE_MATCHERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock-spec-builders.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements the ON_CALL() and EXPECT_CALL() macros.
35//
36// A user can use the ON_CALL() macro to specify the default action of
37// a mock method.  The syntax is:
38//
39//   ON_CALL(mock_object, Method(argument-matchers))
40//       .With(multi-argument-matcher)
41//       .WillByDefault(action);
42//
43//  where the .With() clause is optional.
44//
45// A user can use the EXPECT_CALL() macro to specify an expectation on
46// a mock method.  The syntax is:
47//
48//   EXPECT_CALL(mock_object, Method(argument-matchers))
49//       .With(multi-argument-matchers)
50//       .Times(cardinality)
51//       .InSequence(sequences)
52//       .After(expectations)
53//       .WillOnce(action)
54//       .WillRepeatedly(action)
55//       .RetiresOnSaturation();
56//
57// where all clauses are optional, and .InSequence()/.After()/
58// .WillOnce() can appear any number of times.
59
60#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
61#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62
63#include <map>
64#include <set>
65#include <sstream>
66#include <string>
67#include <vector>
68
69#if GTEST_HAS_EXCEPTIONS
70# include <stdexcept>  // NOLINT
71#endif
72
73#include "gmock/gmock-actions.h"
74#include "gmock/gmock-cardinalities.h"
75#include "gmock/gmock-matchers.h"
76#include "gmock/internal/gmock-internal-utils.h"
77#include "gmock/internal/gmock-port.h"
78#include "gtest/gtest.h"
79
80namespace testing {
81
82// An abstract handle of an expectation.
83class Expectation;
84
85// A set of expectation handles.
86class ExpectationSet;
87
88// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
89// and MUST NOT BE USED IN USER CODE!!!
90namespace internal {
91
92// Implements a mock function.
93template <typename F> class FunctionMocker;
94
95// Base class for expectations.
96class ExpectationBase;
97
98// Implements an expectation.
99template <typename F> class TypedExpectation;
100
101// Helper class for testing the Expectation class template.
102class ExpectationTester;
103
104// Base class for function mockers.
105template <typename F> class FunctionMockerBase;
106
107// Protects the mock object registry (in class Mock), all function
108// mockers, and all expectations.
109//
110// The reason we don't use more fine-grained protection is: when a
111// mock function Foo() is called, it needs to consult its expectations
112// to see which one should be picked.  If another thread is allowed to
113// call a mock function (either Foo() or a different one) at the same
114// time, it could affect the "retired" attributes of Foo()'s
115// expectations when InSequence() is used, and thus affect which
116// expectation gets picked.  Therefore, we sequence all mock function
117// calls to ensure the integrity of the mock objects' states.
118GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
119
120// Untyped base class for ActionResultHolder<R>.
121class UntypedActionResultHolderBase;
122
123// Abstract base class of FunctionMockerBase.  This is the
124// type-agnostic part of the function mocker interface.  Its pure
125// virtual methods are implemented by FunctionMockerBase.
126class GTEST_API_ UntypedFunctionMockerBase {
127 public:
128  UntypedFunctionMockerBase();
129  virtual ~UntypedFunctionMockerBase();
130
131  // Verifies that all expectations on this mock function have been
132  // satisfied.  Reports one or more Google Test non-fatal failures
133  // and returns false if not.
134  bool VerifyAndClearExpectationsLocked()
135      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
136
137  // Clears the ON_CALL()s set on this mock function.
138  virtual void ClearDefaultActionsLocked()
139      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
140
141  // In all of the following Untyped* functions, it's the caller's
142  // responsibility to guarantee the correctness of the arguments'
143  // types.
144
145  // Performs the default action with the given arguments and returns
146  // the action's result.  The call description string will be used in
147  // the error message to describe the call in the case the default
148  // action fails.
149  // L = *
150  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
151      const void* untyped_args,
152      const string& call_description) const = 0;
153
154  // Performs the given action with the given arguments and returns
155  // the action's result.
156  // L = *
157  virtual UntypedActionResultHolderBase* UntypedPerformAction(
158      const void* untyped_action,
159      const void* untyped_args) const = 0;
160
161  // Writes a message that the call is uninteresting (i.e. neither
162  // explicitly expected nor explicitly unexpected) to the given
163  // ostream.
164  virtual void UntypedDescribeUninterestingCall(
165      const void* untyped_args,
166      ::std::ostream* os) const
167          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
168
169  // Returns the expectation that matches the given function arguments
170  // (or NULL is there's no match); when a match is found,
171  // untyped_action is set to point to the action that should be
172  // performed (or NULL if the action is "do default"), and
173  // is_excessive is modified to indicate whether the call exceeds the
174  // expected number.
175  virtual const ExpectationBase* UntypedFindMatchingExpectation(
176      const void* untyped_args,
177      const void** untyped_action, bool* is_excessive,
178      ::std::ostream* what, ::std::ostream* why)
179          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
180
181  // Prints the given function arguments to the ostream.
182  virtual void UntypedPrintArgs(const void* untyped_args,
183                                ::std::ostream* os) const = 0;
184
185  // Sets the mock object this mock method belongs to, and registers
186  // this information in the global mock registry.  Will be called
187  // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
188  // method.
189  // TODO(wan@google.com): rename to SetAndRegisterOwner().
190  void RegisterOwner(const void* mock_obj)
191      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
192
193  // Sets the mock object this mock method belongs to, and sets the
194  // name of the mock function.  Will be called upon each invocation
195  // of this mock function.
196  void SetOwnerAndName(const void* mock_obj, const char* name)
197      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
198
199  // Returns the mock object this mock method belongs to.  Must be
200  // called after RegisterOwner() or SetOwnerAndName() has been
201  // called.
202  const void* MockObject() const
203      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
204
205  // Returns the name of this mock method.  Must be called after
206  // SetOwnerAndName() has been called.
207  const char* Name() const
208      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
209
210  // Returns the result of invoking this mock function with the given
211  // arguments.  This function can be safely called from multiple
212  // threads concurrently.  The caller is responsible for deleting the
213  // result.
214  UntypedActionResultHolderBase* UntypedInvokeWith(
215      const void* untyped_args)
216          GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
217
218 protected:
219  typedef std::vector<const void*> UntypedOnCallSpecs;
220
221  typedef std::vector<internal::linked_ptr<ExpectationBase> >
222  UntypedExpectations;
223
224  // Returns an Expectation object that references and co-owns exp,
225  // which must be an expectation on this mock function.
226  Expectation GetHandleOf(ExpectationBase* exp);
227
228  // Address of the mock object this mock method belongs to.  Only
229  // valid after this mock method has been called or
230  // ON_CALL/EXPECT_CALL has been invoked on it.
231  const void* mock_obj_;  // Protected by g_gmock_mutex.
232
233  // Name of the function being mocked.  Only valid after this mock
234  // method has been called.
235  const char* name_;  // Protected by g_gmock_mutex.
236
237  // All default action specs for this function mocker.
238  UntypedOnCallSpecs untyped_on_call_specs_;
239
240  // All expectations for this function mocker.
241  UntypedExpectations untyped_expectations_;
242};  // class UntypedFunctionMockerBase
243
244// Untyped base class for OnCallSpec<F>.
245class UntypedOnCallSpecBase {
246 public:
247  // The arguments are the location of the ON_CALL() statement.
248  UntypedOnCallSpecBase(const char* a_file, int a_line)
249      : file_(a_file), line_(a_line), last_clause_(kNone) {}
250
251  // Where in the source file was the default action spec defined?
252  const char* file() const { return file_; }
253  int line() const { return line_; }
254
255 protected:
256  // Gives each clause in the ON_CALL() statement a name.
257  enum Clause {
258    // Do not change the order of the enum members!  The run-time
259    // syntax checking relies on it.
260    kNone,
261    kWith,
262    kWillByDefault
263  };
264
265  // Asserts that the ON_CALL() statement has a certain property.
266  void AssertSpecProperty(bool property, const string& failure_message) const {
267    Assert(property, file_, line_, failure_message);
268  }
269
270  // Expects that the ON_CALL() statement has a certain property.
271  void ExpectSpecProperty(bool property, const string& failure_message) const {
272    Expect(property, file_, line_, failure_message);
273  }
274
275  const char* file_;
276  int line_;
277
278  // The last clause in the ON_CALL() statement as seen so far.
279  // Initially kNone and changes as the statement is parsed.
280  Clause last_clause_;
281};  // class UntypedOnCallSpecBase
282
283// This template class implements an ON_CALL spec.
284template <typename F>
285class OnCallSpec : public UntypedOnCallSpecBase {
286 public:
287  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
288  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
289
290  // Constructs an OnCallSpec object from the information inside
291  // the parenthesis of an ON_CALL() statement.
292  OnCallSpec(const char* a_file, int a_line,
293             const ArgumentMatcherTuple& matchers)
294      : UntypedOnCallSpecBase(a_file, a_line),
295        matchers_(matchers),
296        // By default, extra_matcher_ should match anything.  However,
297        // we cannot initialize it with _ as that triggers a compiler
298        // bug in Symbian's C++ compiler (cannot decide between two
299        // overloaded constructors of Matcher<const ArgumentTuple&>).
300        extra_matcher_(A<const ArgumentTuple&>()) {
301  }
302
303  // Implements the .With() clause.
304  OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
305    // Makes sure this is called at most once.
306    ExpectSpecProperty(last_clause_ < kWith,
307                       ".With() cannot appear "
308                       "more than once in an ON_CALL().");
309    last_clause_ = kWith;
310
311    extra_matcher_ = m;
312    return *this;
313  }
314
315  // Implements the .WillByDefault() clause.
316  OnCallSpec& WillByDefault(const Action<F>& action) {
317    ExpectSpecProperty(last_clause_ < kWillByDefault,
318                       ".WillByDefault() must appear "
319                       "exactly once in an ON_CALL().");
320    last_clause_ = kWillByDefault;
321
322    ExpectSpecProperty(!action.IsDoDefault(),
323                       "DoDefault() cannot be used in ON_CALL().");
324    action_ = action;
325    return *this;
326  }
327
328  // Returns true iff the given arguments match the matchers.
329  bool Matches(const ArgumentTuple& args) const {
330    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
331  }
332
333  // Returns the action specified by the user.
334  const Action<F>& GetAction() const {
335    AssertSpecProperty(last_clause_ == kWillByDefault,
336                       ".WillByDefault() must appear exactly "
337                       "once in an ON_CALL().");
338    return action_;
339  }
340
341 private:
342  // The information in statement
343  //
344  //   ON_CALL(mock_object, Method(matchers))
345  //       .With(multi-argument-matcher)
346  //       .WillByDefault(action);
347  //
348  // is recorded in the data members like this:
349  //
350  //   source file that contains the statement => file_
351  //   line number of the statement            => line_
352  //   matchers                                => matchers_
353  //   multi-argument-matcher                  => extra_matcher_
354  //   action                                  => action_
355  ArgumentMatcherTuple matchers_;
356  Matcher<const ArgumentTuple&> extra_matcher_;
357  Action<F> action_;
358};  // class OnCallSpec
359
360// Possible reactions on uninteresting calls.
361enum CallReaction {
362  kAllow,
363  kWarn,
364  kFail,
365  kDefault = kWarn  // By default, warn about uninteresting calls.
366};
367
368}  // namespace internal
369
370// Utilities for manipulating mock objects.
371class GTEST_API_ Mock {
372 public:
373  // The following public methods can be called concurrently.
374
375  // Tells Google Mock to ignore mock_obj when checking for leaked
376  // mock objects.
377  static void AllowLeak(const void* mock_obj)
378      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
379
380  // Verifies and clears all expectations on the given mock object.
381  // If the expectations aren't satisfied, generates one or more
382  // Google Test non-fatal failures and returns false.
383  static bool VerifyAndClearExpectations(void* mock_obj)
384      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
385
386  // Verifies all expectations on the given mock object and clears its
387  // default actions and expectations.  Returns true iff the
388  // verification was successful.
389  static bool VerifyAndClear(void* mock_obj)
390      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
391
392 private:
393  friend class internal::UntypedFunctionMockerBase;
394
395  // Needed for a function mocker to register itself (so that we know
396  // how to clear a mock object).
397  template <typename F>
398  friend class internal::FunctionMockerBase;
399
400  template <typename M>
401  friend class NiceMock;
402
403  template <typename M>
404  friend class NaggyMock;
405
406  template <typename M>
407  friend class StrictMock;
408
409  // Tells Google Mock to allow uninteresting calls on the given mock
410  // object.
411  static void AllowUninterestingCalls(const void* mock_obj)
412      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
413
414  // Tells Google Mock to warn the user about uninteresting calls on
415  // the given mock object.
416  static void WarnUninterestingCalls(const void* mock_obj)
417      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
418
419  // Tells Google Mock to fail uninteresting calls on the given mock
420  // object.
421  static void FailUninterestingCalls(const void* mock_obj)
422      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
423
424  // Tells Google Mock the given mock object is being destroyed and
425  // its entry in the call-reaction table should be removed.
426  static void UnregisterCallReaction(const void* mock_obj)
427      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
428
429  // Returns the reaction Google Mock will have on uninteresting calls
430  // made on the given mock object.
431  static internal::CallReaction GetReactionOnUninterestingCalls(
432      const void* mock_obj)
433          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
434
435  // Verifies that all expectations on the given mock object have been
436  // satisfied.  Reports one or more Google Test non-fatal failures
437  // and returns false if not.
438  static bool VerifyAndClearExpectationsLocked(void* mock_obj)
439      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
440
441  // Clears all ON_CALL()s set on the given mock object.
442  static void ClearDefaultActionsLocked(void* mock_obj)
443      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
444
445  // Registers a mock object and a mock method it owns.
446  static void Register(
447      const void* mock_obj,
448      internal::UntypedFunctionMockerBase* mocker)
449          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
450
451  // Tells Google Mock where in the source code mock_obj is used in an
452  // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
453  // information helps the user identify which object it is.
454  static void RegisterUseByOnCallOrExpectCall(
455      const void* mock_obj, const char* file, int line)
456          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
457
458  // Unregisters a mock method; removes the owning mock object from
459  // the registry when the last mock method associated with it has
460  // been unregistered.  This is called only in the destructor of
461  // FunctionMockerBase.
462  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
463      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
464};  // class Mock
465
466// An abstract handle of an expectation.  Useful in the .After()
467// clause of EXPECT_CALL() for setting the (partial) order of
468// expectations.  The syntax:
469//
470//   Expectation e1 = EXPECT_CALL(...)...;
471//   EXPECT_CALL(...).After(e1)...;
472//
473// sets two expectations where the latter can only be matched after
474// the former has been satisfied.
475//
476// Notes:
477//   - This class is copyable and has value semantics.
478//   - Constness is shallow: a const Expectation object itself cannot
479//     be modified, but the mutable methods of the ExpectationBase
480//     object it references can be called via expectation_base().
481//   - The constructors and destructor are defined out-of-line because
482//     the Symbian WINSCW compiler wants to otherwise instantiate them
483//     when it sees this class definition, at which point it doesn't have
484//     ExpectationBase available yet, leading to incorrect destruction
485//     in the linked_ptr (or compilation errors if using a checking
486//     linked_ptr).
487class GTEST_API_ Expectation {
488 public:
489  // Constructs a null object that doesn't reference any expectation.
490  Expectation();
491
492  ~Expectation();
493
494  // This single-argument ctor must not be explicit, in order to support the
495  //   Expectation e = EXPECT_CALL(...);
496  // syntax.
497  //
498  // A TypedExpectation object stores its pre-requisites as
499  // Expectation objects, and needs to call the non-const Retire()
500  // method on the ExpectationBase objects they reference.  Therefore
501  // Expectation must receive a *non-const* reference to the
502  // ExpectationBase object.
503  Expectation(internal::ExpectationBase& exp);  // NOLINT
504
505  // The compiler-generated copy ctor and operator= work exactly as
506  // intended, so we don't need to define our own.
507
508  // Returns true iff rhs references the same expectation as this object does.
509  bool operator==(const Expectation& rhs) const {
510    return expectation_base_ == rhs.expectation_base_;
511  }
512
513  bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
514
515 private:
516  friend class ExpectationSet;
517  friend class Sequence;
518  friend class ::testing::internal::ExpectationBase;
519  friend class ::testing::internal::UntypedFunctionMockerBase;
520
521  template <typename F>
522  friend class ::testing::internal::FunctionMockerBase;
523
524  template <typename F>
525  friend class ::testing::internal::TypedExpectation;
526
527  // This comparator is needed for putting Expectation objects into a set.
528  class Less {
529   public:
530    bool operator()(const Expectation& lhs, const Expectation& rhs) const {
531      return lhs.expectation_base_.get() < rhs.expectation_base_.get();
532    }
533  };
534
535  typedef ::std::set<Expectation, Less> Set;
536
537  Expectation(
538      const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
539
540  // Returns the expectation this object references.
541  const internal::linked_ptr<internal::ExpectationBase>&
542  expectation_base() const {
543    return expectation_base_;
544  }
545
546  // A linked_ptr that co-owns the expectation this handle references.
547  internal::linked_ptr<internal::ExpectationBase> expectation_base_;
548};
549
550// A set of expectation handles.  Useful in the .After() clause of
551// EXPECT_CALL() for setting the (partial) order of expectations.  The
552// syntax:
553//
554//   ExpectationSet es;
555//   es += EXPECT_CALL(...)...;
556//   es += EXPECT_CALL(...)...;
557//   EXPECT_CALL(...).After(es)...;
558//
559// sets three expectations where the last one can only be matched
560// after the first two have both been satisfied.
561//
562// This class is copyable and has value semantics.
563class ExpectationSet {
564 public:
565  // A bidirectional iterator that can read a const element in the set.
566  typedef Expectation::Set::const_iterator const_iterator;
567
568  // An object stored in the set.  This is an alias of Expectation.
569  typedef Expectation::Set::value_type value_type;
570
571  // Constructs an empty set.
572  ExpectationSet() {}
573
574  // This single-argument ctor must not be explicit, in order to support the
575  //   ExpectationSet es = EXPECT_CALL(...);
576  // syntax.
577  ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT
578    *this += Expectation(exp);
579  }
580
581  // This single-argument ctor implements implicit conversion from
582  // Expectation and thus must not be explicit.  This allows either an
583  // Expectation or an ExpectationSet to be used in .After().
584  ExpectationSet(const Expectation& e) {  // NOLINT
585    *this += e;
586  }
587
588  // The compiler-generator ctor and operator= works exactly as
589  // intended, so we don't need to define our own.
590
591  // Returns true iff rhs contains the same set of Expectation objects
592  // as this does.
593  bool operator==(const ExpectationSet& rhs) const {
594    return expectations_ == rhs.expectations_;
595  }
596
597  bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
598
599  // Implements the syntax
600  //   expectation_set += EXPECT_CALL(...);
601  ExpectationSet& operator+=(const Expectation& e) {
602    expectations_.insert(e);
603    return *this;
604  }
605
606  int size() const { return static_cast<int>(expectations_.size()); }
607
608  const_iterator begin() const { return expectations_.begin(); }
609  const_iterator end() const { return expectations_.end(); }
610
611 private:
612  Expectation::Set expectations_;
613};
614
615
616// Sequence objects are used by a user to specify the relative order
617// in which the expectations should match.  They are copyable (we rely
618// on the compiler-defined copy constructor and assignment operator).
619class GTEST_API_ Sequence {
620 public:
621  // Constructs an empty sequence.
622  Sequence() : last_expectation_(new Expectation) {}
623
624  // Adds an expectation to this sequence.  The caller must ensure
625  // that no other thread is accessing this Sequence object.
626  void AddExpectation(const Expectation& expectation) const;
627
628 private:
629  // The last expectation in this sequence.  We use a linked_ptr here
630  // because Sequence objects are copyable and we want the copies to
631  // be aliases.  The linked_ptr allows the copies to co-own and share
632  // the same Expectation object.
633  internal::linked_ptr<Expectation> last_expectation_;
634};  // class Sequence
635
636// An object of this type causes all EXPECT_CALL() statements
637// encountered in its scope to be put in an anonymous sequence.  The
638// work is done in the constructor and destructor.  You should only
639// create an InSequence object on the stack.
640//
641// The sole purpose for this class is to support easy definition of
642// sequential expectations, e.g.
643//
644//   {
645//     InSequence dummy;  // The name of the object doesn't matter.
646//
647//     // The following expectations must match in the order they appear.
648//     EXPECT_CALL(a, Bar())...;
649//     EXPECT_CALL(a, Baz())...;
650//     ...
651//     EXPECT_CALL(b, Xyz())...;
652//   }
653//
654// You can create InSequence objects in multiple threads, as long as
655// they are used to affect different mock objects.  The idea is that
656// each thread can create and set up its own mocks as if it's the only
657// thread.  However, for clarity of your tests we recommend you to set
658// up mocks in the main thread unless you have a good reason not to do
659// so.
660class GTEST_API_ InSequence {
661 public:
662  InSequence();
663  ~InSequence();
664 private:
665  bool sequence_created_;
666
667  GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
668} GTEST_ATTRIBUTE_UNUSED_;
669
670namespace internal {
671
672// Points to the implicit sequence introduced by a living InSequence
673// object (if any) in the current thread or NULL.
674GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
675
676// Base class for implementing expectations.
677//
678// There are two reasons for having a type-agnostic base class for
679// Expectation:
680//
681//   1. We need to store collections of expectations of different
682//   types (e.g. all pre-requisites of a particular expectation, all
683//   expectations in a sequence).  Therefore these expectation objects
684//   must share a common base class.
685//
686//   2. We can avoid binary code bloat by moving methods not depending
687//   on the template argument of Expectation to the base class.
688//
689// This class is internal and mustn't be used by user code directly.
690class GTEST_API_ ExpectationBase {
691 public:
692  // source_text is the EXPECT_CALL(...) source that created this Expectation.
693  ExpectationBase(const char* file, int line, const string& source_text);
694
695  virtual ~ExpectationBase();
696
697  // Where in the source file was the expectation spec defined?
698  const char* file() const { return file_; }
699  int line() const { return line_; }
700  const char* source_text() const { return source_text_.c_str(); }
701  // Returns the cardinality specified in the expectation spec.
702  const Cardinality& cardinality() const { return cardinality_; }
703
704  // Describes the source file location of this expectation.
705  void DescribeLocationTo(::std::ostream* os) const {
706    *os << FormatFileLocation(file(), line()) << " ";
707  }
708
709  // Describes how many times a function call matching this
710  // expectation has occurred.
711  void DescribeCallCountTo(::std::ostream* os) const
712      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
713
714  // If this mock method has an extra matcher (i.e. .With(matcher)),
715  // describes it to the ostream.
716  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
717
718 protected:
719  friend class ::testing::Expectation;
720  friend class UntypedFunctionMockerBase;
721
722  enum Clause {
723    // Don't change the order of the enum members!
724    kNone,
725    kWith,
726    kTimes,
727    kInSequence,
728    kAfter,
729    kWillOnce,
730    kWillRepeatedly,
731    kRetiresOnSaturation
732  };
733
734  typedef std::vector<const void*> UntypedActions;
735
736  // Returns an Expectation object that references and co-owns this
737  // expectation.
738  virtual Expectation GetHandle() = 0;
739
740  // Asserts that the EXPECT_CALL() statement has the given property.
741  void AssertSpecProperty(bool property, const string& failure_message) const {
742    Assert(property, file_, line_, failure_message);
743  }
744
745  // Expects that the EXPECT_CALL() statement has the given property.
746  void ExpectSpecProperty(bool property, const string& failure_message) const {
747    Expect(property, file_, line_, failure_message);
748  }
749
750  // Explicitly specifies the cardinality of this expectation.  Used
751  // by the subclasses to implement the .Times() clause.
752  void SpecifyCardinality(const Cardinality& cardinality);
753
754  // Returns true iff the user specified the cardinality explicitly
755  // using a .Times().
756  bool cardinality_specified() const { return cardinality_specified_; }
757
758  // Sets the cardinality of this expectation spec.
759  void set_cardinality(const Cardinality& a_cardinality) {
760    cardinality_ = a_cardinality;
761  }
762
763  // The following group of methods should only be called after the
764  // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
765  // the current thread.
766
767  // Retires all pre-requisites of this expectation.
768  void RetireAllPreRequisites()
769      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
770
771  // Returns true iff this expectation is retired.
772  bool is_retired() const
773      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
774    g_gmock_mutex.AssertHeld();
775    return retired_;
776  }
777
778  // Retires this expectation.
779  void Retire()
780      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
781    g_gmock_mutex.AssertHeld();
782    retired_ = true;
783  }
784
785  // Returns true iff this expectation is satisfied.
786  bool IsSatisfied() const
787      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
788    g_gmock_mutex.AssertHeld();
789    return cardinality().IsSatisfiedByCallCount(call_count_);
790  }
791
792  // Returns true iff this expectation is saturated.
793  bool IsSaturated() const
794      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
795    g_gmock_mutex.AssertHeld();
796    return cardinality().IsSaturatedByCallCount(call_count_);
797  }
798
799  // Returns true iff this expectation is over-saturated.
800  bool IsOverSaturated() const
801      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
802    g_gmock_mutex.AssertHeld();
803    return cardinality().IsOverSaturatedByCallCount(call_count_);
804  }
805
806  // Returns true iff all pre-requisites of this expectation are satisfied.
807  bool AllPrerequisitesAreSatisfied() const
808      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
809
810  // Adds unsatisfied pre-requisites of this expectation to 'result'.
811  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
812      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
813
814  // Returns the number this expectation has been invoked.
815  int call_count() const
816      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
817    g_gmock_mutex.AssertHeld();
818    return call_count_;
819  }
820
821  // Increments the number this expectation has been invoked.
822  void IncrementCallCount()
823      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
824    g_gmock_mutex.AssertHeld();
825    call_count_++;
826  }
827
828  // Checks the action count (i.e. the number of WillOnce() and
829  // WillRepeatedly() clauses) against the cardinality if this hasn't
830  // been done before.  Prints a warning if there are too many or too
831  // few actions.
832  void CheckActionCountIfNotDone() const
833      GTEST_LOCK_EXCLUDED_(mutex_);
834
835  friend class ::testing::Sequence;
836  friend class ::testing::internal::ExpectationTester;
837
838  template <typename Function>
839  friend class TypedExpectation;
840
841  // Implements the .Times() clause.
842  void UntypedTimes(const Cardinality& a_cardinality);
843
844  // This group of fields are part of the spec and won't change after
845  // an EXPECT_CALL() statement finishes.
846  const char* file_;          // The file that contains the expectation.
847  int line_;                  // The line number of the expectation.
848  const string source_text_;  // The EXPECT_CALL(...) source text.
849  // True iff the cardinality is specified explicitly.
850  bool cardinality_specified_;
851  Cardinality cardinality_;            // The cardinality of the expectation.
852  // The immediate pre-requisites (i.e. expectations that must be
853  // satisfied before this expectation can be matched) of this
854  // expectation.  We use linked_ptr in the set because we want an
855  // Expectation object to be co-owned by its FunctionMocker and its
856  // successors.  This allows multiple mock objects to be deleted at
857  // different times.
858  ExpectationSet immediate_prerequisites_;
859
860  // This group of fields are the current state of the expectation,
861  // and can change as the mock function is called.
862  int call_count_;  // How many times this expectation has been invoked.
863  bool retired_;    // True iff this expectation has retired.
864  UntypedActions untyped_actions_;
865  bool extra_matcher_specified_;
866  bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.
867  bool retires_on_saturation_;
868  Clause last_clause_;
869  mutable bool action_count_checked_;  // Under mutex_.
870  mutable Mutex mutex_;  // Protects action_count_checked_.
871
872  GTEST_DISALLOW_ASSIGN_(ExpectationBase);
873};  // class ExpectationBase
874
875// Impements an expectation for the given function type.
876template <typename F>
877class TypedExpectation : public ExpectationBase {
878 public:
879  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
880  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
881  typedef typename Function<F>::Result Result;
882
883  TypedExpectation(FunctionMockerBase<F>* owner,
884                   const char* a_file, int a_line, const string& a_source_text,
885                   const ArgumentMatcherTuple& m)
886      : ExpectationBase(a_file, a_line, a_source_text),
887        owner_(owner),
888        matchers_(m),
889        // By default, extra_matcher_ should match anything.  However,
890        // we cannot initialize it with _ as that triggers a compiler
891        // bug in Symbian's C++ compiler (cannot decide between two
892        // overloaded constructors of Matcher<const ArgumentTuple&>).
893        extra_matcher_(A<const ArgumentTuple&>()),
894        repeated_action_(DoDefault()) {}
895
896  virtual ~TypedExpectation() {
897    // Check the validity of the action count if it hasn't been done
898    // yet (for example, if the expectation was never used).
899    CheckActionCountIfNotDone();
900    for (UntypedActions::const_iterator it = untyped_actions_.begin();
901         it != untyped_actions_.end(); ++it) {
902      delete static_cast<const Action<F>*>(*it);
903    }
904  }
905
906  // Implements the .With() clause.
907  TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
908    if (last_clause_ == kWith) {
909      ExpectSpecProperty(false,
910                         ".With() cannot appear "
911                         "more than once in an EXPECT_CALL().");
912    } else {
913      ExpectSpecProperty(last_clause_ < kWith,
914                         ".With() must be the first "
915                         "clause in an EXPECT_CALL().");
916    }
917    last_clause_ = kWith;
918
919    extra_matcher_ = m;
920    extra_matcher_specified_ = true;
921    return *this;
922  }
923
924  // Implements the .Times() clause.
925  TypedExpectation& Times(const Cardinality& a_cardinality) {
926    ExpectationBase::UntypedTimes(a_cardinality);
927    return *this;
928  }
929
930  // Implements the .Times() clause.
931  TypedExpectation& Times(int n) {
932    return Times(Exactly(n));
933  }
934
935  // Implements the .InSequence() clause.
936  TypedExpectation& InSequence(const Sequence& s) {
937    ExpectSpecProperty(last_clause_ <= kInSequence,
938                       ".InSequence() cannot appear after .After(),"
939                       " .WillOnce(), .WillRepeatedly(), or "
940                       ".RetiresOnSaturation().");
941    last_clause_ = kInSequence;
942
943    s.AddExpectation(GetHandle());
944    return *this;
945  }
946  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
947    return InSequence(s1).InSequence(s2);
948  }
949  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
950                               const Sequence& s3) {
951    return InSequence(s1, s2).InSequence(s3);
952  }
953  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
954                               const Sequence& s3, const Sequence& s4) {
955    return InSequence(s1, s2, s3).InSequence(s4);
956  }
957  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
958                               const Sequence& s3, const Sequence& s4,
959                               const Sequence& s5) {
960    return InSequence(s1, s2, s3, s4).InSequence(s5);
961  }
962
963  // Implements that .After() clause.
964  TypedExpectation& After(const ExpectationSet& s) {
965    ExpectSpecProperty(last_clause_ <= kAfter,
966                       ".After() cannot appear after .WillOnce(),"
967                       " .WillRepeatedly(), or "
968                       ".RetiresOnSaturation().");
969    last_clause_ = kAfter;
970
971    for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
972      immediate_prerequisites_ += *it;
973    }
974    return *this;
975  }
976  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
977    return After(s1).After(s2);
978  }
979  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
980                          const ExpectationSet& s3) {
981    return After(s1, s2).After(s3);
982  }
983  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
984                          const ExpectationSet& s3, const ExpectationSet& s4) {
985    return After(s1, s2, s3).After(s4);
986  }
987  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
988                          const ExpectationSet& s3, const ExpectationSet& s4,
989                          const ExpectationSet& s5) {
990    return After(s1, s2, s3, s4).After(s5);
991  }
992
993  // Implements the .WillOnce() clause.
994  TypedExpectation& WillOnce(const Action<F>& action) {
995    ExpectSpecProperty(last_clause_ <= kWillOnce,
996                       ".WillOnce() cannot appear after "
997                       ".WillRepeatedly() or .RetiresOnSaturation().");
998    last_clause_ = kWillOnce;
999
1000    untyped_actions_.push_back(new Action<F>(action));
1001    if (!cardinality_specified()) {
1002      set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1003    }
1004    return *this;
1005  }
1006
1007  // Implements the .WillRepeatedly() clause.
1008  TypedExpectation& WillRepeatedly(const Action<F>& action) {
1009    if (last_clause_ == kWillRepeatedly) {
1010      ExpectSpecProperty(false,
1011                         ".WillRepeatedly() cannot appear "
1012                         "more than once in an EXPECT_CALL().");
1013    } else {
1014      ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1015                         ".WillRepeatedly() cannot appear "
1016                         "after .RetiresOnSaturation().");
1017    }
1018    last_clause_ = kWillRepeatedly;
1019    repeated_action_specified_ = true;
1020
1021    repeated_action_ = action;
1022    if (!cardinality_specified()) {
1023      set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1024    }
1025
1026    // Now that no more action clauses can be specified, we check
1027    // whether their count makes sense.
1028    CheckActionCountIfNotDone();
1029    return *this;
1030  }
1031
1032  // Implements the .RetiresOnSaturation() clause.
1033  TypedExpectation& RetiresOnSaturation() {
1034    ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1035                       ".RetiresOnSaturation() cannot appear "
1036                       "more than once.");
1037    last_clause_ = kRetiresOnSaturation;
1038    retires_on_saturation_ = true;
1039
1040    // Now that no more action clauses can be specified, we check
1041    // whether their count makes sense.
1042    CheckActionCountIfNotDone();
1043    return *this;
1044  }
1045
1046  // Returns the matchers for the arguments as specified inside the
1047  // EXPECT_CALL() macro.
1048  const ArgumentMatcherTuple& matchers() const {
1049    return matchers_;
1050  }
1051
1052  // Returns the matcher specified by the .With() clause.
1053  const Matcher<const ArgumentTuple&>& extra_matcher() const {
1054    return extra_matcher_;
1055  }
1056
1057  // Returns the action specified by the .WillRepeatedly() clause.
1058  const Action<F>& repeated_action() const { return repeated_action_; }
1059
1060  // If this mock method has an extra matcher (i.e. .With(matcher)),
1061  // describes it to the ostream.
1062  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
1063    if (extra_matcher_specified_) {
1064      *os << "    Expected args: ";
1065      extra_matcher_.DescribeTo(os);
1066      *os << "\n";
1067    }
1068  }
1069
1070 private:
1071  template <typename Function>
1072  friend class FunctionMockerBase;
1073
1074  // Returns an Expectation object that references and co-owns this
1075  // expectation.
1076  virtual Expectation GetHandle() {
1077    return owner_->GetHandleOf(this);
1078  }
1079
1080  // The following methods will be called only after the EXPECT_CALL()
1081  // statement finishes and when the current thread holds
1082  // g_gmock_mutex.
1083
1084  // Returns true iff this expectation matches the given arguments.
1085  bool Matches(const ArgumentTuple& args) const
1086      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1087    g_gmock_mutex.AssertHeld();
1088    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1089  }
1090
1091  // Returns true iff this expectation should handle the given arguments.
1092  bool ShouldHandleArguments(const ArgumentTuple& args) const
1093      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1094    g_gmock_mutex.AssertHeld();
1095
1096    // In case the action count wasn't checked when the expectation
1097    // was defined (e.g. if this expectation has no WillRepeatedly()
1098    // or RetiresOnSaturation() clause), we check it when the
1099    // expectation is used for the first time.
1100    CheckActionCountIfNotDone();
1101    return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1102  }
1103
1104  // Describes the result of matching the arguments against this
1105  // expectation to the given ostream.
1106  void ExplainMatchResultTo(
1107      const ArgumentTuple& args,
1108      ::std::ostream* os) const
1109          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1110    g_gmock_mutex.AssertHeld();
1111
1112    if (is_retired()) {
1113      *os << "         Expected: the expectation is active\n"
1114          << "           Actual: it is retired\n";
1115    } else if (!Matches(args)) {
1116      if (!TupleMatches(matchers_, args)) {
1117        ExplainMatchFailureTupleTo(matchers_, args, os);
1118      }
1119      StringMatchResultListener listener;
1120      if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1121        *os << "    Expected args: ";
1122        extra_matcher_.DescribeTo(os);
1123        *os << "\n           Actual: don't match";
1124
1125        internal::PrintIfNotEmpty(listener.str(), os);
1126        *os << "\n";
1127      }
1128    } else if (!AllPrerequisitesAreSatisfied()) {
1129      *os << "         Expected: all pre-requisites are satisfied\n"
1130          << "           Actual: the following immediate pre-requisites "
1131          << "are not satisfied:\n";
1132      ExpectationSet unsatisfied_prereqs;
1133      FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1134      int i = 0;
1135      for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1136           it != unsatisfied_prereqs.end(); ++it) {
1137        it->expectation_base()->DescribeLocationTo(os);
1138        *os << "pre-requisite #" << i++ << "\n";
1139      }
1140      *os << "                   (end of pre-requisites)\n";
1141    } else {
1142      // This line is here just for completeness' sake.  It will never
1143      // be executed as currently the ExplainMatchResultTo() function
1144      // is called only when the mock function call does NOT match the
1145      // expectation.
1146      *os << "The call matches the expectation.\n";
1147    }
1148  }
1149
1150  // Returns the action that should be taken for the current invocation.
1151  const Action<F>& GetCurrentAction(
1152      const FunctionMockerBase<F>* mocker,
1153      const ArgumentTuple& args) const
1154          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1155    g_gmock_mutex.AssertHeld();
1156    const int count = call_count();
1157    Assert(count >= 1, __FILE__, __LINE__,
1158           "call_count() is <= 0 when GetCurrentAction() is "
1159           "called - this should never happen.");
1160
1161    const int action_count = static_cast<int>(untyped_actions_.size());
1162    if (action_count > 0 && !repeated_action_specified_ &&
1163        count > action_count) {
1164      // If there is at least one WillOnce() and no WillRepeatedly(),
1165      // we warn the user when the WillOnce() clauses ran out.
1166      ::std::stringstream ss;
1167      DescribeLocationTo(&ss);
1168      ss << "Actions ran out in " << source_text() << "...\n"
1169         << "Called " << count << " times, but only "
1170         << action_count << " WillOnce()"
1171         << (action_count == 1 ? " is" : "s are") << " specified - ";
1172      mocker->DescribeDefaultActionTo(args, &ss);
1173      Log(kWarning, ss.str(), 1);
1174    }
1175
1176    return count <= action_count ?
1177        *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1178        repeated_action();
1179  }
1180
1181  // Given the arguments of a mock function call, if the call will
1182  // over-saturate this expectation, returns the default action;
1183  // otherwise, returns the next action in this expectation.  Also
1184  // describes *what* happened to 'what', and explains *why* Google
1185  // Mock does it to 'why'.  This method is not const as it calls
1186  // IncrementCallCount().  A return value of NULL means the default
1187  // action.
1188  const Action<F>* GetActionForArguments(
1189      const FunctionMockerBase<F>* mocker,
1190      const ArgumentTuple& args,
1191      ::std::ostream* what,
1192      ::std::ostream* why)
1193          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1194    g_gmock_mutex.AssertHeld();
1195    if (IsSaturated()) {
1196      // We have an excessive call.
1197      IncrementCallCount();
1198      *what << "Mock function called more times than expected - ";
1199      mocker->DescribeDefaultActionTo(args, what);
1200      DescribeCallCountTo(why);
1201
1202      // TODO(wan@google.com): allow the user to control whether
1203      // unexpected calls should fail immediately or continue using a
1204      // flag --gmock_unexpected_calls_are_fatal.
1205      return NULL;
1206    }
1207
1208    IncrementCallCount();
1209    RetireAllPreRequisites();
1210
1211    if (retires_on_saturation_ && IsSaturated()) {
1212      Retire();
1213    }
1214
1215    // Must be done after IncrementCount()!
1216    *what << "Mock function call matches " << source_text() <<"...\n";
1217    return &(GetCurrentAction(mocker, args));
1218  }
1219
1220  // All the fields below won't change once the EXPECT_CALL()
1221  // statement finishes.
1222  FunctionMockerBase<F>* const owner_;
1223  ArgumentMatcherTuple matchers_;
1224  Matcher<const ArgumentTuple&> extra_matcher_;
1225  Action<F> repeated_action_;
1226
1227  GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1228};  // class TypedExpectation
1229
1230// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1231// specifying the default behavior of, or expectation on, a mock
1232// function.
1233
1234// Note: class MockSpec really belongs to the ::testing namespace.
1235// However if we define it in ::testing, MSVC will complain when
1236// classes in ::testing::internal declare it as a friend class
1237// template.  To workaround this compiler bug, we define MockSpec in
1238// ::testing::internal and import it into ::testing.
1239
1240// Logs a message including file and line number information.
1241GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1242                                const char* file, int line,
1243                                const string& message);
1244
1245template <typename F>
1246class MockSpec {
1247 public:
1248  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1249  typedef typename internal::Function<F>::ArgumentMatcherTuple
1250      ArgumentMatcherTuple;
1251
1252  // Constructs a MockSpec object, given the function mocker object
1253  // that the spec is associated with.
1254  explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1255      : function_mocker_(function_mocker) {}
1256
1257  // Adds a new default action spec to the function mocker and returns
1258  // the newly created spec.
1259  internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1260      const char* file, int line, const char* obj, const char* call) {
1261    LogWithLocation(internal::kInfo, file, line,
1262        string("ON_CALL(") + obj + ", " + call + ") invoked");
1263    return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1264  }
1265
1266  // Adds a new expectation spec to the function mocker and returns
1267  // the newly created spec.
1268  internal::TypedExpectation<F>& InternalExpectedAt(
1269      const char* file, int line, const char* obj, const char* call) {
1270    const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
1271    LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1272    return function_mocker_->AddNewExpectation(
1273        file, line, source_text, matchers_);
1274  }
1275
1276 private:
1277  template <typename Function>
1278  friend class internal::FunctionMocker;
1279
1280  void SetMatchers(const ArgumentMatcherTuple& matchers) {
1281    matchers_ = matchers;
1282  }
1283
1284  // The function mocker that owns this spec.
1285  internal::FunctionMockerBase<F>* const function_mocker_;
1286  // The argument matchers specified in the spec.
1287  ArgumentMatcherTuple matchers_;
1288
1289  GTEST_DISALLOW_ASSIGN_(MockSpec);
1290};  // class MockSpec
1291
1292// Wrapper type for generically holding an ordinary value or lvalue reference.
1293// If T is not a reference type, it must be copyable or movable.
1294// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1295// T is a move-only value type (which means that it will always be copyable
1296// if the current platform does not support move semantics).
1297//
1298// The primary template defines handling for values, but function header
1299// comments describe the contract for the whole template (including
1300// specializations).
1301template <typename T>
1302class ReferenceOrValueWrapper {
1303 public:
1304  // Constructs a wrapper from the given value/reference.
1305  explicit ReferenceOrValueWrapper(T value)
1306      : value_(::testing::internal::move(value)) {
1307  }
1308
1309  // Unwraps and returns the underlying value/reference, exactly as
1310  // originally passed. The behavior of calling this more than once on
1311  // the same object is unspecified.
1312  T Unwrap() { return ::testing::internal::move(value_); }
1313
1314  // Provides nondestructive access to the underlying value/reference.
1315  // Always returns a const reference (more precisely,
1316  // const RemoveReference<T>&). The behavior of calling this after
1317  // calling Unwrap on the same object is unspecified.
1318  const T& Peek() const {
1319    return value_;
1320  }
1321
1322 private:
1323  T value_;
1324};
1325
1326// Specialization for lvalue reference types. See primary template
1327// for documentation.
1328template <typename T>
1329class ReferenceOrValueWrapper<T&> {
1330 public:
1331  // Workaround for debatable pass-by-reference lint warning (c-library-team
1332  // policy precludes NOLINT in this context)
1333  typedef T& reference;
1334  explicit ReferenceOrValueWrapper(reference ref)
1335      : value_ptr_(&ref) {}
1336  T& Unwrap() { return *value_ptr_; }
1337  const T& Peek() const { return *value_ptr_; }
1338
1339 private:
1340  T* value_ptr_;
1341};
1342
1343// MSVC warns about using 'this' in base member initializer list, so
1344// we need to temporarily disable the warning.  We have to do it for
1345// the entire class to suppress the warning, even though it's about
1346// the constructor only.
1347
1348#ifdef _MSC_VER
1349# pragma warning(push)          // Saves the current warning state.
1350# pragma warning(disable:4355)  // Temporarily disables warning 4355.
1351#endif  // _MSV_VER
1352
1353// C++ treats the void type specially.  For example, you cannot define
1354// a void-typed variable or pass a void value to a function.
1355// ActionResultHolder<T> holds a value of type T, where T must be a
1356// copyable type or void (T doesn't need to be default-constructable).
1357// It hides the syntactic difference between void and other types, and
1358// is used to unify the code for invoking both void-returning and
1359// non-void-returning mock functions.
1360
1361// Untyped base class for ActionResultHolder<T>.
1362class UntypedActionResultHolderBase {
1363 public:
1364  virtual ~UntypedActionResultHolderBase() {}
1365
1366  // Prints the held value as an action's result to os.
1367  virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1368};
1369
1370// This generic definition is used when T is not void.
1371template <typename T>
1372class ActionResultHolder : public UntypedActionResultHolderBase {
1373 public:
1374  // Returns the held value. Must not be called more than once.
1375  T Unwrap() {
1376    return result_.Unwrap();
1377  }
1378
1379  // Prints the held value as an action's result to os.
1380  virtual void PrintAsActionResult(::std::ostream* os) const {
1381    *os << "\n          Returns: ";
1382    // T may be a reference type, so we don't use UniversalPrint().
1383    UniversalPrinter<T>::Print(result_.Peek(), os);
1384  }
1385
1386  // Performs the given mock function's default action and returns the
1387  // result in a new-ed ActionResultHolder.
1388  template <typename F>
1389  static ActionResultHolder* PerformDefaultAction(
1390      const FunctionMockerBase<F>* func_mocker,
1391      const typename Function<F>::ArgumentTuple& args,
1392      const string& call_description) {
1393    return new ActionResultHolder(Wrapper(
1394        func_mocker->PerformDefaultAction(args, call_description)));
1395  }
1396
1397  // Performs the given action and returns the result in a new-ed
1398  // ActionResultHolder.
1399  template <typename F>
1400  static ActionResultHolder*
1401  PerformAction(const Action<F>& action,
1402                const typename Function<F>::ArgumentTuple& args) {
1403    return new ActionResultHolder(Wrapper(action.Perform(args)));
1404  }
1405
1406 private:
1407  typedef ReferenceOrValueWrapper<T> Wrapper;
1408
1409  explicit ActionResultHolder(Wrapper result)
1410      : result_(::testing::internal::move(result)) {
1411  }
1412
1413  Wrapper result_;
1414
1415  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1416};
1417
1418// Specialization for T = void.
1419template <>
1420class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1421 public:
1422  void Unwrap() { }
1423
1424  virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1425
1426  // Performs the given mock function's default action and returns ownership
1427  // of an empty ActionResultHolder*.
1428  template <typename F>
1429  static ActionResultHolder* PerformDefaultAction(
1430      const FunctionMockerBase<F>* func_mocker,
1431      const typename Function<F>::ArgumentTuple& args,
1432      const string& call_description) {
1433    func_mocker->PerformDefaultAction(args, call_description);
1434    return new ActionResultHolder;
1435  }
1436
1437  // Performs the given action and returns ownership of an empty
1438  // ActionResultHolder*.
1439  template <typename F>
1440  static ActionResultHolder* PerformAction(
1441      const Action<F>& action,
1442      const typename Function<F>::ArgumentTuple& args) {
1443    action.Perform(args);
1444    return new ActionResultHolder;
1445  }
1446
1447 private:
1448  ActionResultHolder() {}
1449  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1450};
1451
1452// The base of the function mocker class for the given function type.
1453// We put the methods in this class instead of its child to avoid code
1454// bloat.
1455template <typename F>
1456class FunctionMockerBase : public UntypedFunctionMockerBase {
1457 public:
1458  typedef typename Function<F>::Result Result;
1459  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1460  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1461
1462  FunctionMockerBase() : current_spec_(this) {}
1463
1464  // The destructor verifies that all expectations on this mock
1465  // function have been satisfied.  If not, it will report Google Test
1466  // non-fatal failures for the violations.
1467  virtual ~FunctionMockerBase()
1468        GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1469    MutexLock l(&g_gmock_mutex);
1470    VerifyAndClearExpectationsLocked();
1471    Mock::UnregisterLocked(this);
1472    ClearDefaultActionsLocked();
1473  }
1474
1475  // Returns the ON_CALL spec that matches this mock function with the
1476  // given arguments; returns NULL if no matching ON_CALL is found.
1477  // L = *
1478  const OnCallSpec<F>* FindOnCallSpec(
1479      const ArgumentTuple& args) const {
1480    for (UntypedOnCallSpecs::const_reverse_iterator it
1481             = untyped_on_call_specs_.rbegin();
1482         it != untyped_on_call_specs_.rend(); ++it) {
1483      const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1484      if (spec->Matches(args))
1485        return spec;
1486    }
1487
1488    return NULL;
1489  }
1490
1491  // Performs the default action of this mock function on the given
1492  // arguments and returns the result. Asserts (or throws if
1493  // exceptions are enabled) with a helpful call descrption if there
1494  // is no valid return value. This method doesn't depend on the
1495  // mutable state of this object, and thus can be called concurrently
1496  // without locking.
1497  // L = *
1498  Result PerformDefaultAction(const ArgumentTuple& args,
1499                              const string& call_description) const {
1500    const OnCallSpec<F>* const spec =
1501        this->FindOnCallSpec(args);
1502    if (spec != NULL) {
1503      return spec->GetAction().Perform(args);
1504    }
1505    const string message = call_description +
1506        "\n    The mock function has no default action "
1507        "set, and its return type has no default value set.";
1508#if GTEST_HAS_EXCEPTIONS
1509    if (!DefaultValue<Result>::Exists()) {
1510      throw std::runtime_error(message);
1511    }
1512#else
1513    Assert(DefaultValue<Result>::Exists(), "", -1, message);
1514#endif
1515    return DefaultValue<Result>::Get();
1516  }
1517
1518  // Performs the default action with the given arguments and returns
1519  // the action's result.  The call description string will be used in
1520  // the error message to describe the call in the case the default
1521  // action fails.  The caller is responsible for deleting the result.
1522  // L = *
1523  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1524      const void* untyped_args,  // must point to an ArgumentTuple
1525      const string& call_description) const {
1526    const ArgumentTuple& args =
1527        *static_cast<const ArgumentTuple*>(untyped_args);
1528    return ResultHolder::PerformDefaultAction(this, args, call_description);
1529  }
1530
1531  // Performs the given action with the given arguments and returns
1532  // the action's result.  The caller is responsible for deleting the
1533  // result.
1534  // L = *
1535  virtual UntypedActionResultHolderBase* UntypedPerformAction(
1536      const void* untyped_action, const void* untyped_args) const {
1537    // Make a copy of the action before performing it, in case the
1538    // action deletes the mock object (and thus deletes itself).
1539    const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1540    const ArgumentTuple& args =
1541        *static_cast<const ArgumentTuple*>(untyped_args);
1542    return ResultHolder::PerformAction(action, args);
1543  }
1544
1545  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1546  // clears the ON_CALL()s set on this mock function.
1547  virtual void ClearDefaultActionsLocked()
1548      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1549    g_gmock_mutex.AssertHeld();
1550
1551    // Deleting our default actions may trigger other mock objects to be
1552    // deleted, for example if an action contains a reference counted smart
1553    // pointer to that mock object, and that is the last reference. So if we
1554    // delete our actions within the context of the global mutex we may deadlock
1555    // when this method is called again. Instead, make a copy of the set of
1556    // actions to delete, clear our set within the mutex, and then delete the
1557    // actions outside of the mutex.
1558    UntypedOnCallSpecs specs_to_delete;
1559    untyped_on_call_specs_.swap(specs_to_delete);
1560
1561    g_gmock_mutex.Unlock();
1562    for (UntypedOnCallSpecs::const_iterator it =
1563             specs_to_delete.begin();
1564         it != specs_to_delete.end(); ++it) {
1565      delete static_cast<const OnCallSpec<F>*>(*it);
1566    }
1567
1568    // Lock the mutex again, since the caller expects it to be locked when we
1569    // return.
1570    g_gmock_mutex.Lock();
1571  }
1572
1573 protected:
1574  template <typename Function>
1575  friend class MockSpec;
1576
1577  typedef ActionResultHolder<Result> ResultHolder;
1578
1579  // Returns the result of invoking this mock function with the given
1580  // arguments.  This function can be safely called from multiple
1581  // threads concurrently.
1582  Result InvokeWith(const ArgumentTuple& args)
1583        GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1584    scoped_ptr<ResultHolder> holder(
1585        DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args)));
1586    return holder->Unwrap();
1587  }
1588
1589  // Adds and returns a default action spec for this mock function.
1590  OnCallSpec<F>& AddNewOnCallSpec(
1591      const char* file, int line,
1592      const ArgumentMatcherTuple& m)
1593          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1594    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1595    OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1596    untyped_on_call_specs_.push_back(on_call_spec);
1597    return *on_call_spec;
1598  }
1599
1600  // Adds and returns an expectation spec for this mock function.
1601  TypedExpectation<F>& AddNewExpectation(
1602      const char* file,
1603      int line,
1604      const string& source_text,
1605      const ArgumentMatcherTuple& m)
1606          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1607    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1608    TypedExpectation<F>* const expectation =
1609        new TypedExpectation<F>(this, file, line, source_text, m);
1610    const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1611    untyped_expectations_.push_back(untyped_expectation);
1612
1613    // Adds this expectation into the implicit sequence if there is one.
1614    Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1615    if (implicit_sequence != NULL) {
1616      implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1617    }
1618
1619    return *expectation;
1620  }
1621
1622  // The current spec (either default action spec or expectation spec)
1623  // being described on this function mocker.
1624  MockSpec<F>& current_spec() { return current_spec_; }
1625
1626 private:
1627  template <typename Func> friend class TypedExpectation;
1628
1629  // Some utilities needed for implementing UntypedInvokeWith().
1630
1631  // Describes what default action will be performed for the given
1632  // arguments.
1633  // L = *
1634  void DescribeDefaultActionTo(const ArgumentTuple& args,
1635                               ::std::ostream* os) const {
1636    const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1637
1638    if (spec == NULL) {
1639      *os << (internal::type_equals<Result, void>::value ?
1640              "returning directly.\n" :
1641              "returning default value.\n");
1642    } else {
1643      *os << "taking default action specified at:\n"
1644          << FormatFileLocation(spec->file(), spec->line()) << "\n";
1645    }
1646  }
1647
1648  // Writes a message that the call is uninteresting (i.e. neither
1649  // explicitly expected nor explicitly unexpected) to the given
1650  // ostream.
1651  virtual void UntypedDescribeUninterestingCall(
1652      const void* untyped_args,
1653      ::std::ostream* os) const
1654          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1655    const ArgumentTuple& args =
1656        *static_cast<const ArgumentTuple*>(untyped_args);
1657    *os << "Uninteresting mock function call - ";
1658    DescribeDefaultActionTo(args, os);
1659    *os << "    Function call: " << Name();
1660    UniversalPrint(args, os);
1661  }
1662
1663  // Returns the expectation that matches the given function arguments
1664  // (or NULL is there's no match); when a match is found,
1665  // untyped_action is set to point to the action that should be
1666  // performed (or NULL if the action is "do default"), and
1667  // is_excessive is modified to indicate whether the call exceeds the
1668  // expected number.
1669  //
1670  // Critical section: We must find the matching expectation and the
1671  // corresponding action that needs to be taken in an ATOMIC
1672  // transaction.  Otherwise another thread may call this mock
1673  // method in the middle and mess up the state.
1674  //
1675  // However, performing the action has to be left out of the critical
1676  // section.  The reason is that we have no control on what the
1677  // action does (it can invoke an arbitrary user function or even a
1678  // mock function) and excessive locking could cause a dead lock.
1679  virtual const ExpectationBase* UntypedFindMatchingExpectation(
1680      const void* untyped_args,
1681      const void** untyped_action, bool* is_excessive,
1682      ::std::ostream* what, ::std::ostream* why)
1683          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1684    const ArgumentTuple& args =
1685        *static_cast<const ArgumentTuple*>(untyped_args);
1686    MutexLock l(&g_gmock_mutex);
1687    TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1688    if (exp == NULL) {  // A match wasn't found.
1689      this->FormatUnexpectedCallMessageLocked(args, what, why);
1690      return NULL;
1691    }
1692
1693    // This line must be done before calling GetActionForArguments(),
1694    // which will increment the call count for *exp and thus affect
1695    // its saturation status.
1696    *is_excessive = exp->IsSaturated();
1697    const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1698    if (action != NULL && action->IsDoDefault())
1699      action = NULL;  // Normalize "do default" to NULL.
1700    *untyped_action = action;
1701    return exp;
1702  }
1703
1704  // Prints the given function arguments to the ostream.
1705  virtual void UntypedPrintArgs(const void* untyped_args,
1706                                ::std::ostream* os) const {
1707    const ArgumentTuple& args =
1708        *static_cast<const ArgumentTuple*>(untyped_args);
1709    UniversalPrint(args, os);
1710  }
1711
1712  // Returns the expectation that matches the arguments, or NULL if no
1713  // expectation matches them.
1714  TypedExpectation<F>* FindMatchingExpectationLocked(
1715      const ArgumentTuple& args) const
1716          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1717    g_gmock_mutex.AssertHeld();
1718    for (typename UntypedExpectations::const_reverse_iterator it =
1719             untyped_expectations_.rbegin();
1720         it != untyped_expectations_.rend(); ++it) {
1721      TypedExpectation<F>* const exp =
1722          static_cast<TypedExpectation<F>*>(it->get());
1723      if (exp->ShouldHandleArguments(args)) {
1724        return exp;
1725      }
1726    }
1727    return NULL;
1728  }
1729
1730  // Returns a message that the arguments don't match any expectation.
1731  void FormatUnexpectedCallMessageLocked(
1732      const ArgumentTuple& args,
1733      ::std::ostream* os,
1734      ::std::ostream* why) const
1735          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1736    g_gmock_mutex.AssertHeld();
1737    *os << "\nUnexpected mock function call - ";
1738    DescribeDefaultActionTo(args, os);
1739    PrintTriedExpectationsLocked(args, why);
1740  }
1741
1742  // Prints a list of expectations that have been tried against the
1743  // current mock function call.
1744  void PrintTriedExpectationsLocked(
1745      const ArgumentTuple& args,
1746      ::std::ostream* why) const
1747          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1748    g_gmock_mutex.AssertHeld();
1749    const int count = static_cast<int>(untyped_expectations_.size());
1750    *why << "Google Mock tried the following " << count << " "
1751         << (count == 1 ? "expectation, but it didn't match" :
1752             "expectations, but none matched")
1753         << ":\n";
1754    for (int i = 0; i < count; i++) {
1755      TypedExpectation<F>* const expectation =
1756          static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1757      *why << "\n";
1758      expectation->DescribeLocationTo(why);
1759      if (count > 1) {
1760        *why << "tried expectation #" << i << ": ";
1761      }
1762      *why << expectation->source_text() << "...\n";
1763      expectation->ExplainMatchResultTo(args, why);
1764      expectation->DescribeCallCountTo(why);
1765    }
1766  }
1767
1768  // The current spec (either default action spec or expectation spec)
1769  // being described on this function mocker.
1770  MockSpec<F> current_spec_;
1771
1772  // There is no generally useful and implementable semantics of
1773  // copying a mock object, so copying a mock is usually a user error.
1774  // Thus we disallow copying function mockers.  If the user really
1775  // wants to copy a mock object, he should implement his own copy
1776  // operation, for example:
1777  //
1778  //   class MockFoo : public Foo {
1779  //    public:
1780  //     // Defines a copy constructor explicitly.
1781  //     MockFoo(const MockFoo& src) {}
1782  //     ...
1783  //   };
1784  GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
1785};  // class FunctionMockerBase
1786
1787#ifdef _MSC_VER
1788# pragma warning(pop)  // Restores the warning state.
1789#endif  // _MSV_VER
1790
1791// Implements methods of FunctionMockerBase.
1792
1793// Verifies that all expectations on this mock function have been
1794// satisfied.  Reports one or more Google Test non-fatal failures and
1795// returns false if not.
1796
1797// Reports an uninteresting call (whose description is in msg) in the
1798// manner specified by 'reaction'.
1799void ReportUninterestingCall(CallReaction reaction, const string& msg);
1800
1801}  // namespace internal
1802
1803// The style guide prohibits "using" statements in a namespace scope
1804// inside a header file.  However, the MockSpec class template is
1805// meant to be defined in the ::testing namespace.  The following line
1806// is just a trick for working around a bug in MSVC 8.0, which cannot
1807// handle it if we define MockSpec in ::testing.
1808using internal::MockSpec;
1809
1810// Const(x) is a convenient function for obtaining a const reference
1811// to x.  This is useful for setting expectations on an overloaded
1812// const mock method, e.g.
1813//
1814//   class MockFoo : public FooInterface {
1815//    public:
1816//     MOCK_METHOD0(Bar, int());
1817//     MOCK_CONST_METHOD0(Bar, int&());
1818//   };
1819//
1820//   MockFoo foo;
1821//   // Expects a call to non-const MockFoo::Bar().
1822//   EXPECT_CALL(foo, Bar());
1823//   // Expects a call to const MockFoo::Bar().
1824//   EXPECT_CALL(Const(foo), Bar());
1825template <typename T>
1826inline const T& Const(const T& x) { return x; }
1827
1828// Constructs an Expectation object that references and co-owns exp.
1829inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
1830    : expectation_base_(exp.GetHandle().expectation_base()) {}
1831
1832}  // namespace testing
1833
1834// A separate macro is required to avoid compile errors when the name
1835// of the method used in call is a result of macro expansion.
1836// See CompilesWithMethodNameExpandedFromMacro tests in
1837// internal/gmock-spec-builders_test.cc for more details.
1838#define GMOCK_ON_CALL_IMPL_(obj, call) \
1839    ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1840                                                    #obj, #call)
1841#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
1842
1843#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
1844    ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
1845#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
1846
1847#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/gmock.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This is the main header file a user should include.
35
36#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_
37#define GMOCK_INCLUDE_GMOCK_GMOCK_H_
38
39// This file implements the following syntax:
40//
41//   ON_CALL(mock_object.Method(...))
42//     .With(...) ?
43//     .WillByDefault(...);
44//
45// where With() is optional and WillByDefault() must appear exactly
46// once.
47//
48//   EXPECT_CALL(mock_object.Method(...))
49//     .With(...) ?
50//     .Times(...) ?
51//     .InSequence(...) *
52//     .WillOnce(...) *
53//     .WillRepeatedly(...) ?
54//     .RetiresOnSaturation() ? ;
55//
56// where all clauses are optional and WillOnce() can be repeated.
57
58#include "gmock/gmock-actions.h"
59#include "gmock/gmock-cardinalities.h"
60#include "gmock/gmock-generated-actions.h"
61#include "gmock/gmock-generated-function-mockers.h"
62#include "gmock/gmock-generated-nice-strict.h"
63#include "gmock/gmock-generated-matchers.h"
64#include "gmock/gmock-matchers.h"
65#include "gmock/gmock-more-actions.h"
66#include "gmock/gmock-more-matchers.h"
67#include "gmock/internal/gmock-internal-utils.h"
68
69namespace testing {
70
71// Declares Google Mock flags that we want a user to use programmatically.
72GMOCK_DECLARE_bool_(catch_leaked_mocks);
73GMOCK_DECLARE_string_(verbose);
74
75// Initializes Google Mock.  This must be called before running the
76// tests.  In particular, it parses the command line for the flags
77// that Google Mock recognizes.  Whenever a Google Mock flag is seen,
78// it is removed from argv, and *argc is decremented.
79//
80// No value is returned.  Instead, the Google Mock flag variables are
81// updated.
82//
83// Since Google Test is needed for Google Mock to work, this function
84// also initializes Google Test and parses its flags, if that hasn't
85// been done.
86GTEST_API_ void InitGoogleMock(int* argc, char** argv);
87
88// This overloaded version can be used in Windows programs compiled in
89// UNICODE mode.
90GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
91
92}  // namespace testing
93
94#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_H_
trunk/3rdparty/googletest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gmock-generated-actions.h.pump
3// DO NOT EDIT BY HAND!!!
4
5#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
6#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
7
8#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$$ This is a Pump source file (http://go/pump).  Please use Pump to convert
3$$ it to callback-actions.h.
4$$
5$var max_callback_arity = 5
6$$}} This meta comment fixes auto-indentation in editors.
7#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
8#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
9
10#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/internal/custom/gmock-matchers.h
r0r249096
1// Copyright 2015, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// ============================================================
31// An installation-specific extension point for gmock-matchers.h.
32// ============================================================
33//
34// Adds google3 callback support to CallableTraits.
35//
36#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_
37#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_
38
39#endif  //  GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/internal/custom/gmock-port.h
r0r249096
1// Copyright 2015, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Injection point for custom user configurations.
31// The following macros can be defined:
32//
33//   Flag related macros:
34//     GMOCK_DECLARE_bool_(name)
35//     GMOCK_DECLARE_int32_(name)
36//     GMOCK_DECLARE_string_(name)
37//     GMOCK_DEFINE_bool_(name, default_val, doc)
38//     GMOCK_DEFINE_int32_(name, default_val, doc)
39//     GMOCK_DEFINE_string_(name, default_val, doc)
40//
41// ** Custom implementation starts here **
42
43#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
44#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
45
46#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
trunk/3rdparty/googletest/googlemock/include/gmock/internal/gmock-generated-internal-utils.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gmock-generated-internal-utils.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2007, Google Inc.
6// All rights reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33//
34// Author: wan@google.com (Zhanyong Wan)
35
36// Google Mock - a framework for writing C++ mock classes.
37//
38// This file contains template meta-programming utility classes needed
39// for implementing Google Mock.
40
41#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
42#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
43
44#include "gmock/internal/gmock-port.h"
45
46namespace testing {
47
48template <typename T>
49class Matcher;
50
51namespace internal {
52
53// An IgnoredValue object can be implicitly constructed from ANY value.
54// This is used in implementing the IgnoreResult(a) action.
55class IgnoredValue {
56 public:
57  // This constructor template allows any value to be implicitly
58  // converted to IgnoredValue.  The object has no data member and
59  // doesn't try to remember anything about the argument.  We
60  // deliberately omit the 'explicit' keyword in order to allow the
61  // conversion to be implicit.
62  template <typename T>
63  IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)
64};
65
66// MatcherTuple<T>::type is a tuple type where each field is a Matcher
67// for the corresponding field in tuple type T.
68template <typename Tuple>
69struct MatcherTuple;
70
71template <>
72struct MatcherTuple< ::testing::tuple<> > {
73  typedef ::testing::tuple< > type;
74};
75
76template <typename A1>
77struct MatcherTuple< ::testing::tuple<A1> > {
78  typedef ::testing::tuple<Matcher<A1> > type;
79};
80
81template <typename A1, typename A2>
82struct MatcherTuple< ::testing::tuple<A1, A2> > {
83  typedef ::testing::tuple<Matcher<A1>, Matcher<A2> > type;
84};
85
86template <typename A1, typename A2, typename A3>
87struct MatcherTuple< ::testing::tuple<A1, A2, A3> > {
88  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type;
89};
90
91template <typename A1, typename A2, typename A3, typename A4>
92struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > {
93  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>,
94      Matcher<A4> > type;
95};
96
97template <typename A1, typename A2, typename A3, typename A4, typename A5>
98struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > {
99  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
100      Matcher<A5> > type;
101};
102
103template <typename A1, typename A2, typename A3, typename A4, typename A5,
104    typename A6>
105struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
106  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
107      Matcher<A5>, Matcher<A6> > type;
108};
109
110template <typename A1, typename A2, typename A3, typename A4, typename A5,
111    typename A6, typename A7>
112struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
113  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
114      Matcher<A5>, Matcher<A6>, Matcher<A7> > type;
115};
116
117template <typename A1, typename A2, typename A3, typename A4, typename A5,
118    typename A6, typename A7, typename A8>
119struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
120  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
121      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type;
122};
123
124template <typename A1, typename A2, typename A3, typename A4, typename A5,
125    typename A6, typename A7, typename A8, typename A9>
126struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
127  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
128      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type;
129};
130
131template <typename A1, typename A2, typename A3, typename A4, typename A5,
132    typename A6, typename A7, typename A8, typename A9, typename A10>
133struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
134    A10> > {
135  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
136      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>,
137      Matcher<A10> > type;
138};
139
140// Template struct Function<F>, where F must be a function type, contains
141// the following typedefs:
142//
143//   Result:               the function's return type.
144//   ArgumentN:            the type of the N-th argument, where N starts with 1.
145//   ArgumentTuple:        the tuple type consisting of all parameters of F.
146//   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
147//                         parameters of F.
148//   MakeResultVoid:       the function type obtained by substituting void
149//                         for the return type of F.
150//   MakeResultIgnoredValue:
151//                         the function type obtained by substituting Something
152//                         for the return type of F.
153template <typename F>
154struct Function;
155
156template <typename R>
157struct Function<R()> {
158  typedef R Result;
159  typedef ::testing::tuple<> ArgumentTuple;
160  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
161  typedef void MakeResultVoid();
162  typedef IgnoredValue MakeResultIgnoredValue();
163};
164
165template <typename R, typename A1>
166struct Function<R(A1)>
167    : Function<R()> {
168  typedef A1 Argument1;
169  typedef ::testing::tuple<A1> ArgumentTuple;
170  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
171  typedef void MakeResultVoid(A1);
172  typedef IgnoredValue MakeResultIgnoredValue(A1);
173};
174
175template <typename R, typename A1, typename A2>
176struct Function<R(A1, A2)>
177    : Function<R(A1)> {
178  typedef A2 Argument2;
179  typedef ::testing::tuple<A1, A2> ArgumentTuple;
180  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
181  typedef void MakeResultVoid(A1, A2);
182  typedef IgnoredValue MakeResultIgnoredValue(A1, A2);
183};
184
185template <typename R, typename A1, typename A2, typename A3>
186struct Function<R(A1, A2, A3)>
187    : Function<R(A1, A2)> {
188  typedef A3 Argument3;
189  typedef ::testing::tuple<A1, A2, A3> ArgumentTuple;
190  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
191  typedef void MakeResultVoid(A1, A2, A3);
192  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3);
193};
194
195template <typename R, typename A1, typename A2, typename A3, typename A4>
196struct Function<R(A1, A2, A3, A4)>
197    : Function<R(A1, A2, A3)> {
198  typedef A4 Argument4;
199  typedef ::testing::tuple<A1, A2, A3, A4> ArgumentTuple;
200  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
201  typedef void MakeResultVoid(A1, A2, A3, A4);
202  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4);
203};
204
205template <typename R, typename A1, typename A2, typename A3, typename A4,
206    typename A5>
207struct Function<R(A1, A2, A3, A4, A5)>
208    : Function<R(A1, A2, A3, A4)> {
209  typedef A5 Argument5;
210  typedef ::testing::tuple<A1, A2, A3, A4, A5> ArgumentTuple;
211  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
212  typedef void MakeResultVoid(A1, A2, A3, A4, A5);
213  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5);
214};
215
216template <typename R, typename A1, typename A2, typename A3, typename A4,
217    typename A5, typename A6>
218struct Function<R(A1, A2, A3, A4, A5, A6)>
219    : Function<R(A1, A2, A3, A4, A5)> {
220  typedef A6 Argument6;
221  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple;
222  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
223  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6);
224  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6);
225};
226
227template <typename R, typename A1, typename A2, typename A3, typename A4,
228    typename A5, typename A6, typename A7>
229struct Function<R(A1, A2, A3, A4, A5, A6, A7)>
230    : Function<R(A1, A2, A3, A4, A5, A6)> {
231  typedef A7 Argument7;
232  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple;
233  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
234  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7);
235  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7);
236};
237
238template <typename R, typename A1, typename A2, typename A3, typename A4,
239    typename A5, typename A6, typename A7, typename A8>
240struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8)>
241    : Function<R(A1, A2, A3, A4, A5, A6, A7)> {
242  typedef A8 Argument8;
243  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple;
244  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
245  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8);
246  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8);
247};
248
249template <typename R, typename A1, typename A2, typename A3, typename A4,
250    typename A5, typename A6, typename A7, typename A8, typename A9>
251struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)>
252    : Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> {
253  typedef A9 Argument9;
254  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple;
255  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
256  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9);
257  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8,
258      A9);
259};
260
261template <typename R, typename A1, typename A2, typename A3, typename A4,
262    typename A5, typename A6, typename A7, typename A8, typename A9,
263    typename A10>
264struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)>
265    : Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
266  typedef A10 Argument10;
267  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
268      A10> ArgumentTuple;
269  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
270  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
271  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8,
272      A9, A10);
273};
274
275}  // namespace internal
276
277}  // namespace testing
278
279#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$$ This is a Pump source file.  Please use Pump to convert it to
3$$ gmock-generated-function-mockers.h.
4$$
5$var n = 10  $$ The maximum arity we support.
6// Copyright 2007, Google Inc.
7// All rights reserved.
8//
9// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions are
11// met:
12//
13//     * Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//     * Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following disclaimer
17// in the documentation and/or other materials provided with the
18// distribution.
19//     * Neither the name of Google Inc. nor the names of its
20// contributors may be used to endorse or promote products derived from
21// this software without specific prior written permission.
22//
23// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34//
35// Author: wan@google.com (Zhanyong Wan)
36
37// Google Mock - a framework for writing C++ mock classes.
38//
39// This file contains template meta-programming utility classes needed
40// for implementing Google Mock.
41
42#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
43#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
44
45#include "gmock/internal/gmock-port.h"
46
47namespace testing {
48
49template <typename T>
50class Matcher;
51
52namespace internal {
53
54// An IgnoredValue object can be implicitly constructed from ANY value.
55// This is used in implementing the IgnoreResult(a) action.
56class IgnoredValue {
57 public:
58  // This constructor template allows any value to be implicitly
59  // converted to IgnoredValue.  The object has no data member and
60  // doesn't try to remember anything about the argument.  We
61  // deliberately omit the 'explicit' keyword in order to allow the
62  // conversion to be implicit.
63  template <typename T>
64  IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)
65};
66
67// MatcherTuple<T>::type is a tuple type where each field is a Matcher
68// for the corresponding field in tuple type T.
69template <typename Tuple>
70struct MatcherTuple;
71
72
73$range i 0..n
74$for i [[
75$range j 1..i
76$var typename_As = [[$for j, [[typename A$j]]]]
77$var As = [[$for j, [[A$j]]]]
78$var matcher_As = [[$for j, [[Matcher<A$j>]]]]
79template <$typename_As>
80struct MatcherTuple< ::testing::tuple<$As> > {
81  typedef ::testing::tuple<$matcher_As > type;
82};
83
84
85]]
86// Template struct Function<F>, where F must be a function type, contains
87// the following typedefs:
88//
89//   Result:               the function's return type.
90//   ArgumentN:            the type of the N-th argument, where N starts with 1.
91//   ArgumentTuple:        the tuple type consisting of all parameters of F.
92//   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
93//                         parameters of F.
94//   MakeResultVoid:       the function type obtained by substituting void
95//                         for the return type of F.
96//   MakeResultIgnoredValue:
97//                         the function type obtained by substituting Something
98//                         for the return type of F.
99template <typename F>
100struct Function;
101
102template <typename R>
103struct Function<R()> {
104  typedef R Result;
105  typedef ::testing::tuple<> ArgumentTuple;
106  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
107  typedef void MakeResultVoid();
108  typedef IgnoredValue MakeResultIgnoredValue();
109};
110
111
112$range i 1..n
113$for i [[
114$range j 1..i
115$var typename_As = [[$for j [[, typename A$j]]]]
116$var As = [[$for j, [[A$j]]]]
117$var matcher_As = [[$for j, [[Matcher<A$j>]]]]
118$range k 1..i-1
119$var prev_As = [[$for k, [[A$k]]]]
120template <typename R$typename_As>
121struct Function<R($As)>
122    : Function<R($prev_As)> {
123  typedef A$i Argument$i;
124  typedef ::testing::tuple<$As> ArgumentTuple;
125  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
126  typedef void MakeResultVoid($As);
127  typedef IgnoredValue MakeResultIgnoredValue($As);
128};
129
130
131]]
132}  // namespace internal
133
134}  // namespace testing
135
136#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
trunk/3rdparty/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file defines some utilities useful for implementing Google
35// Mock.  They are subject to change without notice, so please DO NOT
36// USE THEM IN USER CODE.
37
38#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
39#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40
41#include <stdio.h>
42#include <ostream>  // NOLINT
43#include <string>
44
45#include "gmock/internal/gmock-generated-internal-utils.h"
46#include "gmock/internal/gmock-port.h"
47#include "gtest/gtest.h"
48
49namespace testing {
50namespace internal {
51
52// Converts an identifier name to a space-separated list of lower-case
53// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
54// treated as one word.  For example, both "FooBar123" and
55// "foo_bar_123" are converted to "foo bar 123".
56GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name);
57
58// PointeeOf<Pointer>::type is the type of a value pointed to by a
59// Pointer, which can be either a smart pointer or a raw pointer.  The
60// following default implementation is for the case where Pointer is a
61// smart pointer.
62template <typename Pointer>
63struct PointeeOf {
64  // Smart pointer classes define type element_type as the type of
65  // their pointees.
66  typedef typename Pointer::element_type type;
67};
68// This specialization is for the raw pointer case.
69template <typename T>
70struct PointeeOf<T*> { typedef T type; };  // NOLINT
71
72// GetRawPointer(p) returns the raw pointer underlying p when p is a
73// smart pointer, or returns p itself when p is already a raw pointer.
74// The following default implementation is for the smart pointer case.
75template <typename Pointer>
76inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
77  return p.get();
78}
79// This overloaded version is for the raw pointer case.
80template <typename Element>
81inline Element* GetRawPointer(Element* p) { return p; }
82
83// This comparator allows linked_ptr to be stored in sets.
84template <typename T>
85struct LinkedPtrLessThan {
86  bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
87                  const ::testing::internal::linked_ptr<T>& rhs) const {
88    return lhs.get() < rhs.get();
89  }
90};
91
92// Symbian compilation can be done with wchar_t being either a native
93// type or a typedef.  Using Google Mock with OpenC without wchar_t
94// should require the definition of _STLP_NO_WCHAR_T.
95//
96// MSVC treats wchar_t as a native type usually, but treats it as the
97// same as unsigned short when the compiler option /Zc:wchar_t- is
98// specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
99// is a native type.
100#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \
101    (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))
102// wchar_t is a typedef.
103#else
104# define GMOCK_WCHAR_T_IS_NATIVE_ 1
105#endif
106
107// signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
108// Using them is a bad practice and not portable.  So DON'T use them.
109//
110// Still, Google Mock is designed to work even if the user uses signed
111// wchar_t or unsigned wchar_t (obviously, assuming the compiler
112// supports them).
113//
114// To gcc,
115//   wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
116#ifdef __GNUC__
117// signed/unsigned wchar_t are valid types.
118# define GMOCK_HAS_SIGNED_WCHAR_T_ 1
119#endif
120
121// In what follows, we use the term "kind" to indicate whether a type
122// is bool, an integer type (excluding bool), a floating-point type,
123// or none of them.  This categorization is useful for determining
124// when a matcher argument type can be safely converted to another
125// type in the implementation of SafeMatcherCast.
126enum TypeKind {
127  kBool, kInteger, kFloatingPoint, kOther
128};
129
130// KindOf<T>::value is the kind of type T.
131template <typename T> struct KindOf {
132  enum { value = kOther };  // The default kind.
133};
134
135// This macro declares that the kind of 'type' is 'kind'.
136#define GMOCK_DECLARE_KIND_(type, kind) \
137  template <> struct KindOf<type> { enum { value = kind }; }
138
139GMOCK_DECLARE_KIND_(bool, kBool);
140
141// All standard integer types.
142GMOCK_DECLARE_KIND_(char, kInteger);
143GMOCK_DECLARE_KIND_(signed char, kInteger);
144GMOCK_DECLARE_KIND_(unsigned char, kInteger);
145GMOCK_DECLARE_KIND_(short, kInteger);  // NOLINT
146GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
147GMOCK_DECLARE_KIND_(int, kInteger);
148GMOCK_DECLARE_KIND_(unsigned int, kInteger);
149GMOCK_DECLARE_KIND_(long, kInteger);  // NOLINT
150GMOCK_DECLARE_KIND_(unsigned long, kInteger);  // NOLINT
151
152#if GMOCK_WCHAR_T_IS_NATIVE_
153GMOCK_DECLARE_KIND_(wchar_t, kInteger);
154#endif
155
156// Non-standard integer types.
157GMOCK_DECLARE_KIND_(Int64, kInteger);
158GMOCK_DECLARE_KIND_(UInt64, kInteger);
159
160// All standard floating-point types.
161GMOCK_DECLARE_KIND_(float, kFloatingPoint);
162GMOCK_DECLARE_KIND_(double, kFloatingPoint);
163GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
164
165#undef GMOCK_DECLARE_KIND_
166
167// Evaluates to the kind of 'type'.
168#define GMOCK_KIND_OF_(type) \
169  static_cast< ::testing::internal::TypeKind>( \
170      ::testing::internal::KindOf<type>::value)
171
172// Evaluates to true iff integer type T is signed.
173#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
174
175// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
176// is true iff arithmetic type From can be losslessly converted to
177// arithmetic type To.
178//
179// It's the user's responsibility to ensure that both From and To are
180// raw (i.e. has no CV modifier, is not a pointer, and is not a
181// reference) built-in arithmetic types, kFromKind is the kind of
182// From, and kToKind is the kind of To; the value is
183// implementation-defined when the above pre-condition is violated.
184template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
185struct LosslessArithmeticConvertibleImpl : public false_type {};
186
187// Converting bool to bool is lossless.
188template <>
189struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
190    : public true_type {};  // NOLINT
191
192// Converting bool to any integer type is lossless.
193template <typename To>
194struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
195    : public true_type {};  // NOLINT
196
197// Converting bool to any floating-point type is lossless.
198template <typename To>
199struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
200    : public true_type {};  // NOLINT
201
202// Converting an integer to bool is lossy.
203template <typename From>
204struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
205    : public false_type {};  // NOLINT
206
207// Converting an integer to another non-bool integer is lossless iff
208// the target type's range encloses the source type's range.
209template <typename From, typename To>
210struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
211    : public bool_constant<
212      // When converting from a smaller size to a larger size, we are
213      // fine as long as we are not converting from signed to unsigned.
214      ((sizeof(From) < sizeof(To)) &&
215       (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
216      // When converting between the same size, the signedness must match.
217      ((sizeof(From) == sizeof(To)) &&
218       (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {};  // NOLINT
219
220#undef GMOCK_IS_SIGNED_
221
222// Converting an integer to a floating-point type may be lossy, since
223// the format of a floating-point number is implementation-defined.
224template <typename From, typename To>
225struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
226    : public false_type {};  // NOLINT
227
228// Converting a floating-point to bool is lossy.
229template <typename From>
230struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
231    : public false_type {};  // NOLINT
232
233// Converting a floating-point to an integer is lossy.
234template <typename From, typename To>
235struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
236    : public false_type {};  // NOLINT
237
238// Converting a floating-point to another floating-point is lossless
239// iff the target type is at least as big as the source type.
240template <typename From, typename To>
241struct LosslessArithmeticConvertibleImpl<
242  kFloatingPoint, From, kFloatingPoint, To>
243    : public bool_constant<sizeof(From) <= sizeof(To)> {};  // NOLINT
244
245// LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
246// type From can be losslessly converted to arithmetic type To.
247//
248// It's the user's responsibility to ensure that both From and To are
249// raw (i.e. has no CV modifier, is not a pointer, and is not a
250// reference) built-in arithmetic types; the value is
251// implementation-defined when the above pre-condition is violated.
252template <typename From, typename To>
253struct LosslessArithmeticConvertible
254    : public LosslessArithmeticConvertibleImpl<
255  GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {};  // NOLINT
256
257// This interface knows how to report a Google Mock failure (either
258// non-fatal or fatal).
259class FailureReporterInterface {
260 public:
261  // The type of a failure (either non-fatal or fatal).
262  enum FailureType {
263    kNonfatal, kFatal
264  };
265
266  virtual ~FailureReporterInterface() {}
267
268  // Reports a failure that occurred at the given source file location.
269  virtual void ReportFailure(FailureType type, const char* file, int line,
270                             const string& message) = 0;
271};
272
273// Returns the failure reporter used by Google Mock.
274GTEST_API_ FailureReporterInterface* GetFailureReporter();
275
276// Asserts that condition is true; aborts the process with the given
277// message if condition is false.  We cannot use LOG(FATAL) or CHECK()
278// as Google Mock might be used to mock the log sink itself.  We
279// inline this function to prevent it from showing up in the stack
280// trace.
281inline void Assert(bool condition, const char* file, int line,
282                   const string& msg) {
283  if (!condition) {
284    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
285                                        file, line, msg);
286  }
287}
288inline void Assert(bool condition, const char* file, int line) {
289  Assert(condition, file, line, "Assertion failed.");
290}
291
292// Verifies that condition is true; generates a non-fatal failure if
293// condition is false.
294inline void Expect(bool condition, const char* file, int line,
295                   const string& msg) {
296  if (!condition) {
297    GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
298                                        file, line, msg);
299  }
300}
301inline void Expect(bool condition, const char* file, int line) {
302  Expect(condition, file, line, "Expectation failed.");
303}
304
305// Severity level of a log.
306enum LogSeverity {
307  kInfo = 0,
308  kWarning = 1
309};
310
311// Valid values for the --gmock_verbose flag.
312
313// All logs (informational and warnings) are printed.
314const char kInfoVerbosity[] = "info";
315// Only warnings are printed.
316const char kWarningVerbosity[] = "warning";
317// No logs are printed.
318const char kErrorVerbosity[] = "error";
319
320// Returns true iff a log with the given severity is visible according
321// to the --gmock_verbose flag.
322GTEST_API_ bool LogIsVisible(LogSeverity severity);
323
324// Prints the given message to stdout iff 'severity' >= the level
325// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
326// 0, also prints the stack trace excluding the top
327// stack_frames_to_skip frames.  In opt mode, any positive
328// stack_frames_to_skip is treated as 0, since we don't know which
329// function calls will be inlined by the compiler and need to be
330// conservative.
331GTEST_API_ void Log(LogSeverity severity,
332                    const string& message,
333                    int stack_frames_to_skip);
334
335// TODO(wan@google.com): group all type utilities together.
336
337// Type traits.
338
339// is_reference<T>::value is non-zero iff T is a reference type.
340template <typename T> struct is_reference : public false_type {};
341template <typename T> struct is_reference<T&> : public true_type {};
342
343// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
344template <typename T1, typename T2> struct type_equals : public false_type {};
345template <typename T> struct type_equals<T, T> : public true_type {};
346
347// remove_reference<T>::type removes the reference from type T, if any.
348template <typename T> struct remove_reference { typedef T type; };  // NOLINT
349template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
350
351// DecayArray<T>::type turns an array type U[N] to const U* and preserves
352// other types.  Useful for saving a copy of a function argument.
353template <typename T> struct DecayArray { typedef T type; };  // NOLINT
354template <typename T, size_t N> struct DecayArray<T[N]> {
355  typedef const T* type;
356};
357// Sometimes people use arrays whose size is not available at the use site
358// (e.g. extern const char kNamePrefix[]).  This specialization covers that
359// case.
360template <typename T> struct DecayArray<T[]> {
361  typedef const T* type;
362};
363
364// Disable MSVC warnings for infinite recursion, since in this case the
365// the recursion is unreachable.
366#ifdef _MSC_VER
367# pragma warning(push)
368# pragma warning(disable:4717)
369#endif
370
371// Invalid<T>() is usable as an expression of type T, but will terminate
372// the program with an assertion failure if actually run.  This is useful
373// when a value of type T is needed for compilation, but the statement
374// will not really be executed (or we don't care if the statement
375// crashes).
376template <typename T>
377inline T Invalid() {
378  Assert(false, "", -1, "Internal error: attempt to return invalid value");
379  // This statement is unreachable, and would never terminate even if it
380  // could be reached. It is provided only to placate compiler warnings
381  // about missing return statements.
382  return Invalid<T>();
383}
384
385#ifdef _MSC_VER
386# pragma warning(pop)
387#endif
388
389// Given a raw type (i.e. having no top-level reference or const
390// modifier) RawContainer that's either an STL-style container or a
391// native array, class StlContainerView<RawContainer> has the
392// following members:
393//
394//   - type is a type that provides an STL-style container view to
395//     (i.e. implements the STL container concept for) RawContainer;
396//   - const_reference is a type that provides a reference to a const
397//     RawContainer;
398//   - ConstReference(raw_container) returns a const reference to an STL-style
399//     container view to raw_container, which is a RawContainer.
400//   - Copy(raw_container) returns an STL-style container view of a
401//     copy of raw_container, which is a RawContainer.
402//
403// This generic version is used when RawContainer itself is already an
404// STL-style container.
405template <class RawContainer>
406class StlContainerView {
407 public:
408  typedef RawContainer type;
409  typedef const type& const_reference;
410
411  static const_reference ConstReference(const RawContainer& container) {
412    // Ensures that RawContainer is not a const type.
413    testing::StaticAssertTypeEq<RawContainer,
414        GTEST_REMOVE_CONST_(RawContainer)>();
415    return container;
416  }
417  static type Copy(const RawContainer& container) { return container; }
418};
419
420// This specialization is used when RawContainer is a native array type.
421template <typename Element, size_t N>
422class StlContainerView<Element[N]> {
423 public:
424  typedef GTEST_REMOVE_CONST_(Element) RawElement;
425  typedef internal::NativeArray<RawElement> type;
426  // NativeArray<T> can represent a native array either by value or by
427  // reference (selected by a constructor argument), so 'const type'
428  // can be used to reference a const native array.  We cannot
429  // 'typedef const type& const_reference' here, as that would mean
430  // ConstReference() has to return a reference to a local variable.
431  typedef const type const_reference;
432
433  static const_reference ConstReference(const Element (&array)[N]) {
434    // Ensures that Element is not a const type.
435    testing::StaticAssertTypeEq<Element, RawElement>();
436#if GTEST_OS_SYMBIAN
437    // The Nokia Symbian compiler confuses itself in template instantiation
438    // for this call without the cast to Element*:
439    // function call '[testing::internal::NativeArray<char *>].NativeArray(
440    //     {lval} const char *[4], long, testing::internal::RelationToSource)'
441    //     does not match
442    // 'testing::internal::NativeArray<char *>::NativeArray(
443    //     char *const *, unsigned int, testing::internal::RelationToSource)'
444    // (instantiating: 'testing::internal::ContainsMatcherImpl
445    //     <const char * (&)[4]>::Matches(const char * (&)[4]) const')
446    // (instantiating: 'testing::internal::StlContainerView<char *[4]>::
447    //     ConstReference(const char * (&)[4])')
448    // (and though the N parameter type is mismatched in the above explicit
449    // conversion of it doesn't help - only the conversion of the array).
450    return type(const_cast<Element*>(&array[0]), N,
451                RelationToSourceReference());
452#else
453    return type(array, N, RelationToSourceReference());
454#endif  // GTEST_OS_SYMBIAN
455  }
456  static type Copy(const Element (&array)[N]) {
457#if GTEST_OS_SYMBIAN
458    return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
459#else
460    return type(array, N, RelationToSourceCopy());
461#endif  // GTEST_OS_SYMBIAN
462  }
463};
464
465// This specialization is used when RawContainer is a native array
466// represented as a (pointer, size) tuple.
467template <typename ElementPointer, typename Size>
468class StlContainerView< ::testing::tuple<ElementPointer, Size> > {
469 public:
470  typedef GTEST_REMOVE_CONST_(
471      typename internal::PointeeOf<ElementPointer>::type) RawElement;
472  typedef internal::NativeArray<RawElement> type;
473  typedef const type const_reference;
474
475  static const_reference ConstReference(
476      const ::testing::tuple<ElementPointer, Size>& array) {
477    return type(get<0>(array), get<1>(array), RelationToSourceReference());
478  }
479  static type Copy(const ::testing::tuple<ElementPointer, Size>& array) {
480    return type(get<0>(array), get<1>(array), RelationToSourceCopy());
481  }
482};
483
484// The following specialization prevents the user from instantiating
485// StlContainer with a reference type.
486template <typename T> class StlContainerView<T&>;
487
488// A type transform to remove constness from the first part of a pair.
489// Pairs like that are used as the value_type of associative containers,
490// and this transform produces a similar but assignable pair.
491template <typename T>
492struct RemoveConstFromKey {
493  typedef T type;
494};
495
496// Partially specialized to remove constness from std::pair<const K, V>.
497template <typename K, typename V>
498struct RemoveConstFromKey<std::pair<const K, V> > {
499  typedef std::pair<K, V> type;
500};
501
502// Mapping from booleans to types. Similar to boost::bool_<kValue> and
503// std::integral_constant<bool, kValue>.
504template <bool kValue>
505struct BooleanConstant {};
506
507}  // namespace internal
508}  // namespace testing
509
510#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
511
trunk/3rdparty/googletest/googlemock/include/gmock/internal/gmock-port.h
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vadimb@google.com (Vadim Berman)
31//
32// Low-level types and utilities for porting Google Mock to various
33// platforms.  All macros ending with _ and symbols defined in an
34// internal namespace are subject to change without notice.  Code
35// outside Google Mock MUST NOT USE THEM DIRECTLY.  Macros that don't
36// end with _ are part of Google Mock's public API and can be used by
37// code outside Google Mock.
38
39#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
40#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
41
42#include <assert.h>
43#include <stdlib.h>
44#include <iostream>
45
46// Most of the utilities needed for porting Google Mock are also
47// required for Google Test and are defined in gtest-port.h.
48//
49// Note to maintainers: to reduce code duplication, prefer adding
50// portability utilities to Google Test's gtest-port.h instead of
51// here, as Google Mock depends on Google Test.  Only add a utility
52// here if it's truly specific to Google Mock.
53#include "gtest/internal/gtest-linked_ptr.h"
54#include "gtest/internal/gtest-port.h"
55#include "gmock/internal/custom/gmock-port.h"
56
57// To avoid conditional compilation everywhere, we make it
58// gmock-port.h's responsibility to #include the header implementing
59// tr1/tuple.  gmock-port.h does this via gtest-port.h, which is
60// guaranteed to pull in the tuple header.
61
62// For MS Visual C++, check the compiler version. At least VS 2003 is
63// required to compile Google Mock.
64#if defined(_MSC_VER) && _MSC_VER < 1310
65# error "At least Visual C++ 2003 (7.1) is required to compile Google Mock."
66#endif
67
68// Macro for referencing flags.  This is public as we want the user to
69// use this syntax to reference Google Mock flags.
70#define GMOCK_FLAG(name) FLAGS_gmock_##name
71
72#if !defined(GMOCK_DECLARE_bool_)
73
74// Macros for declaring flags.
75#define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
76#define GMOCK_DECLARE_int32_(name) \
77    extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name)
78#define GMOCK_DECLARE_string_(name) \
79    extern GTEST_API_ ::std::string GMOCK_FLAG(name)
80
81// Macros for defining flags.
82#define GMOCK_DEFINE_bool_(name, default_val, doc) \
83    GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
84#define GMOCK_DEFINE_int32_(name, default_val, doc) \
85    GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val)
86#define GMOCK_DEFINE_string_(name, default_val, doc) \
87    GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
88
89#endif  // !defined(GMOCK_DECLARE_bool_)
90
91#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
trunk/3rdparty/googletest/googlemock/make/Makefile
r0r249096
1# A sample Makefile for building both Google Mock and Google Test and
2# using them in user tests.  This file is self-contained, so you don't
3# need to use the Makefile in Google Test's source tree.  Please tweak
4# it to suit your environment and project.  You may want to move it to
5# your project's root directory.
6#
7# SYNOPSIS:
8#
9#   make [all]  - makes everything.
10#   make TARGET - makes the given target.
11#   make clean  - removes all files generated by make.
12
13# Please tweak the following variable definitions as needed by your
14# project, except GMOCK_HEADERS and GTEST_HEADERS, which you can use
15# in your own targets but shouldn't modify.
16
17# Points to the root of Google Test, relative to where this file is.
18# Remember to tweak this if you move this file, or if you want to use
19# a copy of Google Test at a different location.
20GTEST_DIR = ../gtest
21
22# Points to the root of Google Mock, relative to where this file is.
23# Remember to tweak this if you move this file.
24GMOCK_DIR = ..
25
26# Where to find user code.
27USER_DIR = ../test
28
29# Flags passed to the preprocessor.
30# Set Google Test and Google Mock's header directories as system
31# directories, such that the compiler doesn't generate warnings in
32# these headers.
33CPPFLAGS += -isystem $(GTEST_DIR)/include -isystem $(GMOCK_DIR)/include
34
35# Flags passed to the C++ compiler.
36CXXFLAGS += -g -Wall -Wextra -pthread
37
38# All tests produced by this Makefile.  Remember to add new tests you
39# created to the list.
40TESTS = gmock_test
41
42# All Google Test headers.  Usually you shouldn't change this
43# definition.
44GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \
45                $(GTEST_DIR)/include/gtest/internal/*.h
46
47# All Google Mock headers. Note that all Google Test headers are
48# included here too, as they are #included by Google Mock headers.
49# Usually you shouldn't change this definition.   
50GMOCK_HEADERS = $(GMOCK_DIR)/include/gmock/*.h \
51                $(GMOCK_DIR)/include/gmock/internal/*.h \
52                $(GTEST_HEADERS)
53
54# House-keeping build targets.
55
56all : $(TESTS)
57
58clean :
59   rm -f $(TESTS) gmock.a gmock_main.a *.o
60
61# Builds gmock.a and gmock_main.a.  These libraries contain both
62# Google Mock and Google Test.  A test should link with either gmock.a
63# or gmock_main.a, depending on whether it defines its own main()
64# function.  It's fine if your test only uses features from Google
65# Test (and not Google Mock).
66
67# Usually you shouldn't tweak such internal variables, indicated by a
68# trailing _.
69GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)
70GMOCK_SRCS_ = $(GMOCK_DIR)/src/*.cc $(GMOCK_HEADERS)
71
72# For simplicity and to avoid depending on implementation details of
73# Google Mock and Google Test, the dependencies specified below are
74# conservative and not optimized.  This is fine as Google Mock and
75# Google Test compile fast and for ordinary users their source rarely
76# changes.
77gtest-all.o : $(GTEST_SRCS_)
78   $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
79            -c $(GTEST_DIR)/src/gtest-all.cc
80
81gmock-all.o : $(GMOCK_SRCS_)
82   $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
83            -c $(GMOCK_DIR)/src/gmock-all.cc
84
85gmock_main.o : $(GMOCK_SRCS_)
86   $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
87            -c $(GMOCK_DIR)/src/gmock_main.cc
88
89gmock.a : gmock-all.o gtest-all.o
90   $(AR) $(ARFLAGS) $@ $^
91
92gmock_main.a : gmock-all.o gtest-all.o gmock_main.o
93   $(AR) $(ARFLAGS) $@ $^
94
95# Builds a sample test.
96
97gmock_test.o : $(USER_DIR)/gmock_test.cc $(GMOCK_HEADERS)
98   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/gmock_test.cc
99
100gmock_test : gmock_test.o gmock_main.a
101   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@
trunk/3rdparty/googletest/googlemock/msvc/2005/gmock.sln
r0r249096
1
2Microsoft Visual Studio Solution File, Format Version 9.00
3# Visual Studio 2005
4Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
5EndProject
6Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
7EndProject
8Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
9EndProject
10Global
11   GlobalSection(SolutionConfigurationPlatforms) = preSolution
12      Debug|Win32 = Debug|Win32
13      Release|Win32 = Release|Win32
14   EndGlobalSection
15   GlobalSection(ProjectConfigurationPlatforms) = postSolution
16      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32
17      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32
18      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32
19      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32
20      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32
21      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32
22      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32
23      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32
24      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32
25      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32
26      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32
27      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32
28   EndGlobalSection
29   GlobalSection(SolutionProperties) = preSolution
30      HideSolutionNode = FALSE
31   EndGlobalSection
32EndGlobal
trunk/3rdparty/googletest/googlemock/msvc/2005/gmock.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="8.00"
5   Name="gmock"
6   ProjectGUID="{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
7   RootNamespace="gmock"
8   Keyword="Win32Proj"
9   >
10   <Platforms>
11      <Platform
12         Name="Win32"
13      />
14   </Platforms>
15   <ToolFiles>
16   </ToolFiles>
17   <Configurations>
18      <Configuration
19         Name="Debug|Win32"
20         OutputDirectory="$(SolutionDir)$(ConfigurationName)"
21         IntermediateDirectory="$(OutDir)\$(ProjectName)"
22         ConfigurationType="4"
23         InheritedPropertySheets=".\gmock_config.vsprops"
24         CharacterSet="1"
25         >
26         <Tool
27            Name="VCPreBuildEventTool"
28         />
29         <Tool
30            Name="VCCustomBuildTool"
31         />
32         <Tool
33            Name="VCXMLDataGeneratorTool"
34         />
35         <Tool
36            Name="VCWebServiceProxyGeneratorTool"
37         />
38         <Tool
39            Name="VCMIDLTool"
40         />
41         <Tool
42            Name="VCCLCompilerTool"
43            Optimization="0"
44            AdditionalIncludeDirectories="..\..\include;..\.."
45            PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
46            MinimalRebuild="true"
47            BasicRuntimeChecks="3"
48            RuntimeLibrary="1"
49            UsePrecompiledHeader="0"
50            WarningLevel="3"
51            Detect64BitPortabilityProblems="true"
52            DebugInformationFormat="3"
53         />
54         <Tool
55            Name="VCManagedResourceCompilerTool"
56         />
57         <Tool
58            Name="VCResourceCompilerTool"
59         />
60         <Tool
61            Name="VCPreLinkEventTool"
62         />
63         <Tool
64            Name="VCLibrarianTool"
65         />
66         <Tool
67            Name="VCALinkTool"
68         />
69         <Tool
70            Name="VCXDCMakeTool"
71         />
72         <Tool
73            Name="VCBscMakeTool"
74         />
75         <Tool
76            Name="VCFxCopTool"
77         />
78         <Tool
79            Name="VCPostBuildEventTool"
80         />
81      </Configuration>
82      <Configuration
83         Name="Release|Win32"
84         OutputDirectory="$(SolutionDir)$(ConfigurationName)"
85         IntermediateDirectory="$(OutDir)\$(ProjectName)"
86         ConfigurationType="4"
87         InheritedPropertySheets=".\gmock_config.vsprops"
88         CharacterSet="1"
89         WholeProgramOptimization="1"
90         >
91         <Tool
92            Name="VCPreBuildEventTool"
93         />
94         <Tool
95            Name="VCCustomBuildTool"
96         />
97         <Tool
98            Name="VCXMLDataGeneratorTool"
99         />
100         <Tool
101            Name="VCWebServiceProxyGeneratorTool"
102         />
103         <Tool
104            Name="VCMIDLTool"
105         />
106         <Tool
107            Name="VCCLCompilerTool"
108            AdditionalIncludeDirectories="..\..\include;..\.."
109            PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
110            RuntimeLibrary="0"
111            UsePrecompiledHeader="0"
112            WarningLevel="3"
113            Detect64BitPortabilityProblems="true"
114            DebugInformationFormat="3"
115         />
116         <Tool
117            Name="VCManagedResourceCompilerTool"
118         />
119         <Tool
120            Name="VCResourceCompilerTool"
121         />
122         <Tool
123            Name="VCPreLinkEventTool"
124         />
125         <Tool
126            Name="VCLibrarianTool"
127         />
128         <Tool
129            Name="VCALinkTool"
130         />
131         <Tool
132            Name="VCXDCMakeTool"
133         />
134         <Tool
135            Name="VCBscMakeTool"
136         />
137         <Tool
138            Name="VCFxCopTool"
139         />
140         <Tool
141            Name="VCPostBuildEventTool"
142         />
143      </Configuration>
144   </Configurations>
145   <References>
146   </References>
147   <Files>
148      <Filter
149         Name="Source Files"
150         Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
151         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
152         >
153         <File
154            RelativePath="..\..\src\gmock-all.cc"
155            >
156         </File>
157         <File
158            RelativePath="$(GTestDir)\src\gtest-all.cc"
159            >
160            <FileConfiguration
161               Name="Debug|Win32"
162               >
163               <Tool
164                  Name="VCCLCompilerTool"
165                  AdditionalIncludeDirectories="$(GTestDir)"
166               />
167            </FileConfiguration>
168            <FileConfiguration
169               Name="Release|Win32"
170               >
171               <Tool
172                  Name="VCCLCompilerTool"
173                  AdditionalIncludeDirectories="$(GTestDir)"
174               />
175            </FileConfiguration>
176         </File>
177      </Filter>
178      <Filter
179         Name="Public Header Files"
180         Filter="h;hpp;hxx;hm;inl;inc;xsd"
181         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
182         >
183      </Filter>
184      <Filter
185         Name="Private Header Files"
186         >
187      </Filter>
188   </Files>
189   <Globals>
190   </Globals>
191</VisualStudioProject>
trunk/3rdparty/googletest/googlemock/msvc/2005/gmock_config.vsprops
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioPropertySheet
3   ProjectType="Visual C++"
4   Version="8.00"
5   Name="gmock_config"
6   >
7   <Tool
8      Name="VCCLCompilerTool"
9      AdditionalIncludeDirectories="&quot;$(GTestDir)/include&quot;"
10   />
11   <UserMacro
12      Name="GTestDir"
13      Value="../../gtest"
14   />
15</VisualStudioPropertySheet>
trunk/3rdparty/googletest/googlemock/msvc/2005/gmock_main.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="8.00"
5   Name="gmock_main"
6   ProjectGUID="{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
7   RootNamespace="gmock_main"
8   Keyword="Win32Proj"
9   >
10   <Platforms>
11      <Platform
12         Name="Win32"
13      />
14   </Platforms>
15   <ToolFiles>
16   </ToolFiles>
17   <Configurations>
18      <Configuration
19         Name="Debug|Win32"
20         OutputDirectory="$(SolutionDir)$(ConfigurationName)"
21         IntermediateDirectory="$(OutDir)\$(ProjectName)"
22         ConfigurationType="4"
23         InheritedPropertySheets=".\gmock_config.vsprops"
24         CharacterSet="1"
25         >
26         <Tool
27            Name="VCPreBuildEventTool"
28         />
29         <Tool
30            Name="VCCustomBuildTool"
31         />
32         <Tool
33            Name="VCXMLDataGeneratorTool"
34         />
35         <Tool
36            Name="VCWebServiceProxyGeneratorTool"
37         />
38         <Tool
39            Name="VCMIDLTool"
40         />
41         <Tool
42            Name="VCCLCompilerTool"
43            Optimization="0"
44            AdditionalIncludeDirectories="../../include"
45            PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
46            MinimalRebuild="true"
47            BasicRuntimeChecks="3"
48            RuntimeLibrary="1"
49            UsePrecompiledHeader="0"
50            WarningLevel="3"
51            Detect64BitPortabilityProblems="true"
52            DebugInformationFormat="3"
53         />
54         <Tool
55            Name="VCManagedResourceCompilerTool"
56         />
57         <Tool
58            Name="VCResourceCompilerTool"
59         />
60         <Tool
61            Name="VCPreLinkEventTool"
62         />
63         <Tool
64            Name="VCLibrarianTool"
65         />
66         <Tool
67            Name="VCALinkTool"
68         />
69         <Tool
70            Name="VCXDCMakeTool"
71         />
72         <Tool
73            Name="VCBscMakeTool"
74         />
75         <Tool
76            Name="VCFxCopTool"
77         />
78         <Tool
79            Name="VCPostBuildEventTool"
80         />
81      </Configuration>
82      <Configuration
83         Name="Release|Win32"
84         OutputDirectory="$(SolutionDir)$(ConfigurationName)"
85         IntermediateDirectory="$(OutDir)\$(ProjectName)"
86         ConfigurationType="4"
87         InheritedPropertySheets=".\gmock_config.vsprops"
88         CharacterSet="1"
89         WholeProgramOptimization="1"
90         >
91         <Tool
92            Name="VCPreBuildEventTool"
93         />
94         <Tool
95            Name="VCCustomBuildTool"
96         />
97         <Tool
98            Name="VCXMLDataGeneratorTool"
99         />
100         <Tool
101            Name="VCWebServiceProxyGeneratorTool"
102         />
103         <Tool
104            Name="VCMIDLTool"
105         />
106         <Tool
107            Name="VCCLCompilerTool"
108            AdditionalIncludeDirectories="../../include"
109            PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
110            RuntimeLibrary="0"
111            UsePrecompiledHeader="0"
112            WarningLevel="3"
113            Detect64BitPortabilityProblems="true"
114            DebugInformationFormat="3"
115         />
116         <Tool
117            Name="VCManagedResourceCompilerTool"
118         />
119         <Tool
120            Name="VCResourceCompilerTool"
121         />
122         <Tool
123            Name="VCPreLinkEventTool"
124         />
125         <Tool
126            Name="VCLibrarianTool"
127         />
128         <Tool
129            Name="VCALinkTool"
130         />
131         <Tool
132            Name="VCXDCMakeTool"
133         />
134         <Tool
135            Name="VCBscMakeTool"
136         />
137         <Tool
138            Name="VCFxCopTool"
139         />
140         <Tool
141            Name="VCPostBuildEventTool"
142         />
143      </Configuration>
144   </Configurations>
145   <References>
146      <ProjectReference
147         ReferencedProjectIdentifier="{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
148         RelativePathToProject=".\gmock.vcproj"
149      />
150   </References>
151   <Files>
152      <Filter
153         Name="Source Files"
154         Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
155         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
156         >
157         <File
158            RelativePath="..\..\src\gmock_main.cc"
159            >
160            <FileConfiguration
161               Name="Debug|Win32"
162               >
163               <Tool
164                  Name="VCCLCompilerTool"
165                  AdditionalIncludeDirectories="../../include"
166               />
167            </FileConfiguration>
168            <FileConfiguration
169               Name="Release|Win32"
170               >
171               <Tool
172                  Name="VCCLCompilerTool"
173                  AdditionalIncludeDirectories="../../include"
174               />
175            </FileConfiguration>
176         </File>
177      </Filter>
178      <Filter
179         Name="Header Files"
180         Filter="h;hpp;hxx;hm;inl;inc;xsd"
181         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
182         >
183      </Filter>
184   </Files>
185   <Globals>
186   </Globals>
187</VisualStudioProject>
trunk/3rdparty/googletest/googlemock/msvc/2005/gmock_test.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="8.00"
5   Name="gmock_test"
6   ProjectGUID="{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
7   RootNamespace="gmock_test"
8   Keyword="Win32Proj"
9   >
10   <Platforms>
11      <Platform
12         Name="Win32"
13      />
14   </Platforms>
15   <ToolFiles>
16   </ToolFiles>
17   <Configurations>
18      <Configuration
19         Name="Debug|Win32"
20         OutputDirectory="$(SolutionDir)$(ConfigurationName)"
21         IntermediateDirectory="$(OutDir)\$(ProjectName)"
22         ConfigurationType="1"
23         InheritedPropertySheets=".\gmock_config.vsprops"
24         CharacterSet="1"
25         >
26         <Tool
27            Name="VCPreBuildEventTool"
28         />
29         <Tool
30            Name="VCCustomBuildTool"
31         />
32         <Tool
33            Name="VCXMLDataGeneratorTool"
34         />
35         <Tool
36            Name="VCWebServiceProxyGeneratorTool"
37         />
38         <Tool
39            Name="VCMIDLTool"
40         />
41         <Tool
42            Name="VCCLCompilerTool"
43            AdditionalOptions="/bigobj"
44            Optimization="0"
45            AdditionalIncludeDirectories="..\..\include;..\.."
46            PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
47            MinimalRebuild="true"
48            BasicRuntimeChecks="3"
49            RuntimeLibrary="1"
50            UsePrecompiledHeader="0"
51            WarningLevel="3"
52            Detect64BitPortabilityProblems="true"
53            DebugInformationFormat="3"
54         />
55         <Tool
56            Name="VCManagedResourceCompilerTool"
57         />
58         <Tool
59            Name="VCResourceCompilerTool"
60         />
61         <Tool
62            Name="VCPreLinkEventTool"
63         />
64         <Tool
65            Name="VCLinkerTool"
66            LinkIncremental="2"
67            GenerateDebugInformation="true"
68            SubSystem="1"
69            TargetMachine="1"
70         />
71         <Tool
72            Name="VCALinkTool"
73         />
74         <Tool
75            Name="VCManifestTool"
76         />
77         <Tool
78            Name="VCXDCMakeTool"
79         />
80         <Tool
81            Name="VCBscMakeTool"
82         />
83         <Tool
84            Name="VCFxCopTool"
85         />
86         <Tool
87            Name="VCAppVerifierTool"
88         />
89         <Tool
90            Name="VCWebDeploymentTool"
91         />
92         <Tool
93            Name="VCPostBuildEventTool"
94         />
95      </Configuration>
96      <Configuration
97         Name="Release|Win32"
98         OutputDirectory="$(SolutionDir)$(ConfigurationName)"
99         IntermediateDirectory="$(OutDir)\$(ProjectName)"
100         ConfigurationType="1"
101         InheritedPropertySheets=".\gmock_config.vsprops"
102         CharacterSet="1"
103         WholeProgramOptimization="1"
104         >
105         <Tool
106            Name="VCPreBuildEventTool"
107         />
108         <Tool
109            Name="VCCustomBuildTool"
110         />
111         <Tool
112            Name="VCXMLDataGeneratorTool"
113         />
114         <Tool
115            Name="VCWebServiceProxyGeneratorTool"
116         />
117         <Tool
118            Name="VCMIDLTool"
119         />
120         <Tool
121            Name="VCCLCompilerTool"
122            AdditionalOptions="/bigobj"
123            AdditionalIncludeDirectories="..\..\include;..\.."
124            PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
125            RuntimeLibrary="0"
126            UsePrecompiledHeader="0"
127            WarningLevel="3"
128            Detect64BitPortabilityProblems="true"
129            DebugInformationFormat="3"
130         />
131         <Tool
132            Name="VCManagedResourceCompilerTool"
133         />
134         <Tool
135            Name="VCResourceCompilerTool"
136         />
137         <Tool
138            Name="VCPreLinkEventTool"
139         />
140         <Tool
141            Name="VCLinkerTool"
142            LinkIncremental="1"
143            GenerateDebugInformation="true"
144            SubSystem="1"
145            OptimizeReferences="2"
146            EnableCOMDATFolding="2"
147            TargetMachine="1"
148         />
149         <Tool
150            Name="VCALinkTool"
151         />
152         <Tool
153            Name="VCManifestTool"
154         />
155         <Tool
156            Name="VCXDCMakeTool"
157         />
158         <Tool
159            Name="VCBscMakeTool"
160         />
161         <Tool
162            Name="VCFxCopTool"
163         />
164         <Tool
165            Name="VCAppVerifierTool"
166         />
167         <Tool
168            Name="VCWebDeploymentTool"
169         />
170         <Tool
171            Name="VCPostBuildEventTool"
172         />
173      </Configuration>
174   </Configurations>
175   <References>
176      <ProjectReference
177         ReferencedProjectIdentifier="{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
178         RelativePathToProject=".\gmock_main.vcproj"
179      />
180   </References>
181   <Files>
182      <Filter
183         Name="Source Files"
184         Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
185         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
186         >
187         <File
188            RelativePath="..\..\test\gmock_all_test.cc"
189            >
190         </File>
191      </Filter>
192      <Filter
193         Name="Header Files"
194         Filter="h;hpp;hxx;hm;inl;inc;xsd"
195         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
196         >
197      </Filter>
198   </Files>
199   <Globals>
200   </Globals>
201</VisualStudioProject>
trunk/3rdparty/googletest/googlemock/msvc/2010/gmock.sln
r0r249096
1
2Microsoft Visual Studio Solution File, Format Version 11.00
3# Visual C++ Express 2010
4Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcxproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
5EndProject
6Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcxproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
7EndProject
8Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcxproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
9EndProject
10Global
11   GlobalSection(SolutionConfigurationPlatforms) = preSolution
12      Debug|Win32 = Debug|Win32
13      Release|Win32 = Release|Win32
14   EndGlobalSection
15   GlobalSection(ProjectConfigurationPlatforms) = postSolution
16      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32
17      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32
18      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32
19      {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32
20      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32
21      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32
22      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32
23      {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32
24      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32
25      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32
26      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32
27      {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32
28   EndGlobalSection
29   GlobalSection(SolutionProperties) = preSolution
30      HideSolutionNode = FALSE
31   EndGlobalSection
32EndGlobal
trunk/3rdparty/googletest/googlemock/msvc/2010/gmock.vcxproj
r0r249096
1<?xml version="1.0" encoding="utf-8"?>
2<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3  <ItemGroup Label="ProjectConfigurations">
4    <ProjectConfiguration Include="Debug|Win32">
5      <Configuration>Debug</Configuration>
6      <Platform>Win32</Platform>
7    </ProjectConfiguration>
8    <ProjectConfiguration Include="Release|Win32">
9      <Configuration>Release</Configuration>
10      <Platform>Win32</Platform>
11    </ProjectConfiguration>
12  </ItemGroup>
13  <PropertyGroup Label="Globals">
14    <ProjectGuid>{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}</ProjectGuid>
15    <RootNamespace>gmock</RootNamespace>
16    <Keyword>Win32Proj</Keyword>
17  </PropertyGroup>
18  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
19  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
20    <ConfigurationType>StaticLibrary</ConfigurationType>
21    <CharacterSet>Unicode</CharacterSet>
22    <WholeProgramOptimization>true</WholeProgramOptimization>
23  </PropertyGroup>
24  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
25    <ConfigurationType>StaticLibrary</ConfigurationType>
26    <CharacterSet>Unicode</CharacterSet>
27  </PropertyGroup>
28  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
29  <ImportGroup Label="ExtensionSettings">
30  </ImportGroup>
31  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
32    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
33    <Import Project="gmock_config.props" />
34  </ImportGroup>
35  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
36    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
37    <Import Project="gmock_config.props" />
38  </ImportGroup>
39  <PropertyGroup Label="UserMacros" />
40  <PropertyGroup>
41    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
42    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
43    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
44    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
45    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
46  </PropertyGroup>
47  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
48    <ClCompile>
49      <Optimization>Disabled</Optimization>
50      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
51      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
52      <MinimalRebuild>true</MinimalRebuild>
53      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
54      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
55      <PrecompiledHeader>
56      </PrecompiledHeader>
57      <WarningLevel>Level3</WarningLevel>
58      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
59    </ClCompile>
60  </ItemDefinitionGroup>
61  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
62    <ClCompile>
63      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
64      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
65      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
66      <PrecompiledHeader>
67      </PrecompiledHeader>
68      <WarningLevel>Level3</WarningLevel>
69      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
70    </ClCompile>
71  </ItemDefinitionGroup>
72  <ItemGroup>
73    <ClCompile Include="..\..\src\gmock-all.cc" />
74    <ClCompile Include="$(GTestDir)\src\gtest-all.cc">
75      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
76      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
77    </ClCompile>
78  </ItemGroup>
79  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
80  <ImportGroup Label="ExtensionTargets">
81  </ImportGroup>
82</Project>
trunk/3rdparty/googletest/googlemock/msvc/2010/gmock_config.props
r0r249096
1<?xml version="1.0" encoding="utf-8"?>
2<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3  <PropertyGroup Label="UserMacros">
4    <GTestDir>../../gtest</GTestDir>
5  </PropertyGroup>
6  <PropertyGroup>
7    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
8  </PropertyGroup>
9  <ItemDefinitionGroup>
10    <ClCompile>
11      <AdditionalIncludeDirectories>$(GTestDir)/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
12    </ClCompile>
13  </ItemDefinitionGroup>
14  <ItemGroup>
15    <BuildMacro Include="GTestDir">
16      <Value>$(GTestDir)</Value>
17    </BuildMacro>
18  </ItemGroup>
19</Project>
trunk/3rdparty/googletest/googlemock/msvc/2010/gmock_main.vcxproj
r0r249096
1<?xml version="1.0" encoding="utf-8"?>
2<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3  <ItemGroup Label="ProjectConfigurations">
4    <ProjectConfiguration Include="Debug|Win32">
5      <Configuration>Debug</Configuration>
6      <Platform>Win32</Platform>
7    </ProjectConfiguration>
8    <ProjectConfiguration Include="Release|Win32">
9      <Configuration>Release</Configuration>
10      <Platform>Win32</Platform>
11    </ProjectConfiguration>
12  </ItemGroup>
13  <PropertyGroup Label="Globals">
14    <ProjectGuid>{E4EF614B-30DF-4954-8C53-580A0BF6B589}</ProjectGuid>
15    <RootNamespace>gmock_main</RootNamespace>
16    <Keyword>Win32Proj</Keyword>
17  </PropertyGroup>
18  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
19  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
20    <ConfigurationType>StaticLibrary</ConfigurationType>
21    <CharacterSet>Unicode</CharacterSet>
22    <WholeProgramOptimization>true</WholeProgramOptimization>
23  </PropertyGroup>
24  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
25    <ConfigurationType>StaticLibrary</ConfigurationType>
26    <CharacterSet>Unicode</CharacterSet>
27  </PropertyGroup>
28  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
29  <ImportGroup Label="ExtensionSettings">
30  </ImportGroup>
31  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
32    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
33    <Import Project="gmock_config.props" />
34  </ImportGroup>
35  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
36    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
37    <Import Project="gmock_config.props" />
38  </ImportGroup>
39  <PropertyGroup Label="UserMacros" />
40  <PropertyGroup>
41    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
42    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
43    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
44    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
45    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
46  </PropertyGroup>
47  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
48    <ClCompile>
49      <Optimization>Disabled</Optimization>
50      <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
51      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
52      <MinimalRebuild>true</MinimalRebuild>
53      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
54      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
55      <PrecompiledHeader>
56      </PrecompiledHeader>
57      <WarningLevel>Level3</WarningLevel>
58      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
59    </ClCompile>
60  </ItemDefinitionGroup>
61  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
62    <ClCompile>
63      <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
64      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
65      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
66      <PrecompiledHeader>
67      </PrecompiledHeader>
68      <WarningLevel>Level3</WarningLevel>
69      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
70    </ClCompile>
71  </ItemDefinitionGroup>
72  <ItemGroup>
73    <ProjectReference Include="gmock.vcxproj">
74      <Project>{34681f0d-ce45-415d-b5f2-5c662dfe3bd5}</Project>
75      <CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
76      <ReferenceOutputAssembly>true</ReferenceOutputAssembly>
77    </ProjectReference>
78  </ItemGroup>
79  <ItemGroup>
80    <ClCompile Include="..\..\src\gmock_main.cc">
81      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
82      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
83    </ClCompile>
84  </ItemGroup>
85  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
86  <ImportGroup Label="ExtensionTargets">
87  </ImportGroup>
88</Project>
trunk/3rdparty/googletest/googlemock/msvc/2010/gmock_test.vcxproj
r0r249096
1<?xml version="1.0" encoding="utf-8"?>
2<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3  <ItemGroup Label="ProjectConfigurations">
4    <ProjectConfiguration Include="Debug|Win32">
5      <Configuration>Debug</Configuration>
6      <Platform>Win32</Platform>
7    </ProjectConfiguration>
8    <ProjectConfiguration Include="Release|Win32">
9      <Configuration>Release</Configuration>
10      <Platform>Win32</Platform>
11    </ProjectConfiguration>
12  </ItemGroup>
13  <PropertyGroup Label="Globals">
14    <ProjectGuid>{F10D22F8-AC7B-4213-8720-608E7D878CD2}</ProjectGuid>
15    <RootNamespace>gmock_test</RootNamespace>
16    <Keyword>Win32Proj</Keyword>
17  </PropertyGroup>
18  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
19  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
20    <ConfigurationType>Application</ConfigurationType>
21    <CharacterSet>Unicode</CharacterSet>
22    <WholeProgramOptimization>true</WholeProgramOptimization>
23  </PropertyGroup>
24  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
25    <ConfigurationType>Application</ConfigurationType>
26    <CharacterSet>Unicode</CharacterSet>
27  </PropertyGroup>
28  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
29  <ImportGroup Label="ExtensionSettings">
30  </ImportGroup>
31  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
32    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
33    <Import Project="gmock_config.props" />
34  </ImportGroup>
35  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
36    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
37    <Import Project="gmock_config.props" />
38  </ImportGroup>
39  <PropertyGroup Label="UserMacros" />
40  <PropertyGroup>
41    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
42    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
43    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
44    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
45    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
46    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
47    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
48  </PropertyGroup>
49  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
50    <ClCompile>
51      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
52      <Optimization>Disabled</Optimization>
53      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
54      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
55      <MinimalRebuild>true</MinimalRebuild>
56      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
57      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
58      <PrecompiledHeader>
59      </PrecompiledHeader>
60      <WarningLevel>Level3</WarningLevel>
61      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
62    </ClCompile>
63    <Link>
64      <GenerateDebugInformation>true</GenerateDebugInformation>
65      <SubSystem>Console</SubSystem>
66      <TargetMachine>MachineX86</TargetMachine>
67    </Link>
68  </ItemDefinitionGroup>
69  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
70    <ClCompile>
71      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
72      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
73      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
74      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
75      <PrecompiledHeader>
76      </PrecompiledHeader>
77      <WarningLevel>Level3</WarningLevel>
78      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
79    </ClCompile>
80    <Link>
81      <GenerateDebugInformation>true</GenerateDebugInformation>
82      <SubSystem>Console</SubSystem>
83      <OptimizeReferences>true</OptimizeReferences>
84      <EnableCOMDATFolding>true</EnableCOMDATFolding>
85      <TargetMachine>MachineX86</TargetMachine>
86    </Link>
87  </ItemDefinitionGroup>
88  <ItemGroup>
89    <ProjectReference Include="gmock_main.vcxproj">
90      <Project>{e4ef614b-30df-4954-8c53-580a0bf6b589}</Project>
91      <CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
92      <ReferenceOutputAssembly>true</ReferenceOutputAssembly>
93    </ProjectReference>
94  </ItemGroup>
95  <ItemGroup>
96    <ClCompile Include="..\..\test\gmock_all_test.cc" />
97  </ItemGroup>
98  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
99  <ImportGroup Label="ExtensionTargets">
100  </ImportGroup>
101</Project>
trunk/3rdparty/googletest/googlemock/scripts/fuse_gmock_files.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""fuse_gmock_files.py v0.1.0
33Fuses Google Mock and Google Test source code into two .h files and a .cc file.
34
35SYNOPSIS
36       fuse_gmock_files.py [GMOCK_ROOT_DIR] OUTPUT_DIR
37
38       Scans GMOCK_ROOT_DIR for Google Mock and Google Test source
39       code, assuming Google Test is in the GMOCK_ROOT_DIR/gtest
40       sub-directory, and generates three files:
41       OUTPUT_DIR/gtest/gtest.h, OUTPUT_DIR/gmock/gmock.h, and
42       OUTPUT_DIR/gmock-gtest-all.cc.  Then you can build your tests
43       by adding OUTPUT_DIR to the include search path and linking
44       with OUTPUT_DIR/gmock-gtest-all.cc.  These three files contain
45       everything you need to use Google Mock.  Hence you can
46       "install" Google Mock by copying them to wherever you want.
47
48       GMOCK_ROOT_DIR can be omitted and defaults to the parent
49       directory of the directory holding this script.
50
51EXAMPLES
52       ./fuse_gmock_files.py fused_gmock
53       ./fuse_gmock_files.py path/to/unpacked/gmock fused_gmock
54
55This tool is experimental.  In particular, it assumes that there is no
56conditional inclusion of Google Mock or Google Test headers.  Please
57report any problems to googlemock@googlegroups.com.  You can read
58http://code.google.com/p/googlemock/wiki/CookBook for more
59information.
60"""
61
62__author__ = 'wan@google.com (Zhanyong Wan)'
63
64import os
65import re
66import sets
67import sys
68
69# We assume that this file is in the scripts/ directory in the Google
70# Mock root directory.
71DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
72
73# We need to call into gtest/scripts/fuse_gtest_files.py.
74sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, 'gtest/scripts'))
75import fuse_gtest_files
76gtest = fuse_gtest_files
77
78# Regex for matching '#include "gmock/..."'.
79INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"')
80
81# Where to find the source seed files.
82GMOCK_H_SEED = 'include/gmock/gmock.h'
83GMOCK_ALL_CC_SEED = 'src/gmock-all.cc'
84
85# Where to put the generated files.
86GTEST_H_OUTPUT = 'gtest/gtest.h'
87GMOCK_H_OUTPUT = 'gmock/gmock.h'
88GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc'
89
90
91def GetGTestRootDir(gmock_root):
92  """Returns the root directory of Google Test."""
93
94  return os.path.join(gmock_root, 'gtest')
95
96
97def ValidateGMockRootDir(gmock_root):
98  """Makes sure gmock_root points to a valid gmock root directory.
99
100  The function aborts the program on failure.
101  """
102
103  gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
104  gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED)
105  gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED)
106
107
108def ValidateOutputDir(output_dir):
109  """Makes sure output_dir points to a valid output directory.
110
111  The function aborts the program on failure.
112  """
113
114  gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
115  gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT)
116  gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT)
117
118
119def FuseGMockH(gmock_root, output_dir):
120  """Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
121
122  output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
123  processed_files = sets.Set()  # Holds all gmock headers we've processed.
124
125  def ProcessFile(gmock_header_path):
126    """Processes the given gmock header file."""
127
128    # We don't process the same header twice.
129    if gmock_header_path in processed_files:
130      return
131
132    processed_files.add(gmock_header_path)
133
134    # Reads each line in the given gmock header.
135    for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
136      m = INCLUDE_GMOCK_FILE_REGEX.match(line)
137      if m:
138        # It's '#include "gmock/..."' - let's process it recursively.
139        ProcessFile('include/' + m.group(1))
140      else:
141        m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
142        if m:
143          # It's '#include "gtest/foo.h"'.  We translate it to
144          # "gtest/gtest.h", regardless of what foo is, since all
145          # gtest headers are fused into gtest/gtest.h.
146
147          # There is no need to #include gtest.h twice.
148          if not gtest.GTEST_H_SEED in processed_files:
149            processed_files.add(gtest.GTEST_H_SEED)
150            output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
151        else:
152          # Otherwise we copy the line unchanged to the output file.
153          output_file.write(line)
154
155  ProcessFile(GMOCK_H_SEED)
156  output_file.close()
157
158
159def FuseGMockAllCcToFile(gmock_root, output_file):
160  """Scans folder gmock_root to fuse gmock-all.cc into output_file."""
161
162  processed_files = sets.Set()
163
164  def ProcessFile(gmock_source_file):
165    """Processes the given gmock source file."""
166
167    # We don't process the same #included file twice.
168    if gmock_source_file in processed_files:
169      return
170
171    processed_files.add(gmock_source_file)
172
173    # Reads each line in the given gmock source file.
174    for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
175      m = INCLUDE_GMOCK_FILE_REGEX.match(line)
176      if m:
177        # It's '#include "gmock/foo.h"'.  We treat it as '#include
178        # "gmock/gmock.h"', as all other gmock headers are being fused
179        # into gmock.h and cannot be #included directly.
180
181        # There is no need to #include "gmock/gmock.h" more than once.
182        if not GMOCK_H_SEED in processed_files:
183          processed_files.add(GMOCK_H_SEED)
184          output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
185      else:
186        m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
187        if m:
188          # It's '#include "gtest/..."'.
189          # There is no need to #include gtest.h as it has been
190          # #included by gtest-all.cc.
191          pass
192        else:
193          m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
194          if m:
195            # It's '#include "src/foo"' - let's process it recursively.
196            ProcessFile(m.group(1))
197          else:
198            # Otherwise we copy the line unchanged to the output file.
199            output_file.write(line)
200
201  ProcessFile(GMOCK_ALL_CC_SEED)
202
203
204def FuseGMockGTestAllCc(gmock_root, output_dir):
205  """Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
206
207  output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
208  # First, fuse gtest-all.cc into gmock-gtest-all.cc.
209  gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
210  # Next, append fused gmock-all.cc to gmock-gtest-all.cc.
211  FuseGMockAllCcToFile(gmock_root, output_file)
212  output_file.close()
213
214
215def FuseGMock(gmock_root, output_dir):
216  """Fuses gtest.h, gmock.h, and gmock-gtest-all.h."""
217
218  ValidateGMockRootDir(gmock_root)
219  ValidateOutputDir(output_dir)
220
221  gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir)
222  FuseGMockH(gmock_root, output_dir)
223  FuseGMockGTestAllCc(gmock_root, output_dir)
224
225
226def main():
227  argc = len(sys.argv)
228  if argc == 2:
229    # fuse_gmock_files.py OUTPUT_DIR
230    FuseGMock(DEFAULT_GMOCK_ROOT_DIR, sys.argv[1])
231  elif argc == 3:
232    # fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
233    FuseGMock(sys.argv[1], sys.argv[2])
234  else:
235    print __doc__
236    sys.exit(1)
237
238
239if __name__ == '__main__':
240  main()
trunk/3rdparty/googletest/googlemock/scripts/generator/LICENSE
r0r249096
1
2                                 Apache License
3                           Version 2.0, January 2004
4                        http://www.apache.org/licenses/
5
6   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
8   1. Definitions.
9
10      "License" shall mean the terms and conditions for use, reproduction,
11      and distribution as defined by Sections 1 through 9 of this document.
12
13      "Licensor" shall mean the copyright owner or entity authorized by
14      the copyright owner that is granting the License.
15
16      "Legal Entity" shall mean the union of the acting entity and all
17      other entities that control, are controlled by, or are under common
18      control with that entity. For the purposes of this definition,
19      "control" means (i) the power, direct or indirect, to cause the
20      direction or management of such entity, whether by contract or
21      otherwise, or (ii) ownership of fifty percent (50%) or more of the
22      outstanding shares, or (iii) beneficial ownership of such entity.
23
24      "You" (or "Your") shall mean an individual or Legal Entity
25      exercising permissions granted by this License.
26
27      "Source" form shall mean the preferred form for making modifications,
28      including but not limited to software source code, documentation
29      source, and configuration files.
30
31      "Object" form shall mean any form resulting from mechanical
32      transformation or translation of a Source form, including but
33      not limited to compiled object code, generated documentation,
34      and conversions to other media types.
35
36      "Work" shall mean the work of authorship, whether in Source or
37      Object form, made available under the License, as indicated by a
38      copyright notice that is included in or attached to the work
39      (an example is provided in the Appendix below).
40
41      "Derivative Works" shall mean any work, whether in Source or Object
42      form, that is based on (or derived from) the Work and for which the
43      editorial revisions, annotations, elaborations, or other modifications
44      represent, as a whole, an original work of authorship. For the purposes
45      of this License, Derivative Works shall not include works that remain
46      separable from, or merely link (or bind by name) to the interfaces of,
47      the Work and Derivative Works thereof.
48
49      "Contribution" shall mean any work of authorship, including
50      the original version of the Work and any modifications or additions
51      to that Work or Derivative Works thereof, that is intentionally
52      submitted to Licensor for inclusion in the Work by the copyright owner
53      or by an individual or Legal Entity authorized to submit on behalf of
54      the copyright owner. For the purposes of this definition, "submitted"
55      means any form of electronic, verbal, or written communication sent
56      to the Licensor or its representatives, including but not limited to
57      communication on electronic mailing lists, source code control systems,
58      and issue tracking systems that are managed by, or on behalf of, the
59      Licensor for the purpose of discussing and improving the Work, but
60      excluding communication that is conspicuously marked or otherwise
61      designated in writing by the copyright owner as "Not a Contribution."
62
63      "Contributor" shall mean Licensor and any individual or Legal Entity
64      on behalf of whom a Contribution has been received by Licensor and
65      subsequently incorporated within the Work.
66
67   2. Grant of Copyright License. Subject to the terms and conditions of
68      this License, each Contributor hereby grants to You a perpetual,
69      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70      copyright license to reproduce, prepare Derivative Works of,
71      publicly display, publicly perform, sublicense, and distribute the
72      Work and such Derivative Works in Source or Object form.
73
74   3. Grant of Patent License. Subject to the terms and conditions of
75      this License, each Contributor hereby grants to You a perpetual,
76      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77      (except as stated in this section) patent license to make, have made,
78      use, offer to sell, sell, import, and otherwise transfer the Work,
79      where such license applies only to those patent claims licensable
80      by such Contributor that are necessarily infringed by their
81      Contribution(s) alone or by combination of their Contribution(s)
82      with the Work to which such Contribution(s) was submitted. If You
83      institute patent litigation against any entity (including a
84      cross-claim or counterclaim in a lawsuit) alleging that the Work
85      or a Contribution incorporated within the Work constitutes direct
86      or contributory patent infringement, then any patent licenses
87      granted to You under this License for that Work shall terminate
88      as of the date such litigation is filed.
89
90   4. Redistribution. You may reproduce and distribute copies of the
91      Work or Derivative Works thereof in any medium, with or without
92      modifications, and in Source or Object form, provided that You
93      meet the following conditions:
94
95      (a) You must give any other recipients of the Work or
96          Derivative Works a copy of this License; and
97
98      (b) You must cause any modified files to carry prominent notices
99          stating that You changed the files; and
100
101      (c) You must retain, in the Source form of any Derivative Works
102          that You distribute, all copyright, patent, trademark, and
103          attribution notices from the Source form of the Work,
104          excluding those notices that do not pertain to any part of
105          the Derivative Works; and
106
107      (d) If the Work includes a "NOTICE" text file as part of its
108          distribution, then any Derivative Works that You distribute must
109          include a readable copy of the attribution notices contained
110          within such NOTICE file, excluding those notices that do not
111          pertain to any part of the Derivative Works, in at least one
112          of the following places: within a NOTICE text file distributed
113          as part of the Derivative Works; within the Source form or
114          documentation, if provided along with the Derivative Works; or,
115          within a display generated by the Derivative Works, if and
116          wherever such third-party notices normally appear. The contents
117          of the NOTICE file are for informational purposes only and
118          do not modify the License. You may add Your own attribution
119          notices within Derivative Works that You distribute, alongside
120          or as an addendum to the NOTICE text from the Work, provided
121          that such additional attribution notices cannot be construed
122          as modifying the License.
123
124      You may add Your own copyright statement to Your modifications and
125      may provide additional or different license terms and conditions
126      for use, reproduction, or distribution of Your modifications, or
127      for any such Derivative Works as a whole, provided Your use,
128      reproduction, and distribution of the Work otherwise complies with
129      the conditions stated in this License.
130
131   5. Submission of Contributions. Unless You explicitly state otherwise,
132      any Contribution intentionally submitted for inclusion in the Work
133      by You to the Licensor shall be under the terms and conditions of
134      this License, without any additional terms or conditions.
135      Notwithstanding the above, nothing herein shall supersede or modify
136      the terms of any separate license agreement you may have executed
137      with Licensor regarding such Contributions.
138
139   6. Trademarks. This License does not grant permission to use the trade
140      names, trademarks, service marks, or product names of the Licensor,
141      except as required for reasonable and customary use in describing the
142      origin of the Work and reproducing the content of the NOTICE file.
143
144   7. Disclaimer of Warranty. Unless required by applicable law or
145      agreed to in writing, Licensor provides the Work (and each
146      Contributor provides its Contributions) on an "AS IS" BASIS,
147      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148      implied, including, without limitation, any warranties or conditions
149      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150      PARTICULAR PURPOSE. You are solely responsible for determining the
151      appropriateness of using or redistributing the Work and assume any
152      risks associated with Your exercise of permissions under this License.
153
154   8. Limitation of Liability. In no event and under no legal theory,
155      whether in tort (including negligence), contract, or otherwise,
156      unless required by applicable law (such as deliberate and grossly
157      negligent acts) or agreed to in writing, shall any Contributor be
158      liable to You for damages, including any direct, indirect, special,
159      incidental, or consequential damages of any character arising as a
160      result of this License or out of the use or inability to use the
161      Work (including but not limited to damages for loss of goodwill,
162      work stoppage, computer failure or malfunction, or any and all
163      other commercial damages or losses), even if such Contributor
164      has been advised of the possibility of such damages.
165
166   9. Accepting Warranty or Additional Liability. While redistributing
167      the Work or Derivative Works thereof, You may choose to offer,
168      and charge a fee for, acceptance of support, warranty, indemnity,
169      or other liability obligations and/or rights consistent with this
170      License. However, in accepting such obligations, You may act only
171      on Your own behalf and on Your sole responsibility, not on behalf
172      of any other Contributor, and only if You agree to indemnify,
173      defend, and hold each Contributor harmless for any liability
174      incurred by, or claims asserted against, such Contributor by reason
175      of your accepting any such warranty or additional liability.
176
177   END OF TERMS AND CONDITIONS
178
179   APPENDIX: How to apply the Apache License to your work.
180
181      To apply the Apache License to your work, attach the following
182      boilerplate notice, with the fields enclosed by brackets "[]"
183      replaced with your own identifying information. (Don't include
184      the brackets!)  The text should be enclosed in the appropriate
185      comment syntax for the file format. We also recommend that a
186      file or class name and description of purpose be included on the
187      same "printed page" as the copyright notice for easier
188      identification within third-party archives.
189
190   Copyright [2007] Neal Norwitz
191   Portions Copyright [2007] Google Inc.
192
193   Licensed under the Apache License, Version 2.0 (the "License");
194   you may not use this file except in compliance with the License.
195   You may obtain a copy of the License at
196
197       http://www.apache.org/licenses/LICENSE-2.0
198
199   Unless required by applicable law or agreed to in writing, software
200   distributed under the License is distributed on an "AS IS" BASIS,
201   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202   See the License for the specific language governing permissions and
203   limitations under the License.
trunk/3rdparty/googletest/googlemock/scripts/generator/README
r0r249096
1
2The Google Mock class generator is an application that is part of cppclean.
3For more information about cppclean, see the README.cppclean file or
4visit http://code.google.com/p/cppclean/
5
6cppclean requires Python 2.3.5 or later.  If you don't have Python installed
7on your system, you will also need to install it.  You can download Python
8from:  http://www.python.org/download/releases/
9
10To use the Google Mock class generator, you need to call it
11on the command line passing the header file and class for which you want
12to generate a Google Mock class.
13
14Make sure to install the scripts somewhere in your path.  Then you can
15run the program.
16
17  gmock_gen.py header-file.h [ClassName]...
18
19If no ClassNames are specified, all classes in the file are emitted.
20
21To change the indentation from the default of 2, set INDENT in
22the environment.  For example to use an indent of 4 spaces:
23
24INDENT=4 gmock_gen.py header-file.h ClassName
25
26This version was made from SVN revision 281 in the cppclean repository.
27
28Known Limitations
29-----------------
30Not all code will be generated properly.  For example, when mocking templated
31classes, the template information is lost.  You will need to add the template
32information manually.
33
34Not all permutations of using multiple pointers/references will be rendered
35properly.  These will also have to be fixed manually.
trunk/3rdparty/googletest/googlemock/scripts/generator/README.cppclean
r0r249096
1Goal:
2-----
3  CppClean attempts to find problems in C++ source that slow development
4  in large code bases, for example various forms of unused code.
5  Unused code can be unused functions, methods, data members, types, etc
6  to unnecessary #include directives.  Unnecessary #includes can cause
7  considerable extra compiles increasing the edit-compile-run cycle.
8
9  The project home page is:   http://code.google.com/p/cppclean/
10
11
12Features:
13---------
14 * Find and print C++ language constructs: classes, methods, functions, etc.
15 * Find classes with virtual methods, no virtual destructor, and no bases
16 * Find global/static data that are potential problems when using threads
17 * Unnecessary forward class declarations
18 * Unnecessary function declarations
19 * Undeclared function definitions
20 * (planned) Find unnecessary header files #included
21   - No direct reference to anything in the header
22   - Header is unnecessary if classes were forward declared instead
23 * (planned) Source files that reference headers not directly #included,
24   ie, files that rely on a transitive #include from another header
25 * (planned) Unused members (private, protected, & public) methods and data
26 * (planned) Store AST in a SQL database so relationships can be queried
27
28AST is Abstract Syntax Tree, a representation of parsed source code.
29http://en.wikipedia.org/wiki/Abstract_syntax_tree
30
31
32System Requirements:
33--------------------
34 * Python 2.4 or later (2.3 probably works too)
35 * Works on Windows (untested), Mac OS X, and Unix
36
37
38How to Run:
39-----------
40  For all examples, it is assumed that cppclean resides in a directory called
41  /cppclean.
42
43  To print warnings for classes with virtual methods, no virtual destructor and
44  no base classes:
45
46      /cppclean/run.sh nonvirtual_dtors.py file1.h file2.h file3.cc ...
47
48  To print all the functions defined in header file(s):
49
50      /cppclean/run.sh functions.py file1.h file2.h ...
51
52  All the commands take multiple files on the command line.  Other programs
53  include: find_warnings, headers, methods, and types.  Some other programs
54  are available, but used primarily for debugging.
55
56  run.sh is a simple wrapper that sets PYTHONPATH to /cppclean and then
57  runs the program in /cppclean/cpp/PROGRAM.py.  There is currently
58  no equivalent for Windows.  Contributions for a run.bat file
59  would be greatly appreciated.
60
61
62How to Configure:
63-----------------
64  You can add a siteheaders.py file in /cppclean/cpp to configure where
65  to look for other headers (typically -I options passed to a compiler).
66  Currently two values are supported:  _TRANSITIVE and GetIncludeDirs.
67  _TRANSITIVE should be set to a boolean value (True or False) indicating
68  whether to transitively process all header files.  The default is False.
69
70  GetIncludeDirs is a function that takes a single argument and returns
71  a sequence of directories to include.  This can be a generator or
72  return a static list.
73
74      def GetIncludeDirs(filename):
75          return ['/some/path/with/other/headers']
76
77      # Here is a more complicated example.
78      def GetIncludeDirs(filename):
79          yield '/path1'
80          yield os.path.join('/path2', os.path.dirname(filename))
81          yield '/path3'
82
83
84How to Test:
85------------
86  For all examples, it is assumed that cppclean resides in a directory called
87  /cppclean.  The tests require
88
89  cd /cppclean
90  make test
91  # To generate expected results after a change:
92  make expected
93
94
95Current Status:
96---------------
97  The parser works pretty well for header files, parsing about 99% of Google's
98  header files.  Anything which inspects structure of C++ source files should
99  work reasonably well.  Function bodies are not transformed to an AST,
100  but left as tokens.  Much work is still needed on finding unused header files
101  and storing an AST in a database.
102
103
104Non-goals:
105----------
106 * Parsing all valid C++ source
107 * Handling invalid C++ source gracefully
108 * Compiling to machine code (or anything beyond an AST)
109
110
111Contact:
112--------
113  If you used cppclean, I would love to hear about your experiences
114  cppclean@googlegroups.com.  Even if you don't use cppclean, I'd like to
115  hear from you.  :-)  (You can contact me directly at:  nnorwitz@gmail.com)
trunk/3rdparty/googletest/googlemock/scripts/generator/cpp/__init__.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2007 Neal Norwitz
4# Portions Copyright 2007 Google Inc.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Generate an Abstract Syntax Tree (AST) for C++."""
19
20__author__ = 'nnorwitz@google.com (Neal Norwitz)'
21
22
23# TODO:
24#  * Tokens should never be exported, need to convert to Nodes
25#    (return types, parameters, etc.)
26#  * Handle static class data for templatized classes
27#  * Handle casts (both C++ and C-style)
28#  * Handle conditions and loops (if/else, switch, for, while/do)
29#
30# TODO much, much later:
31#  * Handle #define
32#  * exceptions
33
34
35try:
36    # Python 3.x
37    import builtins
38except ImportError:
39    # Python 2.x
40    import __builtin__ as builtins
41
42import sys
43import traceback
44
45from cpp import keywords
46from cpp import tokenize
47from cpp import utils
48
49
50if not hasattr(builtins, 'reversed'):
51    # Support Python 2.3 and earlier.
52    def reversed(seq):
53        for i in range(len(seq)-1, -1, -1):
54            yield seq[i]
55
56if not hasattr(builtins, 'next'):
57    # Support Python 2.5 and earlier.
58    def next(obj):
59        return obj.next()
60
61
62VISIBILITY_PUBLIC, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE = range(3)
63
64FUNCTION_NONE = 0x00
65FUNCTION_CONST = 0x01
66FUNCTION_VIRTUAL = 0x02
67FUNCTION_PURE_VIRTUAL = 0x04
68FUNCTION_CTOR = 0x08
69FUNCTION_DTOR = 0x10
70FUNCTION_ATTRIBUTE = 0x20
71FUNCTION_UNKNOWN_ANNOTATION = 0x40
72FUNCTION_THROW = 0x80
73FUNCTION_OVERRIDE = 0x100
74
75"""
76These are currently unused.  Should really handle these properly at some point.
77
78TYPE_MODIFIER_INLINE   = 0x010000
79TYPE_MODIFIER_EXTERN   = 0x020000
80TYPE_MODIFIER_STATIC   = 0x040000
81TYPE_MODIFIER_CONST    = 0x080000
82TYPE_MODIFIER_REGISTER = 0x100000
83TYPE_MODIFIER_VOLATILE = 0x200000
84TYPE_MODIFIER_MUTABLE  = 0x400000
85
86TYPE_MODIFIER_MAP = {
87    'inline': TYPE_MODIFIER_INLINE,
88    'extern': TYPE_MODIFIER_EXTERN,
89    'static': TYPE_MODIFIER_STATIC,
90    'const': TYPE_MODIFIER_CONST,
91    'register': TYPE_MODIFIER_REGISTER,
92    'volatile': TYPE_MODIFIER_VOLATILE,
93    'mutable': TYPE_MODIFIER_MUTABLE,
94    }
95"""
96
97_INTERNAL_TOKEN = 'internal'
98_NAMESPACE_POP = 'ns-pop'
99
100
101# TODO(nnorwitz): use this as a singleton for templated_types, etc
102# where we don't want to create a new empty dict each time.  It is also const.
103class _NullDict(object):
104    __contains__ = lambda self: False
105    keys = values = items = iterkeys = itervalues = iteritems = lambda self: ()
106
107
108# TODO(nnorwitz): move AST nodes into a separate module.
109class Node(object):
110    """Base AST node."""
111
112    def __init__(self, start, end):
113        self.start = start
114        self.end = end
115
116    def IsDeclaration(self):
117        """Returns bool if this node is a declaration."""
118        return False
119
120    def IsDefinition(self):
121        """Returns bool if this node is a definition."""
122        return False
123
124    def IsExportable(self):
125        """Returns bool if this node exportable from a header file."""
126        return False
127
128    def Requires(self, node):
129        """Does this AST node require the definition of the node passed in?"""
130        return False
131
132    def XXX__str__(self):
133        return self._StringHelper(self.__class__.__name__, '')
134
135    def _StringHelper(self, name, suffix):
136        if not utils.DEBUG:
137            return '%s(%s)' % (name, suffix)
138        return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
139
140    def __repr__(self):
141        return str(self)
142
143
144class Define(Node):
145    def __init__(self, start, end, name, definition):
146        Node.__init__(self, start, end)
147        self.name = name
148        self.definition = definition
149
150    def __str__(self):
151        value = '%s %s' % (self.name, self.definition)
152        return self._StringHelper(self.__class__.__name__, value)
153
154
155class Include(Node):
156    def __init__(self, start, end, filename, system):
157        Node.__init__(self, start, end)
158        self.filename = filename
159        self.system = system
160
161    def __str__(self):
162        fmt = '"%s"'
163        if self.system:
164            fmt = '<%s>'
165        return self._StringHelper(self.__class__.__name__, fmt % self.filename)
166
167
168class Goto(Node):
169    def __init__(self, start, end, label):
170        Node.__init__(self, start, end)
171        self.label = label
172
173    def __str__(self):
174        return self._StringHelper(self.__class__.__name__, str(self.label))
175
176
177class Expr(Node):
178    def __init__(self, start, end, expr):
179        Node.__init__(self, start, end)
180        self.expr = expr
181
182    def Requires(self, node):
183        # TODO(nnorwitz): impl.
184        return False
185
186    def __str__(self):
187        return self._StringHelper(self.__class__.__name__, str(self.expr))
188
189
190class Return(Expr):
191    pass
192
193
194class Delete(Expr):
195    pass
196
197
198class Friend(Expr):
199    def __init__(self, start, end, expr, namespace):
200        Expr.__init__(self, start, end, expr)
201        self.namespace = namespace[:]
202
203
204class Using(Node):
205    def __init__(self, start, end, names):
206        Node.__init__(self, start, end)
207        self.names = names
208
209    def __str__(self):
210        return self._StringHelper(self.__class__.__name__, str(self.names))
211
212
213class Parameter(Node):
214    def __init__(self, start, end, name, parameter_type, default):
215        Node.__init__(self, start, end)
216        self.name = name
217        self.type = parameter_type
218        self.default = default
219
220    def Requires(self, node):
221        # TODO(nnorwitz): handle namespaces, etc.
222        return self.type.name == node.name
223
224    def __str__(self):
225        name = str(self.type)
226        suffix = '%s %s' % (name, self.name)
227        if self.default:
228            suffix += ' = ' + ''.join([d.name for d in self.default])
229        return self._StringHelper(self.__class__.__name__, suffix)
230
231
232class _GenericDeclaration(Node):
233    def __init__(self, start, end, name, namespace):
234        Node.__init__(self, start, end)
235        self.name = name
236        self.namespace = namespace[:]
237
238    def FullName(self):
239        prefix = ''
240        if self.namespace and self.namespace[-1]:
241            prefix = '::'.join(self.namespace) + '::'
242        return prefix + self.name
243
244    def _TypeStringHelper(self, suffix):
245        if self.namespace:
246            names = [n or '<anonymous>' for n in self.namespace]
247            suffix += ' in ' + '::'.join(names)
248        return self._StringHelper(self.__class__.__name__, suffix)
249
250
251# TODO(nnorwitz): merge with Parameter in some way?
252class VariableDeclaration(_GenericDeclaration):
253    def __init__(self, start, end, name, var_type, initial_value, namespace):
254        _GenericDeclaration.__init__(self, start, end, name, namespace)
255        self.type = var_type
256        self.initial_value = initial_value
257
258    def Requires(self, node):
259        # TODO(nnorwitz): handle namespaces, etc.
260        return self.type.name == node.name
261
262    def ToString(self):
263        """Return a string that tries to reconstitute the variable decl."""
264        suffix = '%s %s' % (self.type, self.name)
265        if self.initial_value:
266            suffix += ' = ' + self.initial_value
267        return suffix
268
269    def __str__(self):
270        return self._StringHelper(self.__class__.__name__, self.ToString())
271
272
273class Typedef(_GenericDeclaration):
274    def __init__(self, start, end, name, alias, namespace):
275        _GenericDeclaration.__init__(self, start, end, name, namespace)
276        self.alias = alias
277
278    def IsDefinition(self):
279        return True
280
281    def IsExportable(self):
282        return True
283
284    def Requires(self, node):
285        # TODO(nnorwitz): handle namespaces, etc.
286        name = node.name
287        for token in self.alias:
288            if token is not None and name == token.name:
289                return True
290        return False
291
292    def __str__(self):
293        suffix = '%s, %s' % (self.name, self.alias)
294        return self._TypeStringHelper(suffix)
295
296
297class _NestedType(_GenericDeclaration):
298    def __init__(self, start, end, name, fields, namespace):
299        _GenericDeclaration.__init__(self, start, end, name, namespace)
300        self.fields = fields
301
302    def IsDefinition(self):
303        return True
304
305    def IsExportable(self):
306        return True
307
308    def __str__(self):
309        suffix = '%s, {%s}' % (self.name, self.fields)
310        return self._TypeStringHelper(suffix)
311
312
313class Union(_NestedType):
314    pass
315
316
317class Enum(_NestedType):
318    pass
319
320
321class Class(_GenericDeclaration):
322    def __init__(self, start, end, name, bases, templated_types, body, namespace):
323        _GenericDeclaration.__init__(self, start, end, name, namespace)
324        self.bases = bases
325        self.body = body
326        self.templated_types = templated_types
327
328    def IsDeclaration(self):
329        return self.bases is None and self.body is None
330
331    def IsDefinition(self):
332        return not self.IsDeclaration()
333
334    def IsExportable(self):
335        return not self.IsDeclaration()
336
337    def Requires(self, node):
338        # TODO(nnorwitz): handle namespaces, etc.
339        if self.bases:
340            for token_list in self.bases:
341                # TODO(nnorwitz): bases are tokens, do name comparision.
342                for token in token_list:
343                    if token.name == node.name:
344                        return True
345        # TODO(nnorwitz): search in body too.
346        return False
347
348    def __str__(self):
349        name = self.name
350        if self.templated_types:
351            name += '<%s>' % self.templated_types
352        suffix = '%s, %s, %s' % (name, self.bases, self.body)
353        return self._TypeStringHelper(suffix)
354
355
356class Struct(Class):
357    pass
358
359
360class Function(_GenericDeclaration):
361    def __init__(self, start, end, name, return_type, parameters,
362                 modifiers, templated_types, body, namespace):
363        _GenericDeclaration.__init__(self, start, end, name, namespace)
364        converter = TypeConverter(namespace)
365        self.return_type = converter.CreateReturnType(return_type)
366        self.parameters = converter.ToParameters(parameters)
367        self.modifiers = modifiers
368        self.body = body
369        self.templated_types = templated_types
370
371    def IsDeclaration(self):
372        return self.body is None
373
374    def IsDefinition(self):
375        return self.body is not None
376
377    def IsExportable(self):
378        if self.return_type and 'static' in self.return_type.modifiers:
379            return False
380        return None not in self.namespace
381
382    def Requires(self, node):
383        if self.parameters:
384            # TODO(nnorwitz): parameters are tokens, do name comparision.
385            for p in self.parameters:
386                if p.name == node.name:
387                    return True
388        # TODO(nnorwitz): search in body too.
389        return False
390
391    def __str__(self):
392        # TODO(nnorwitz): add templated_types.
393        suffix = ('%s %s(%s), 0x%02x, %s' %
394                  (self.return_type, self.name, self.parameters,
395                   self.modifiers, self.body))
396        return self._TypeStringHelper(suffix)
397
398
399class Method(Function):
400    def __init__(self, start, end, name, in_class, return_type, parameters,
401                 modifiers, templated_types, body, namespace):
402        Function.__init__(self, start, end, name, return_type, parameters,
403                          modifiers, templated_types, body, namespace)
404        # TODO(nnorwitz): in_class could also be a namespace which can
405        # mess up finding functions properly.
406        self.in_class = in_class
407
408
409class Type(_GenericDeclaration):
410    """Type used for any variable (eg class, primitive, struct, etc)."""
411
412    def __init__(self, start, end, name, templated_types, modifiers,
413                 reference, pointer, array):
414        """
415        Args:
416          name: str name of main type
417          templated_types: [Class (Type?)] template type info between <>
418          modifiers: [str] type modifiers (keywords) eg, const, mutable, etc.
419          reference, pointer, array: bools
420        """
421        _GenericDeclaration.__init__(self, start, end, name, [])
422        self.templated_types = templated_types
423        if not name and modifiers:
424            self.name = modifiers.pop()
425        self.modifiers = modifiers
426        self.reference = reference
427        self.pointer = pointer
428        self.array = array
429
430    def __str__(self):
431        prefix = ''
432        if self.modifiers:
433            prefix = ' '.join(self.modifiers) + ' '
434        name = str(self.name)
435        if self.templated_types:
436            name += '<%s>' % self.templated_types
437        suffix = prefix + name
438        if self.reference:
439            suffix += '&'
440        if self.pointer:
441            suffix += '*'
442        if self.array:
443            suffix += '[]'
444        return self._TypeStringHelper(suffix)
445
446    # By definition, Is* are always False.  A Type can only exist in
447    # some sort of variable declaration, parameter, or return value.
448    def IsDeclaration(self):
449        return False
450
451    def IsDefinition(self):
452        return False
453
454    def IsExportable(self):
455        return False
456
457
458class TypeConverter(object):
459
460    def __init__(self, namespace_stack):
461        self.namespace_stack = namespace_stack
462
463    def _GetTemplateEnd(self, tokens, start):
464        count = 1
465        end = start
466        while 1:
467            token = tokens[end]
468            end += 1
469            if token.name == '<':
470                count += 1
471            elif token.name == '>':
472                count -= 1
473                if count == 0:
474                    break
475        return tokens[start:end-1], end
476
477    def ToType(self, tokens):
478        """Convert [Token,...] to [Class(...), ] useful for base classes.
479        For example, code like class Foo : public Bar<x, y> { ... };
480        the "Bar<x, y>" portion gets converted to an AST.
481
482        Returns:
483          [Class(...), ...]
484        """
485        result = []
486        name_tokens = []
487        reference = pointer = array = False
488
489        def AddType(templated_types):
490            # Partition tokens into name and modifier tokens.
491            names = []
492            modifiers = []
493            for t in name_tokens:
494                if keywords.IsKeyword(t.name):
495                    modifiers.append(t.name)
496                else:
497                    names.append(t.name)
498            name = ''.join(names)
499            if name_tokens:
500                result.append(Type(name_tokens[0].start, name_tokens[-1].end,
501                                   name, templated_types, modifiers,
502                                   reference, pointer, array))
503            del name_tokens[:]
504
505        i = 0
506        end = len(tokens)
507        while i < end:
508            token = tokens[i]
509            if token.name == '<':
510                new_tokens, new_end = self._GetTemplateEnd(tokens, i+1)
511                AddType(self.ToType(new_tokens))
512                # If there is a comma after the template, we need to consume
513                # that here otherwise it becomes part of the name.
514                i = new_end
515                reference = pointer = array = False
516            elif token.name == ',':
517                AddType([])
518                reference = pointer = array = False
519            elif token.name == '*':
520                pointer = True
521            elif token.name == '&':
522                reference = True
523            elif token.name == '[':
524               pointer = True
525            elif token.name == ']':
526                pass
527            else:
528                name_tokens.append(token)
529            i += 1
530
531        if name_tokens:
532            # No '<' in the tokens, just a simple name and no template.
533            AddType([])
534        return result
535
536    def DeclarationToParts(self, parts, needs_name_removed):
537        name = None
538        default = []
539        if needs_name_removed:
540            # Handle default (initial) values properly.
541            for i, t in enumerate(parts):
542                if t.name == '=':
543                    default = parts[i+1:]
544                    name = parts[i-1].name
545                    if name == ']' and parts[i-2].name == '[':
546                        name = parts[i-3].name
547                        i -= 1
548                    parts = parts[:i-1]
549                    break
550            else:
551                if parts[-1].token_type == tokenize.NAME:
552                    name = parts.pop().name
553                else:
554                    # TODO(nnorwitz): this is a hack that happens for code like
555                    # Register(Foo<T>); where it thinks this is a function call
556                    # but it's actually a declaration.
557                    name = '???'
558        modifiers = []
559        type_name = []
560        other_tokens = []
561        templated_types = []
562        i = 0
563        end = len(parts)
564        while i < end:
565            p = parts[i]
566            if keywords.IsKeyword(p.name):
567                modifiers.append(p.name)
568            elif p.name == '<':
569                templated_tokens, new_end = self._GetTemplateEnd(parts, i+1)
570                templated_types = self.ToType(templated_tokens)
571                i = new_end - 1
572                # Don't add a spurious :: to data members being initialized.
573                next_index = i + 1
574                if next_index < end and parts[next_index].name == '::':
575                    i += 1
576            elif p.name in ('[', ']', '='):
577                # These are handled elsewhere.
578                other_tokens.append(p)
579            elif p.name not in ('*', '&', '>'):
580                # Ensure that names have a space between them.
581                if (type_name and type_name[-1].token_type == tokenize.NAME and
582                    p.token_type == tokenize.NAME):
583                    type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0))
584                type_name.append(p)
585            else:
586                other_tokens.append(p)
587            i += 1
588        type_name = ''.join([t.name for t in type_name])
589        return name, type_name, templated_types, modifiers, default, other_tokens
590
591    def ToParameters(self, tokens):
592        if not tokens:
593            return []
594
595        result = []
596        name = type_name = ''
597        type_modifiers = []
598        pointer = reference = array = False
599        first_token = None
600        default = []
601
602        def AddParameter(end):
603            if default:
604                del default[0]  # Remove flag.
605            parts = self.DeclarationToParts(type_modifiers, True)
606            (name, type_name, templated_types, modifiers,
607             unused_default, unused_other_tokens) = parts
608            parameter_type = Type(first_token.start, first_token.end,
609                                  type_name, templated_types, modifiers,
610                                  reference, pointer, array)
611            p = Parameter(first_token.start, end, name,
612                          parameter_type, default)
613            result.append(p)
614
615        template_count = 0
616        for s in tokens:
617            if not first_token:
618                first_token = s
619            if s.name == '<':
620                template_count += 1
621            elif s.name == '>':
622                template_count -= 1
623            if template_count > 0:
624                type_modifiers.append(s)
625                continue
626
627            if s.name == ',':
628                AddParameter(s.start)
629                name = type_name = ''
630                type_modifiers = []
631                pointer = reference = array = False
632                first_token = None
633                default = []
634            elif s.name == '*':
635                pointer = True
636            elif s.name == '&':
637                reference = True
638            elif s.name == '[':
639                array = True
640            elif s.name == ']':
641                pass  # Just don't add to type_modifiers.
642            elif s.name == '=':
643                # Got a default value.  Add any value (None) as a flag.
644                default.append(None)
645            elif default:
646                default.append(s)
647            else:
648                type_modifiers.append(s)
649        AddParameter(tokens[-1].end)
650        return result
651
652    def CreateReturnType(self, return_type_seq):
653        if not return_type_seq:
654            return None
655        start = return_type_seq[0].start
656        end = return_type_seq[-1].end
657        _, name, templated_types, modifiers, default, other_tokens = \
658           self.DeclarationToParts(return_type_seq, False)
659        names = [n.name for n in other_tokens]
660        reference = '&' in names
661        pointer = '*' in names
662        array = '[' in names
663        return Type(start, end, name, templated_types, modifiers,
664                    reference, pointer, array)
665
666    def GetTemplateIndices(self, names):
667        # names is a list of strings.
668        start = names.index('<')
669        end = len(names) - 1
670        while end > 0:
671            if names[end] == '>':
672                break
673            end -= 1
674        return start, end+1
675
676class AstBuilder(object):
677    def __init__(self, token_stream, filename, in_class='', visibility=None,
678                 namespace_stack=[]):
679        self.tokens = token_stream
680        self.filename = filename
681        # TODO(nnorwitz): use a better data structure (deque) for the queue.
682        # Switching directions of the "queue" improved perf by about 25%.
683        # Using a deque should be even better since we access from both sides.
684        self.token_queue = []
685        self.namespace_stack = namespace_stack[:]
686        self.in_class = in_class
687        if in_class is None:
688            self.in_class_name_only = None
689        else:
690            self.in_class_name_only = in_class.split('::')[-1]
691        self.visibility = visibility
692        self.in_function = False
693        self.current_token = None
694        # Keep the state whether we are currently handling a typedef or not.
695        self._handling_typedef = False
696
697        self.converter = TypeConverter(self.namespace_stack)
698
699    def HandleError(self, msg, token):
700        printable_queue = list(reversed(self.token_queue[-20:]))
701        sys.stderr.write('Got %s in %s @ %s %s\n' %
702                         (msg, self.filename, token, printable_queue))
703
704    def Generate(self):
705        while 1:
706            token = self._GetNextToken()
707            if not token:
708                break
709
710            # Get the next token.
711            self.current_token = token
712
713            # Dispatch on the next token type.
714            if token.token_type == _INTERNAL_TOKEN:
715                if token.name == _NAMESPACE_POP:
716                    self.namespace_stack.pop()
717                continue
718
719            try:
720                result = self._GenerateOne(token)
721                if result is not None:
722                    yield result
723            except:
724                self.HandleError('exception', token)
725                raise
726
727    def _CreateVariable(self, pos_token, name, type_name, type_modifiers,
728                        ref_pointer_name_seq, templated_types, value=None):
729        reference = '&' in ref_pointer_name_seq
730        pointer = '*' in ref_pointer_name_seq
731        array = '[' in ref_pointer_name_seq
732        var_type = Type(pos_token.start, pos_token.end, type_name,
733                        templated_types, type_modifiers,
734                        reference, pointer, array)
735        return VariableDeclaration(pos_token.start, pos_token.end,
736                                   name, var_type, value, self.namespace_stack)
737
738    def _GenerateOne(self, token):
739        if token.token_type == tokenize.NAME:
740            if (keywords.IsKeyword(token.name) and
741                not keywords.IsBuiltinType(token.name)):
742                method = getattr(self, 'handle_' + token.name)
743                return method()
744            elif token.name == self.in_class_name_only:
745                # The token name is the same as the class, must be a ctor if
746                # there is a paren.  Otherwise, it's the return type.
747                # Peek ahead to get the next token to figure out which.
748                next = self._GetNextToken()
749                self._AddBackToken(next)
750                if next.token_type == tokenize.SYNTAX and next.name == '(':
751                    return self._GetMethod([token], FUNCTION_CTOR, None, True)
752                # Fall through--handle like any other method.
753
754            # Handle data or function declaration/definition.
755            syntax = tokenize.SYNTAX
756            temp_tokens, last_token = \
757                self._GetVarTokensUpTo(syntax, '(', ';', '{', '[')
758            temp_tokens.insert(0, token)
759            if last_token.name == '(':
760                # If there is an assignment before the paren,
761                # this is an expression, not a method.
762                expr = bool([e for e in temp_tokens if e.name == '='])
763                if expr:
764                    new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';')
765                    temp_tokens.append(last_token)
766                    temp_tokens.extend(new_temp)
767                    last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0)
768
769            if last_token.name == '[':
770                # Handle array, this isn't a method, unless it's an operator.
771                # TODO(nnorwitz): keep the size somewhere.
772                # unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']')
773                temp_tokens.append(last_token)
774                if temp_tokens[-2].name == 'operator':
775                    temp_tokens.append(self._GetNextToken())
776                else:
777                    temp_tokens2, last_token = \
778                        self._GetVarTokensUpTo(tokenize.SYNTAX, ';')
779                    temp_tokens.extend(temp_tokens2)
780
781            if last_token.name == ';':
782                # Handle data, this isn't a method.
783                parts = self.converter.DeclarationToParts(temp_tokens, True)
784                (name, type_name, templated_types, modifiers, default,
785                 unused_other_tokens) = parts
786
787                t0 = temp_tokens[0]
788                names = [t.name for t in temp_tokens]
789                if templated_types:
790                    start, end = self.converter.GetTemplateIndices(names)
791                    names = names[:start] + names[end:]
792                default = ''.join([t.name for t in default])
793                return self._CreateVariable(t0, name, type_name, modifiers,
794                                            names, templated_types, default)
795            if last_token.name == '{':
796                self._AddBackTokens(temp_tokens[1:])
797                self._AddBackToken(last_token)
798                method_name = temp_tokens[0].name
799                method = getattr(self, 'handle_' + method_name, None)
800                if not method:
801                    # Must be declaring a variable.
802                    # TODO(nnorwitz): handle the declaration.
803                    return None
804                return method()
805            return self._GetMethod(temp_tokens, 0, None, False)
806        elif token.token_type == tokenize.SYNTAX:
807            if token.name == '~' and self.in_class:
808                # Must be a dtor (probably not in method body).
809                token = self._GetNextToken()
810                # self.in_class can contain A::Name, but the dtor will only
811                # be Name.  Make sure to compare against the right value.
812                if (token.token_type == tokenize.NAME and
813                    token.name == self.in_class_name_only):
814                    return self._GetMethod([token], FUNCTION_DTOR, None, True)
815            # TODO(nnorwitz): handle a lot more syntax.
816        elif token.token_type == tokenize.PREPROCESSOR:
817            # TODO(nnorwitz): handle more preprocessor directives.
818            # token starts with a #, so remove it and strip whitespace.
819            name = token.name[1:].lstrip()
820            if name.startswith('include'):
821                # Remove "include".
822                name = name[7:].strip()
823                assert name
824                # Handle #include \<newline> "header-on-second-line.h".
825                if name.startswith('\\'):
826                    name = name[1:].strip()
827                assert name[0] in '<"', token
828                assert name[-1] in '>"', token
829                system = name[0] == '<'
830                filename = name[1:-1]
831                return Include(token.start, token.end, filename, system)
832            if name.startswith('define'):
833                # Remove "define".
834                name = name[6:].strip()
835                assert name
836                value = ''
837                for i, c in enumerate(name):
838                    if c.isspace():
839                        value = name[i:].lstrip()
840                        name = name[:i]
841                        break
842                return Define(token.start, token.end, name, value)
843            if name.startswith('if') and name[2:3].isspace():
844                condition = name[3:].strip()
845                if condition.startswith('0') or condition.startswith('(0)'):
846                    self._SkipIf0Blocks()
847        return None
848
849    def _GetTokensUpTo(self, expected_token_type, expected_token):
850        return self._GetVarTokensUpTo(expected_token_type, expected_token)[0]
851
852    def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens):
853        last_token = self._GetNextToken()
854        tokens = []
855        while (last_token.token_type != expected_token_type or
856               last_token.name not in expected_tokens):
857            tokens.append(last_token)
858            last_token = self._GetNextToken()
859        return tokens, last_token
860
861    # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
862    def _IgnoreUpTo(self, token_type, token):
863        unused_tokens = self._GetTokensUpTo(token_type, token)
864
865    def _SkipIf0Blocks(self):
866        count = 1
867        while 1:
868            token = self._GetNextToken()
869            if token.token_type != tokenize.PREPROCESSOR:
870                continue
871
872            name = token.name[1:].lstrip()
873            if name.startswith('endif'):
874                count -= 1
875                if count == 0:
876                    break
877            elif name.startswith('if'):
878                count += 1
879
880    def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None):
881        if GetNextToken is None:
882            GetNextToken = self._GetNextToken
883        # Assumes the current token is open_paren and we will consume
884        # and return up to the close_paren.
885        count = 1
886        token = GetNextToken()
887        while 1:
888            if token.token_type == tokenize.SYNTAX:
889                if token.name == open_paren:
890                    count += 1
891                elif token.name == close_paren:
892                    count -= 1
893                    if count == 0:
894                        break
895            yield token
896            token = GetNextToken()
897        yield token
898
899    def _GetParameters(self):
900        return self._GetMatchingChar('(', ')')
901
902    def GetScope(self):
903        return self._GetMatchingChar('{', '}')
904
905    def _GetNextToken(self):
906        if self.token_queue:
907            return self.token_queue.pop()
908        return next(self.tokens)
909
910    def _AddBackToken(self, token):
911        if token.whence == tokenize.WHENCE_STREAM:
912            token.whence = tokenize.WHENCE_QUEUE
913            self.token_queue.insert(0, token)
914        else:
915            assert token.whence == tokenize.WHENCE_QUEUE, token
916            self.token_queue.append(token)
917
918    def _AddBackTokens(self, tokens):
919        if tokens:
920            if tokens[-1].whence == tokenize.WHENCE_STREAM:
921                for token in tokens:
922                    token.whence = tokenize.WHENCE_QUEUE
923                self.token_queue[:0] = reversed(tokens)
924            else:
925                assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens
926                self.token_queue.extend(reversed(tokens))
927
928    def GetName(self, seq=None):
929        """Returns ([tokens], next_token_info)."""
930        GetNextToken = self._GetNextToken
931        if seq is not None:
932            it = iter(seq)
933            GetNextToken = lambda: next(it)
934        next_token = GetNextToken()
935        tokens = []
936        last_token_was_name = False
937        while (next_token.token_type == tokenize.NAME or
938               (next_token.token_type == tokenize.SYNTAX and
939                next_token.name in ('::', '<'))):
940            # Two NAMEs in a row means the identifier should terminate.
941            # It's probably some sort of variable declaration.
942            if last_token_was_name and next_token.token_type == tokenize.NAME:
943                break
944            last_token_was_name = next_token.token_type == tokenize.NAME
945            tokens.append(next_token)
946            # Handle templated names.
947            if next_token.name == '<':
948                tokens.extend(self._GetMatchingChar('<', '>', GetNextToken))
949                last_token_was_name = True
950            next_token = GetNextToken()
951        return tokens, next_token
952
953    def GetMethod(self, modifiers, templated_types):
954        return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
955        assert len(return_type_and_name) >= 1
956        return self._GetMethod(return_type_and_name, modifiers, templated_types,
957                               False)
958
959    def _GetMethod(self, return_type_and_name, modifiers, templated_types,
960                   get_paren):
961        template_portion = None
962        if get_paren:
963            token = self._GetNextToken()
964            assert token.token_type == tokenize.SYNTAX, token
965            if token.name == '<':
966                # Handle templatized dtors.
967                template_portion = [token]
968                template_portion.extend(self._GetMatchingChar('<', '>'))
969                token = self._GetNextToken()
970            assert token.token_type == tokenize.SYNTAX, token
971            assert token.name == '(', token
972
973        name = return_type_and_name.pop()
974        # Handle templatized ctors.
975        if name.name == '>':
976            index = 1
977            while return_type_and_name[index].name != '<':
978                index += 1
979            template_portion = return_type_and_name[index:] + [name]
980            del return_type_and_name[index:]
981            name = return_type_and_name.pop()
982        elif name.name == ']':
983            rt = return_type_and_name
984            assert rt[-1].name == '[', return_type_and_name
985            assert rt[-2].name == 'operator', return_type_and_name
986            name_seq = return_type_and_name[-2:]
987            del return_type_and_name[-2:]
988            name = tokenize.Token(tokenize.NAME, 'operator[]',
989                                  name_seq[0].start, name.end)
990            # Get the open paren so _GetParameters() below works.
991            unused_open_paren = self._GetNextToken()
992
993        # TODO(nnorwitz): store template_portion.
994        return_type = return_type_and_name
995        indices = name
996        if return_type:
997            indices = return_type[0]
998
999        # Force ctor for templatized ctors.
1000        if name.name == self.in_class and not modifiers:
1001            modifiers |= FUNCTION_CTOR
1002        parameters = list(self._GetParameters())
1003        del parameters[-1]              # Remove trailing ')'.
1004
1005        # Handling operator() is especially weird.
1006        if name.name == 'operator' and not parameters:
1007            token = self._GetNextToken()
1008            assert token.name == '(', token
1009            parameters = list(self._GetParameters())
1010            del parameters[-1]          # Remove trailing ')'.
1011
1012        token = self._GetNextToken()
1013        while token.token_type == tokenize.NAME:
1014            modifier_token = token
1015            token = self._GetNextToken()
1016            if modifier_token.name == 'const':
1017                modifiers |= FUNCTION_CONST
1018            elif modifier_token.name == '__attribute__':
1019                # TODO(nnorwitz): handle more __attribute__ details.
1020                modifiers |= FUNCTION_ATTRIBUTE
1021                assert token.name == '(', token
1022                # Consume everything between the (parens).
1023                unused_tokens = list(self._GetMatchingChar('(', ')'))
1024                token = self._GetNextToken()
1025            elif modifier_token.name == 'throw':
1026                modifiers |= FUNCTION_THROW
1027                assert token.name == '(', token
1028                # Consume everything between the (parens).
1029                unused_tokens = list(self._GetMatchingChar('(', ')'))
1030                token = self._GetNextToken()
1031            elif modifier_token.name == 'override':
1032                modifiers |= FUNCTION_OVERRIDE
1033            elif modifier_token.name == modifier_token.name.upper():
1034                # HACK(nnorwitz):  assume that all upper-case names
1035                # are some macro we aren't expanding.
1036                modifiers |= FUNCTION_UNKNOWN_ANNOTATION
1037            else:
1038                self.HandleError('unexpected token', modifier_token)
1039
1040        assert token.token_type == tokenize.SYNTAX, token
1041        # Handle ctor initializers.
1042        if token.name == ':':
1043            # TODO(nnorwitz): anything else to handle for initializer list?
1044            while token.name != ';' and token.name != '{':
1045                token = self._GetNextToken()
1046
1047        # Handle pointer to functions that are really data but look
1048        # like method declarations.
1049        if token.name == '(':
1050            if parameters[0].name == '*':
1051                # name contains the return type.
1052                name = parameters.pop()
1053                # parameters contains the name of the data.
1054                modifiers = [p.name for p in parameters]
1055                # Already at the ( to open the parameter list.
1056                function_parameters = list(self._GetMatchingChar('(', ')'))
1057                del function_parameters[-1]  # Remove trailing ')'.
1058                # TODO(nnorwitz): store the function_parameters.
1059                token = self._GetNextToken()
1060                assert token.token_type == tokenize.SYNTAX, token
1061                assert token.name == ';', token
1062                return self._CreateVariable(indices, name.name, indices.name,
1063                                            modifiers, '', None)
1064            # At this point, we got something like:
1065            #  return_type (type::*name_)(params);
1066            # This is a data member called name_ that is a function pointer.
1067            # With this code: void (sq_type::*field_)(string&);
1068            # We get: name=void return_type=[] parameters=sq_type ... field_
1069            # TODO(nnorwitz): is return_type always empty?
1070            # TODO(nnorwitz): this isn't even close to being correct.
1071            # Just put in something so we don't crash and can move on.
1072            real_name = parameters[-1]
1073            modifiers = [p.name for p in self._GetParameters()]
1074            del modifiers[-1]           # Remove trailing ')'.
1075            return self._CreateVariable(indices, real_name.name, indices.name,
1076                                        modifiers, '', None)
1077
1078        if token.name == '{':
1079            body = list(self.GetScope())
1080            del body[-1]                # Remove trailing '}'.
1081        else:
1082            body = None
1083            if token.name == '=':
1084                token = self._GetNextToken()
1085
1086                if token.name == 'default' or token.name == 'delete':
1087                    # Ignore explicitly defaulted and deleted special members
1088                    # in C++11.
1089                    token = self._GetNextToken()
1090                else:
1091                    # Handle pure-virtual declarations.
1092                    assert token.token_type == tokenize.CONSTANT, token
1093                    assert token.name == '0', token
1094                    modifiers |= FUNCTION_PURE_VIRTUAL
1095                    token = self._GetNextToken()
1096
1097            if token.name == '[':
1098                # TODO(nnorwitz): store tokens and improve parsing.
1099                # template <typename T, size_t N> char (&ASH(T (&seq)[N]))[N];
1100                tokens = list(self._GetMatchingChar('[', ']'))
1101                token = self._GetNextToken()
1102
1103            assert token.name == ';', (token, return_type_and_name, parameters)
1104
1105        # Looks like we got a method, not a function.
1106        if len(return_type) > 2 and return_type[-1].name == '::':
1107            return_type, in_class = \
1108                         self._GetReturnTypeAndClassName(return_type)
1109            return Method(indices.start, indices.end, name.name, in_class,
1110                          return_type, parameters, modifiers, templated_types,
1111                          body, self.namespace_stack)
1112        return Function(indices.start, indices.end, name.name, return_type,
1113                        parameters, modifiers, templated_types, body,
1114                        self.namespace_stack)
1115
1116    def _GetReturnTypeAndClassName(self, token_seq):
1117        # Splitting the return type from the class name in a method
1118        # can be tricky.  For example, Return::Type::Is::Hard::To::Find().
1119        # Where is the return type and where is the class name?
1120        # The heuristic used is to pull the last name as the class name.
1121        # This includes all the templated type info.
1122        # TODO(nnorwitz): if there is only One name like in the
1123        # example above, punt and assume the last bit is the class name.
1124
1125        # Ignore a :: prefix, if exists so we can find the first real name.
1126        i = 0
1127        if token_seq[0].name == '::':
1128            i = 1
1129        # Ignore a :: suffix, if exists.
1130        end = len(token_seq) - 1
1131        if token_seq[end-1].name == '::':
1132            end -= 1
1133
1134        # Make a copy of the sequence so we can append a sentinel
1135        # value. This is required for GetName will has to have some
1136        # terminating condition beyond the last name.
1137        seq_copy = token_seq[i:end]
1138        seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0))
1139        names = []
1140        while i < end:
1141            # Iterate through the sequence parsing out each name.
1142            new_name, next = self.GetName(seq_copy[i:])
1143            assert new_name, 'Got empty new_name, next=%s' % next
1144            # We got a pointer or ref.  Add it to the name.
1145            if next and next.token_type == tokenize.SYNTAX:
1146                new_name.append(next)
1147            names.append(new_name)
1148            i += len(new_name)
1149
1150        # Now that we have the names, it's time to undo what we did.
1151
1152        # Remove the sentinel value.
1153        names[-1].pop()
1154        # Flatten the token sequence for the return type.
1155        return_type = [e for seq in names[:-1] for e in seq]
1156        # The class name is the last name.
1157        class_name = names[-1]
1158        return return_type, class_name
1159
1160    def handle_bool(self):
1161        pass
1162
1163    def handle_char(self):
1164        pass
1165
1166    def handle_int(self):
1167        pass
1168
1169    def handle_long(self):
1170        pass
1171
1172    def handle_short(self):
1173        pass
1174
1175    def handle_double(self):
1176        pass
1177
1178    def handle_float(self):
1179        pass
1180
1181    def handle_void(self):
1182        pass
1183
1184    def handle_wchar_t(self):
1185        pass
1186
1187    def handle_unsigned(self):
1188        pass
1189
1190    def handle_signed(self):
1191        pass
1192
1193    def _GetNestedType(self, ctor):
1194        name = None
1195        name_tokens, token = self.GetName()
1196        if name_tokens:
1197            name = ''.join([t.name for t in name_tokens])
1198
1199        # Handle forward declarations.
1200        if token.token_type == tokenize.SYNTAX and token.name == ';':
1201            return ctor(token.start, token.end, name, None,
1202                        self.namespace_stack)
1203
1204        if token.token_type == tokenize.NAME and self._handling_typedef:
1205            self._AddBackToken(token)
1206            return ctor(token.start, token.end, name, None,
1207                        self.namespace_stack)
1208
1209        # Must be the type declaration.
1210        fields = list(self._GetMatchingChar('{', '}'))
1211        del fields[-1]                  # Remove trailing '}'.
1212        if token.token_type == tokenize.SYNTAX and token.name == '{':
1213            next = self._GetNextToken()
1214            new_type = ctor(token.start, token.end, name, fields,
1215                            self.namespace_stack)
1216            # A name means this is an anonymous type and the name
1217            # is the variable declaration.
1218            if next.token_type != tokenize.NAME:
1219                return new_type
1220            name = new_type
1221            token = next
1222
1223        # Must be variable declaration using the type prefixed with keyword.
1224        assert token.token_type == tokenize.NAME, token
1225        return self._CreateVariable(token, token.name, name, [], '', None)
1226
1227    def handle_struct(self):
1228        # Special case the handling typedef/aliasing of structs here.
1229        # It would be a pain to handle in the class code.
1230        name_tokens, var_token = self.GetName()
1231        if name_tokens:
1232            next_token = self._GetNextToken()
1233            is_syntax = (var_token.token_type == tokenize.SYNTAX and
1234                         var_token.name[0] in '*&')
1235            is_variable = (var_token.token_type == tokenize.NAME and
1236                           next_token.name == ';')
1237            variable = var_token
1238            if is_syntax and not is_variable:
1239                variable = next_token
1240                temp = self._GetNextToken()
1241                if temp.token_type == tokenize.SYNTAX and temp.name == '(':
1242                    # Handle methods declared to return a struct.
1243                    t0 = name_tokens[0]
1244                    struct = tokenize.Token(tokenize.NAME, 'struct',
1245                                            t0.start-7, t0.start-2)
1246                    type_and_name = [struct]
1247                    type_and_name.extend(name_tokens)
1248                    type_and_name.extend((var_token, next_token))
1249                    return self._GetMethod(type_and_name, 0, None, False)
1250                assert temp.name == ';', (temp, name_tokens, var_token)
1251            if is_syntax or (is_variable and not self._handling_typedef):
1252                modifiers = ['struct']
1253                type_name = ''.join([t.name for t in name_tokens])
1254                position = name_tokens[0]
1255                return self._CreateVariable(position, variable.name, type_name,
1256                                            modifiers, var_token.name, None)
1257            name_tokens.extend((var_token, next_token))
1258            self._AddBackTokens(name_tokens)
1259        else:
1260            self._AddBackToken(var_token)
1261        return self._GetClass(Struct, VISIBILITY_PUBLIC, None)
1262
1263    def handle_union(self):
1264        return self._GetNestedType(Union)
1265
1266    def handle_enum(self):
1267        return self._GetNestedType(Enum)
1268
1269    def handle_auto(self):
1270        # TODO(nnorwitz): warn about using auto?  Probably not since it
1271        # will be reclaimed and useful for C++0x.
1272        pass
1273
1274    def handle_register(self):
1275        pass
1276
1277    def handle_const(self):
1278        pass
1279
1280    def handle_inline(self):
1281        pass
1282
1283    def handle_extern(self):
1284        pass
1285
1286    def handle_static(self):
1287        pass
1288
1289    def handle_virtual(self):
1290        # What follows must be a method.
1291        token = token2 = self._GetNextToken()
1292        if token.name == 'inline':
1293            # HACK(nnorwitz): handle inline dtors by ignoring 'inline'.
1294            token2 = self._GetNextToken()
1295        if token2.token_type == tokenize.SYNTAX and token2.name == '~':
1296            return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
1297        assert token.token_type == tokenize.NAME or token.name == '::', token
1298        return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')  # )
1299        return_type_and_name.insert(0, token)
1300        if token2 is not token:
1301            return_type_and_name.insert(1, token2)
1302        return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL,
1303                               None, False)
1304
1305    def handle_volatile(self):
1306        pass
1307
1308    def handle_mutable(self):
1309        pass
1310
1311    def handle_public(self):
1312        assert self.in_class
1313        self.visibility = VISIBILITY_PUBLIC
1314
1315    def handle_protected(self):
1316        assert self.in_class
1317        self.visibility = VISIBILITY_PROTECTED
1318
1319    def handle_private(self):
1320        assert self.in_class
1321        self.visibility = VISIBILITY_PRIVATE
1322
1323    def handle_friend(self):
1324        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
1325        assert tokens
1326        t0 = tokens[0]
1327        return Friend(t0.start, t0.end, tokens, self.namespace_stack)
1328
1329    def handle_static_cast(self):
1330        pass
1331
1332    def handle_const_cast(self):
1333        pass
1334
1335    def handle_dynamic_cast(self):
1336        pass
1337
1338    def handle_reinterpret_cast(self):
1339        pass
1340
1341    def handle_new(self):
1342        pass
1343
1344    def handle_delete(self):
1345        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
1346        assert tokens
1347        return Delete(tokens[0].start, tokens[0].end, tokens)
1348
1349    def handle_typedef(self):
1350        token = self._GetNextToken()
1351        if (token.token_type == tokenize.NAME and
1352            keywords.IsKeyword(token.name)):
1353            # Token must be struct/enum/union/class.
1354            method = getattr(self, 'handle_' + token.name)
1355            self._handling_typedef = True
1356            tokens = [method()]
1357            self._handling_typedef = False
1358        else:
1359            tokens = [token]
1360
1361        # Get the remainder of the typedef up to the semi-colon.
1362        tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';'))
1363
1364        # TODO(nnorwitz): clean all this up.
1365        assert tokens
1366        name = tokens.pop()
1367        indices = name
1368        if tokens:
1369            indices = tokens[0]
1370        if not indices:
1371            indices = token
1372        if name.name == ')':
1373            # HACK(nnorwitz): Handle pointers to functions "properly".
1374            if (len(tokens) >= 4 and
1375                tokens[1].name == '(' and tokens[2].name == '*'):
1376                tokens.append(name)
1377                name = tokens[3]
1378        elif name.name == ']':
1379            # HACK(nnorwitz): Handle arrays properly.
1380            if len(tokens) >= 2:
1381                tokens.append(name)
1382                name = tokens[1]
1383        new_type = tokens
1384        if tokens and isinstance(tokens[0], tokenize.Token):
1385            new_type = self.converter.ToType(tokens)[0]
1386        return Typedef(indices.start, indices.end, name.name,
1387                       new_type, self.namespace_stack)
1388
1389    def handle_typeid(self):
1390        pass  # Not needed yet.
1391
1392    def handle_typename(self):
1393        pass  # Not needed yet.
1394
1395    def _GetTemplatedTypes(self):
1396        result = {}
1397        tokens = list(self._GetMatchingChar('<', '>'))
1398        len_tokens = len(tokens) - 1    # Ignore trailing '>'.
1399        i = 0
1400        while i < len_tokens:
1401            key = tokens[i].name
1402            i += 1
1403            if keywords.IsKeyword(key) or key == ',':
1404                continue
1405            type_name = default = None
1406            if i < len_tokens:
1407                i += 1
1408                if tokens[i-1].name == '=':
1409                    assert i < len_tokens, '%s %s' % (i, tokens)
1410                    default, unused_next_token = self.GetName(tokens[i:])
1411                    i += len(default)
1412                else:
1413                    if tokens[i-1].name != ',':
1414                        # We got something like: Type variable.
1415                        # Re-adjust the key (variable) and type_name (Type).
1416                        key = tokens[i-1].name
1417                        type_name = tokens[i-2]
1418
1419            result[key] = (type_name, default)
1420        return result
1421
1422    def handle_template(self):
1423        token = self._GetNextToken()
1424        assert token.token_type == tokenize.SYNTAX, token
1425        assert token.name == '<', token
1426        templated_types = self._GetTemplatedTypes()
1427        # TODO(nnorwitz): for now, just ignore the template params.
1428        token = self._GetNextToken()
1429        if token.token_type == tokenize.NAME:
1430            if token.name == 'class':
1431                return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types)
1432            elif token.name == 'struct':
1433                return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types)
1434            elif token.name == 'friend':
1435                return self.handle_friend()
1436        self._AddBackToken(token)
1437        tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';')
1438        tokens.append(last)
1439        self._AddBackTokens(tokens)
1440        if last.name == '(':
1441            return self.GetMethod(FUNCTION_NONE, templated_types)
1442        # Must be a variable definition.
1443        return None
1444
1445    def handle_true(self):
1446        pass  # Nothing to do.
1447
1448    def handle_false(self):
1449        pass  # Nothing to do.
1450
1451    def handle_asm(self):
1452        pass  # Not needed yet.
1453
1454    def handle_class(self):
1455        return self._GetClass(Class, VISIBILITY_PRIVATE, None)
1456
1457    def _GetBases(self):
1458        # Get base classes.
1459        bases = []
1460        while 1:
1461            token = self._GetNextToken()
1462            assert token.token_type == tokenize.NAME, token
1463            # TODO(nnorwitz): store kind of inheritance...maybe.
1464            if token.name not in ('public', 'protected', 'private'):
1465                # If inheritance type is not specified, it is private.
1466                # Just put the token back so we can form a name.
1467                # TODO(nnorwitz): it would be good to warn about this.
1468                self._AddBackToken(token)
1469            else:
1470                # Check for virtual inheritance.
1471                token = self._GetNextToken()
1472                if token.name != 'virtual':
1473                    self._AddBackToken(token)
1474                else:
1475                    # TODO(nnorwitz): store that we got virtual for this base.
1476                    pass
1477            base, next_token = self.GetName()
1478            bases_ast = self.converter.ToType(base)
1479            assert len(bases_ast) == 1, bases_ast
1480            bases.append(bases_ast[0])
1481            assert next_token.token_type == tokenize.SYNTAX, next_token
1482            if next_token.name == '{':
1483                token = next_token
1484                break
1485            # Support multiple inheritance.
1486            assert next_token.name == ',', next_token
1487        return bases, token
1488
1489    def _GetClass(self, class_type, visibility, templated_types):
1490        class_name = None
1491        class_token = self._GetNextToken()
1492        if class_token.token_type != tokenize.NAME:
1493            assert class_token.token_type == tokenize.SYNTAX, class_token
1494            token = class_token
1495        else:
1496            # Skip any macro (e.g. storage class specifiers) after the
1497            # 'class' keyword.
1498            next_token = self._GetNextToken()
1499            if next_token.token_type == tokenize.NAME:
1500                self._AddBackToken(next_token)
1501            else:
1502                self._AddBackTokens([class_token, next_token])
1503            name_tokens, token = self.GetName()
1504            class_name = ''.join([t.name for t in name_tokens])
1505        bases = None
1506        if token.token_type == tokenize.SYNTAX:
1507            if token.name == ';':
1508                # Forward declaration.
1509                return class_type(class_token.start, class_token.end,
1510                                  class_name, None, templated_types, None,
1511                                  self.namespace_stack)
1512            if token.name in '*&':
1513                # Inline forward declaration.  Could be method or data.
1514                name_token = self._GetNextToken()
1515                next_token = self._GetNextToken()
1516                if next_token.name == ';':
1517                    # Handle data
1518                    modifiers = ['class']
1519                    return self._CreateVariable(class_token, name_token.name,
1520                                                class_name,
1521                                                modifiers, token.name, None)
1522                else:
1523                    # Assume this is a method.
1524                    tokens = (class_token, token, name_token, next_token)
1525                    self._AddBackTokens(tokens)
1526                    return self.GetMethod(FUNCTION_NONE, None)
1527            if token.name == ':':
1528                bases, token = self._GetBases()
1529
1530        body = None
1531        if token.token_type == tokenize.SYNTAX and token.name == '{':
1532            assert token.token_type == tokenize.SYNTAX, token
1533            assert token.name == '{', token
1534
1535            ast = AstBuilder(self.GetScope(), self.filename, class_name,
1536                             visibility, self.namespace_stack)
1537            body = list(ast.Generate())
1538
1539            if not self._handling_typedef:
1540                token = self._GetNextToken()
1541                if token.token_type != tokenize.NAME:
1542                    assert token.token_type == tokenize.SYNTAX, token
1543                    assert token.name == ';', token
1544                else:
1545                    new_class = class_type(class_token.start, class_token.end,
1546                                           class_name, bases, None,
1547                                           body, self.namespace_stack)
1548
1549                    modifiers = []
1550                    return self._CreateVariable(class_token,
1551                                                token.name, new_class,
1552                                                modifiers, token.name, None)
1553        else:
1554            if not self._handling_typedef:
1555                self.HandleError('non-typedef token', token)
1556            self._AddBackToken(token)
1557
1558        return class_type(class_token.start, class_token.end, class_name,
1559                          bases, templated_types, body, self.namespace_stack)
1560
1561    def handle_namespace(self):
1562        token = self._GetNextToken()
1563        # Support anonymous namespaces.
1564        name = None
1565        if token.token_type == tokenize.NAME:
1566            name = token.name
1567            token = self._GetNextToken()
1568        self.namespace_stack.append(name)
1569        assert token.token_type == tokenize.SYNTAX, token
1570        # Create an internal token that denotes when the namespace is complete.
1571        internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP,
1572                                        None, None)
1573        internal_token.whence = token.whence
1574        if token.name == '=':
1575            # TODO(nnorwitz): handle aliasing namespaces.
1576            name, next_token = self.GetName()
1577            assert next_token.name == ';', next_token
1578            self._AddBackToken(internal_token)
1579        else:
1580            assert token.name == '{', token
1581            tokens = list(self.GetScope())
1582            # Replace the trailing } with the internal namespace pop token.
1583            tokens[-1] = internal_token
1584            # Handle namespace with nothing in it.
1585            self._AddBackTokens(tokens)
1586        return None
1587
1588    def handle_using(self):
1589        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
1590        assert tokens
1591        return Using(tokens[0].start, tokens[0].end, tokens)
1592
1593    def handle_explicit(self):
1594        assert self.in_class
1595        # Nothing much to do.
1596        # TODO(nnorwitz): maybe verify the method name == class name.
1597        # This must be a ctor.
1598        return self.GetMethod(FUNCTION_CTOR, None)
1599
1600    def handle_this(self):
1601        pass  # Nothing to do.
1602
1603    def handle_operator(self):
1604        # Pull off the next token(s?) and make that part of the method name.
1605        pass
1606
1607    def handle_sizeof(self):
1608        pass
1609
1610    def handle_case(self):
1611        pass
1612
1613    def handle_switch(self):
1614        pass
1615
1616    def handle_default(self):
1617        token = self._GetNextToken()
1618        assert token.token_type == tokenize.SYNTAX
1619        assert token.name == ':'
1620
1621    def handle_if(self):
1622        pass
1623
1624    def handle_else(self):
1625        pass
1626
1627    def handle_return(self):
1628        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
1629        if not tokens:
1630            return Return(self.current_token.start, self.current_token.end, None)
1631        return Return(tokens[0].start, tokens[0].end, tokens)
1632
1633    def handle_goto(self):
1634        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
1635        assert len(tokens) == 1, str(tokens)
1636        return Goto(tokens[0].start, tokens[0].end, tokens[0].name)
1637
1638    def handle_try(self):
1639        pass  # Not needed yet.
1640
1641    def handle_catch(self):
1642        pass  # Not needed yet.
1643
1644    def handle_throw(self):
1645        pass  # Not needed yet.
1646
1647    def handle_while(self):
1648        pass
1649
1650    def handle_do(self):
1651        pass
1652
1653    def handle_for(self):
1654        pass
1655
1656    def handle_break(self):
1657        self._IgnoreUpTo(tokenize.SYNTAX, ';')
1658
1659    def handle_continue(self):
1660        self._IgnoreUpTo(tokenize.SYNTAX, ';')
1661
1662
1663def BuilderFromSource(source, filename):
1664    """Utility method that returns an AstBuilder from source code.
1665
1666    Args:
1667      source: 'C++ source code'
1668      filename: 'file1'
1669
1670    Returns:
1671      AstBuilder
1672    """
1673    return AstBuilder(tokenize.GetTokens(source), filename)
1674
1675
1676def PrintIndentifiers(filename, should_print):
1677    """Prints all identifiers for a C++ source file.
1678
1679    Args:
1680      filename: 'file1'
1681      should_print: predicate with signature: bool Function(token)
1682    """
1683    source = utils.ReadFile(filename, False)
1684    if source is None:
1685        sys.stderr.write('Unable to find: %s\n' % filename)
1686        return
1687
1688    #print('Processing %s' % actual_filename)
1689    builder = BuilderFromSource(source, filename)
1690    try:
1691        for node in builder.Generate():
1692            if should_print(node):
1693                print(node.name)
1694    except KeyboardInterrupt:
1695        return
1696    except:
1697        pass
1698
1699
1700def PrintAllIndentifiers(filenames, should_print):
1701    """Prints all identifiers for each C++ source file in filenames.
1702
1703    Args:
1704      filenames: ['file1', 'file2', ...]
1705      should_print: predicate with signature: bool Function(token)
1706    """
1707    for path in filenames:
1708        PrintIndentifiers(path, should_print)
1709
1710
1711def main(argv):
1712    for filename in argv[1:]:
1713        source = utils.ReadFile(filename)
1714        if source is None:
1715            continue
1716
1717        print('Processing %s' % filename)
1718        builder = BuilderFromSource(source, filename)
1719        try:
1720            entire_ast = filter(None, builder.Generate())
1721        except KeyboardInterrupt:
1722            return
1723        except:
1724            # Already printed a warning, print the traceback and continue.
1725            traceback.print_exc()
1726        else:
1727            if utils.DEBUG:
1728                for ast in entire_ast:
1729                    print(ast)
1730
1731
1732if __name__ == '__main__':
1733    main(sys.argv)
trunk/3rdparty/googletest/googlemock/scripts/generator/cpp/gmock_class.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008 Google Inc.  All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Generate Google Mock classes from base classes.
18
19This program will read in a C++ source file and output the Google Mock
20classes for the specified classes.  If no class is specified, all
21classes in the source file are emitted.
22
23Usage:
24  gmock_class.py header-file.h [ClassName]...
25
26Output is sent to stdout.
27"""
28
29__author__ = 'nnorwitz@google.com (Neal Norwitz)'
30
31
32import os
33import re
34import sys
35
36from cpp import ast
37from cpp import utils
38
39# Preserve compatibility with Python 2.3.
40try:
41  _dummy = set
42except NameError:
43  import sets
44  set = sets.Set
45
46_VERSION = (1, 0, 1)  # The version of this script.
47# How many spaces to indent.  Can set me with the INDENT environment variable.
48_INDENT = 2
49
50
51def _GenerateMethods(output_lines, source, class_node):
52  function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL |
53                   ast.FUNCTION_OVERRIDE)
54  ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
55  indent = ' ' * _INDENT
56
57  for node in class_node.body:
58    # We only care about virtual functions.
59    if (isinstance(node, ast.Function) and
60        node.modifiers & function_type and
61        not node.modifiers & ctor_or_dtor):
62      # Pick out all the elements we need from the original function.
63      const = ''
64      if node.modifiers & ast.FUNCTION_CONST:
65        const = 'CONST_'
66      return_type = 'void'
67      if node.return_type:
68        # Add modifiers like 'const'.
69        modifiers = ''
70        if node.return_type.modifiers:
71          modifiers = ' '.join(node.return_type.modifiers) + ' '
72        return_type = modifiers + node.return_type.name
73        template_args = [arg.name for arg in node.return_type.templated_types]
74        if template_args:
75          return_type += '<' + ', '.join(template_args) + '>'
76          if len(template_args) > 1:
77            for line in [
78                '// The following line won\'t really compile, as the return',
79                '// type has multiple template arguments.  To fix it, use a',
80                '// typedef for the return type.']:
81              output_lines.append(indent + line)
82        if node.return_type.pointer:
83          return_type += '*'
84        if node.return_type.reference:
85          return_type += '&'
86        num_parameters = len(node.parameters)
87        if len(node.parameters) == 1:
88          first_param = node.parameters[0]
89          if source[first_param.start:first_param.end].strip() == 'void':
90            # We must treat T(void) as a function with no parameters.
91            num_parameters = 0
92      tmpl = ''
93      if class_node.templated_types:
94        tmpl = '_T'
95      mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
96
97      args = ''
98      if node.parameters:
99        # Due to the parser limitations, it is impossible to keep comments
100        # while stripping the default parameters.  When defaults are
101        # present, we choose to strip them and comments (and produce
102        # compilable code).
103        # TODO(nnorwitz@google.com): Investigate whether it is possible to
104        # preserve parameter name when reconstructing parameter text from
105        # the AST.
106        if len([param for param in node.parameters if param.default]) > 0:
107          args = ', '.join(param.type.name for param in node.parameters)
108        else:
109          # Get the full text of the parameters from the start
110          # of the first parameter to the end of the last parameter.
111          start = node.parameters[0].start
112          end = node.parameters[-1].end
113          # Remove // comments.
114          args_strings = re.sub(r'//.*', '', source[start:end])
115          # Condense multiple spaces and eliminate newlines putting the
116          # parameters together on a single line.  Ensure there is a
117          # space in an argument which is split by a newline without
118          # intervening whitespace, e.g.: int\nBar
119          args = re.sub('  +', ' ', args_strings.replace('\n', ' '))
120
121      # Create the mock method definition.
122      output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
123                           '%s%s(%s));' % (indent*3, return_type, args)])
124
125
126def _GenerateMocks(filename, source, ast_list, desired_class_names):
127  processed_class_names = set()
128  lines = []
129  for node in ast_list:
130    if (isinstance(node, ast.Class) and node.body and
131        # desired_class_names being None means that all classes are selected.
132        (not desired_class_names or node.name in desired_class_names)):
133      class_name = node.name
134      parent_name = class_name
135      processed_class_names.add(class_name)
136      class_node = node
137      # Add namespace before the class.
138      if class_node.namespace:
139        lines.extend(['namespace %s {' % n for n in class_node.namespace])  # }
140        lines.append('')
141
142      # Add template args for templated classes.
143      if class_node.templated_types:
144        # TODO(paulchang): The AST doesn't preserve template argument order,
145        # so we have to make up names here.
146        # TODO(paulchang): Handle non-type template arguments (e.g.
147        # template<typename T, int N>).
148        template_arg_count = len(class_node.templated_types.keys())
149        template_args = ['T%d' % n for n in range(template_arg_count)]
150        template_decls = ['typename ' + arg for arg in template_args]
151        lines.append('template <' + ', '.join(template_decls) + '>')
152        parent_name += '<' + ', '.join(template_args) + '>'
153
154      # Add the class prolog.
155      lines.append('class Mock%s : public %s {'  # }
156                   % (class_name, parent_name))
157      lines.append('%spublic:' % (' ' * (_INDENT // 2)))
158
159      # Add all the methods.
160      _GenerateMethods(lines, source, class_node)
161
162      # Close the class.
163      if lines:
164        # If there are no virtual methods, no need for a public label.
165        if len(lines) == 2:
166          del lines[-1]
167
168        # Only close the class if there really is a class.
169        lines.append('};')
170        lines.append('')  # Add an extra newline.
171
172      # Close the namespace.
173      if class_node.namespace:
174        for i in range(len(class_node.namespace)-1, -1, -1):
175          lines.append('}  // namespace %s' % class_node.namespace[i])
176        lines.append('')  # Add an extra newline.
177
178  if desired_class_names:
179    missing_class_name_list = list(desired_class_names - processed_class_names)
180    if missing_class_name_list:
181      missing_class_name_list.sort()
182      sys.stderr.write('Class(es) not found in %s: %s\n' %
183                       (filename, ', '.join(missing_class_name_list)))
184  elif not processed_class_names:
185    sys.stderr.write('No class found in %s\n' % filename)
186
187  return lines
188
189
190def main(argv=sys.argv):
191  if len(argv) < 2:
192    sys.stderr.write('Google Mock Class Generator v%s\n\n' %
193                     '.'.join(map(str, _VERSION)))
194    sys.stderr.write(__doc__)
195    return 1
196
197  global _INDENT
198  try:
199    _INDENT = int(os.environ['INDENT'])
200  except KeyError:
201    pass
202  except:
203    sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
204
205  filename = argv[1]
206  desired_class_names = None  # None means all classes in the source file.
207  if len(argv) >= 3:
208    desired_class_names = set(argv[2:])
209  source = utils.ReadFile(filename)
210  if source is None:
211    return 1
212
213  builder = ast.BuilderFromSource(source, filename)
214  try:
215    entire_ast = filter(None, builder.Generate())
216  except KeyboardInterrupt:
217    return
218  except:
219    # An error message was already printed since we couldn't parse.
220    sys.exit(1)
221  else:
222    lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
223    sys.stdout.write('\n'.join(lines))
224
225
226if __name__ == '__main__':
227  main(sys.argv)
trunk/3rdparty/googletest/googlemock/scripts/generator/cpp/gmock_class_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009 Neal Norwitz All Rights Reserved.
4# Portions Copyright 2009 Google Inc. All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Tests for gmock.scripts.generator.cpp.gmock_class."""
19
20__author__ = 'nnorwitz@google.com (Neal Norwitz)'
21
22
23import os
24import sys
25import unittest
26
27# Allow the cpp imports below to work when run as a standalone script.
28sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
29
30from cpp import ast
31from cpp import gmock_class
32
33
34class TestCase(unittest.TestCase):
35  """Helper class that adds assert methods."""
36
37  def StripLeadingWhitespace(self, lines):
38    """Strip leading whitespace in each line in 'lines'."""
39    return '\n'.join([s.lstrip() for s in lines.split('\n')])
40
41  def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
42    """Specialized assert that ignores the indent level."""
43    self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
44
45
46class GenerateMethodsTest(TestCase):
47
48  def GenerateMethodSource(self, cpp_source):
49    """Convert C++ source to Google Mock output source lines."""
50    method_source_lines = []
51    # <test> is a pseudo-filename, it is not read or written.
52    builder = ast.BuilderFromSource(cpp_source, '<test>')
53    ast_list = list(builder.Generate())
54    gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
55    return '\n'.join(method_source_lines)
56
57  def testSimpleMethod(self):
58    source = """
59class Foo {
60 public:
61  virtual int Bar();
62};
63"""
64    self.assertEqualIgnoreLeadingWhitespace(
65        'MOCK_METHOD0(Bar,\nint());',
66        self.GenerateMethodSource(source))
67
68  def testSimpleConstructorsAndDestructor(self):
69    source = """
70class Foo {
71 public:
72  Foo();
73  Foo(int x);
74  Foo(const Foo& f);
75  Foo(Foo&& f);
76  ~Foo();
77  virtual int Bar() = 0;
78};
79"""
80    # The constructors and destructor should be ignored.
81    self.assertEqualIgnoreLeadingWhitespace(
82        'MOCK_METHOD0(Bar,\nint());',
83        self.GenerateMethodSource(source))
84
85  def testVirtualDestructor(self):
86    source = """
87class Foo {
88 public:
89  virtual ~Foo();
90  virtual int Bar() = 0;
91};
92"""
93    # The destructor should be ignored.
94    self.assertEqualIgnoreLeadingWhitespace(
95        'MOCK_METHOD0(Bar,\nint());',
96        self.GenerateMethodSource(source))
97
98  def testExplicitlyDefaultedConstructorsAndDestructor(self):
99    source = """
100class Foo {
101 public:
102  Foo() = default;
103  Foo(const Foo& f) = default;
104  Foo(Foo&& f) = default;
105  ~Foo() = default;
106  virtual int Bar() = 0;
107};
108"""
109    # The constructors and destructor should be ignored.
110    self.assertEqualIgnoreLeadingWhitespace(
111        'MOCK_METHOD0(Bar,\nint());',
112        self.GenerateMethodSource(source))
113
114  def testExplicitlyDeletedConstructorsAndDestructor(self):
115    source = """
116class Foo {
117 public:
118  Foo() = delete;
119  Foo(const Foo& f) = delete;
120  Foo(Foo&& f) = delete;
121  ~Foo() = delete;
122  virtual int Bar() = 0;
123};
124"""
125    # The constructors and destructor should be ignored.
126    self.assertEqualIgnoreLeadingWhitespace(
127        'MOCK_METHOD0(Bar,\nint());',
128        self.GenerateMethodSource(source))
129
130  def testSimpleOverrideMethod(self):
131    source = """
132class Foo {
133 public:
134  int Bar() override;
135};
136"""
137    self.assertEqualIgnoreLeadingWhitespace(
138        'MOCK_METHOD0(Bar,\nint());',
139        self.GenerateMethodSource(source))
140
141  def testSimpleConstMethod(self):
142    source = """
143class Foo {
144 public:
145  virtual void Bar(bool flag) const;
146};
147"""
148    self.assertEqualIgnoreLeadingWhitespace(
149        'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));',
150        self.GenerateMethodSource(source))
151
152  def testExplicitVoid(self):
153    source = """
154class Foo {
155 public:
156  virtual int Bar(void);
157};
158"""
159    self.assertEqualIgnoreLeadingWhitespace(
160        'MOCK_METHOD0(Bar,\nint(void));',
161        self.GenerateMethodSource(source))
162
163  def testStrangeNewlineInParameter(self):
164    source = """
165class Foo {
166 public:
167  virtual void Bar(int
168a) = 0;
169};
170"""
171    self.assertEqualIgnoreLeadingWhitespace(
172        'MOCK_METHOD1(Bar,\nvoid(int a));',
173        self.GenerateMethodSource(source))
174
175  def testDefaultParameters(self):
176    source = """
177class Foo {
178 public:
179  virtual void Bar(int a, char c = 'x') = 0;
180};
181"""
182    self.assertEqualIgnoreLeadingWhitespace(
183        'MOCK_METHOD2(Bar,\nvoid(int, char));',
184        self.GenerateMethodSource(source))
185
186  def testMultipleDefaultParameters(self):
187    source = """
188class Foo {
189 public:
190  virtual void Bar(int a = 42, char c = 'x') = 0;
191};
192"""
193    self.assertEqualIgnoreLeadingWhitespace(
194        'MOCK_METHOD2(Bar,\nvoid(int, char));',
195        self.GenerateMethodSource(source))
196
197  def testRemovesCommentsWhenDefaultsArePresent(self):
198    source = """
199class Foo {
200 public:
201  virtual void Bar(int a = 42 /* a comment */,
202                   char /* other comment */ c= 'x') = 0;
203};
204"""
205    self.assertEqualIgnoreLeadingWhitespace(
206        'MOCK_METHOD2(Bar,\nvoid(int, char));',
207        self.GenerateMethodSource(source))
208
209  def testDoubleSlashCommentsInParameterListAreRemoved(self):
210    source = """
211class Foo {
212 public:
213  virtual void Bar(int a,  // inline comments should be elided.
214                   int b   // inline comments should be elided.
215                   ) const = 0;
216};
217"""
218    self.assertEqualIgnoreLeadingWhitespace(
219        'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));',
220        self.GenerateMethodSource(source))
221
222  def testCStyleCommentsInParameterListAreNotRemoved(self):
223    # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
224    # comments.  Also note that C style comments after the last parameter
225    # are still elided.
226    source = """
227class Foo {
228 public:
229  virtual const string& Bar(int /* keeper */, int b);
230};
231"""
232    self.assertEqualIgnoreLeadingWhitespace(
233        'MOCK_METHOD2(Bar,\nconst string&(int /* keeper */, int b));',
234        self.GenerateMethodSource(source))
235
236  def testArgsOfTemplateTypes(self):
237    source = """
238class Foo {
239 public:
240  virtual int Bar(const vector<int>& v, map<int, string>* output);
241};"""
242    self.assertEqualIgnoreLeadingWhitespace(
243        'MOCK_METHOD2(Bar,\n'
244        'int(const vector<int>& v, map<int, string>* output));',
245        self.GenerateMethodSource(source))
246
247  def testReturnTypeWithOneTemplateArg(self):
248    source = """
249class Foo {
250 public:
251  virtual vector<int>* Bar(int n);
252};"""
253    self.assertEqualIgnoreLeadingWhitespace(
254        'MOCK_METHOD1(Bar,\nvector<int>*(int n));',
255        self.GenerateMethodSource(source))
256
257  def testReturnTypeWithManyTemplateArgs(self):
258    source = """
259class Foo {
260 public:
261  virtual map<int, string> Bar();
262};"""
263    # Comparing the comment text is brittle - we'll think of something
264    # better in case this gets annoying, but for now let's keep it simple.
265    self.assertEqualIgnoreLeadingWhitespace(
266        '// The following line won\'t really compile, as the return\n'
267        '// type has multiple template arguments.  To fix it, use a\n'
268        '// typedef for the return type.\n'
269        'MOCK_METHOD0(Bar,\nmap<int, string>());',
270        self.GenerateMethodSource(source))
271
272  def testSimpleMethodInTemplatedClass(self):
273    source = """
274template<class T>
275class Foo {
276 public:
277  virtual int Bar();
278};
279"""
280    self.assertEqualIgnoreLeadingWhitespace(
281        'MOCK_METHOD0_T(Bar,\nint());',
282        self.GenerateMethodSource(source))
283
284  def testPointerArgWithoutNames(self):
285    source = """
286class Foo {
287  virtual int Bar(C*);
288};
289"""
290    self.assertEqualIgnoreLeadingWhitespace(
291        'MOCK_METHOD1(Bar,\nint(C*));',
292        self.GenerateMethodSource(source))
293
294  def testReferenceArgWithoutNames(self):
295    source = """
296class Foo {
297  virtual int Bar(C&);
298};
299"""
300    self.assertEqualIgnoreLeadingWhitespace(
301        'MOCK_METHOD1(Bar,\nint(C&));',
302        self.GenerateMethodSource(source))
303
304  def testArrayArgWithoutNames(self):
305    source = """
306class Foo {
307  virtual int Bar(C[]);
308};
309"""
310    self.assertEqualIgnoreLeadingWhitespace(
311        'MOCK_METHOD1(Bar,\nint(C[]));',
312        self.GenerateMethodSource(source))
313
314
315class GenerateMocksTest(TestCase):
316
317  def GenerateMocks(self, cpp_source):
318    """Convert C++ source to complete Google Mock output source."""
319    # <test> is a pseudo-filename, it is not read or written.
320    filename = '<test>'
321    builder = ast.BuilderFromSource(cpp_source, filename)
322    ast_list = list(builder.Generate())
323    lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
324    return '\n'.join(lines)
325
326  def testNamespaces(self):
327    source = """
328namespace Foo {
329namespace Bar { class Forward; }
330namespace Baz {
331
332class Test {
333 public:
334  virtual void Foo();
335};
336
337}  // namespace Baz
338}  // namespace Foo
339"""
340    expected = """\
341namespace Foo {
342namespace Baz {
343
344class MockTest : public Test {
345public:
346MOCK_METHOD0(Foo,
347void());
348};
349
350}  // namespace Baz
351}  // namespace Foo
352"""
353    self.assertEqualIgnoreLeadingWhitespace(
354        expected, self.GenerateMocks(source))
355
356  def testClassWithStorageSpecifierMacro(self):
357    source = """
358class STORAGE_SPECIFIER Test {
359 public:
360  virtual void Foo();
361};
362"""
363    expected = """\
364class MockTest : public Test {
365public:
366MOCK_METHOD0(Foo,
367void());
368};
369"""
370    self.assertEqualIgnoreLeadingWhitespace(
371        expected, self.GenerateMocks(source))
372
373  def testTemplatedForwardDeclaration(self):
374    source = """
375template <class T> class Forward;  // Forward declaration should be ignored.
376class Test {
377 public:
378  virtual void Foo();
379};
380"""
381    expected = """\
382class MockTest : public Test {
383public:
384MOCK_METHOD0(Foo,
385void());
386};
387"""
388    self.assertEqualIgnoreLeadingWhitespace(
389        expected, self.GenerateMocks(source))
390
391  def testTemplatedClass(self):
392    source = """
393template <typename S, typename T>
394class Test {
395 public:
396  virtual void Foo();
397};
398"""
399    expected = """\
400template <typename T0, typename T1>
401class MockTest : public Test<T0, T1> {
402public:
403MOCK_METHOD0_T(Foo,
404void());
405};
406"""
407    self.assertEqualIgnoreLeadingWhitespace(
408        expected, self.GenerateMocks(source))
409
410  def testTemplateInATemplateTypedef(self):
411    source = """
412class Test {
413 public:
414  typedef std::vector<std::list<int>> FooType;
415  virtual void Bar(const FooType& test_arg);
416};
417"""
418    expected = """\
419class MockTest : public Test {
420public:
421MOCK_METHOD1(Bar,
422void(const FooType& test_arg));
423};
424"""
425    self.assertEqualIgnoreLeadingWhitespace(
426        expected, self.GenerateMocks(source))
427
428  def testTemplateInATemplateTypedefWithComma(self):
429    source = """
430class Test {
431 public:
432  typedef std::function<void(
433      const vector<std::list<int>>&, int> FooType;
434  virtual void Bar(const FooType& test_arg);
435};
436"""
437    expected = """\
438class MockTest : public Test {
439public:
440MOCK_METHOD1(Bar,
441void(const FooType& test_arg));
442};
443"""
444    self.assertEqualIgnoreLeadingWhitespace(
445        expected, self.GenerateMocks(source))
446
447if __name__ == '__main__':
448  unittest.main()
trunk/3rdparty/googletest/googlemock/scripts/generator/cpp/keywords.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2007 Neal Norwitz
4# Portions Copyright 2007 Google Inc.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""C++ keywords and helper utilities for determining keywords."""
19
20__author__ = 'nnorwitz@google.com (Neal Norwitz)'
21
22
23try:
24    # Python 3.x
25    import builtins
26except ImportError:
27    # Python 2.x
28    import __builtin__ as builtins
29
30
31if not hasattr(builtins, 'set'):
32    # Nominal support for Python 2.3.
33    from sets import Set as set
34
35
36TYPES = set('bool char int long short double float void wchar_t unsigned signed'.split())
37TYPE_MODIFIERS = set('auto register const inline extern static virtual volatile mutable'.split())
38ACCESS = set('public protected private friend'.split())
39
40CASTS = set('static_cast const_cast dynamic_cast reinterpret_cast'.split())
41
42OTHERS = set('true false asm class namespace using explicit this operator sizeof'.split())
43OTHER_TYPES = set('new delete typedef struct union enum typeid typename template'.split())
44
45CONTROL = set('case switch default if else return goto'.split())
46EXCEPTION = set('try catch throw'.split())
47LOOP = set('while do for break continue'.split())
48
49ALL = TYPES | TYPE_MODIFIERS | ACCESS | CASTS | OTHERS | OTHER_TYPES | CONTROL | EXCEPTION | LOOP
50
51
52def IsKeyword(token):
53    return token in ALL
54
55def IsBuiltinType(token):
56    if token in ('virtual', 'inline'):
57        # These only apply to methods, they can't be types by themselves.
58        return False
59    return token in TYPES or token in TYPE_MODIFIERS
trunk/3rdparty/googletest/googlemock/scripts/generator/cpp/tokenize.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2007 Neal Norwitz
4# Portions Copyright 2007 Google Inc.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Tokenize C++ source code."""
19
20__author__ = 'nnorwitz@google.com (Neal Norwitz)'
21
22
23try:
24    # Python 3.x
25    import builtins
26except ImportError:
27    # Python 2.x
28    import __builtin__ as builtins
29
30
31import sys
32
33from cpp import utils
34
35
36if not hasattr(builtins, 'set'):
37    # Nominal support for Python 2.3.
38    from sets import Set as set
39
40
41# Add $ as a valid identifier char since so much code uses it.
42_letters = 'abcdefghijklmnopqrstuvwxyz'
43VALID_IDENTIFIER_CHARS = set(_letters + _letters.upper() + '_0123456789$')
44HEX_DIGITS = set('0123456789abcdefABCDEF')
45INT_OR_FLOAT_DIGITS = set('01234567890eE-+')
46
47
48# C++0x string preffixes.
49_STR_PREFIXES = set(('R', 'u8', 'u8R', 'u', 'uR', 'U', 'UR', 'L', 'LR'))
50
51
52# Token types.
53UNKNOWN = 'UNKNOWN'
54SYNTAX = 'SYNTAX'
55CONSTANT = 'CONSTANT'
56NAME = 'NAME'
57PREPROCESSOR = 'PREPROCESSOR'
58
59# Where the token originated from.  This can be used for backtracking.
60# It is always set to WHENCE_STREAM in this code.
61WHENCE_STREAM, WHENCE_QUEUE = range(2)
62
63
64class Token(object):
65    """Data container to represent a C++ token.
66
67    Tokens can be identifiers, syntax char(s), constants, or
68    pre-processor directives.
69
70    start contains the index of the first char of the token in the source
71    end contains the index of the last char of the token in the source
72    """
73
74    def __init__(self, token_type, name, start, end):
75        self.token_type = token_type
76        self.name = name
77        self.start = start
78        self.end = end
79        self.whence = WHENCE_STREAM
80
81    def __str__(self):
82        if not utils.DEBUG:
83            return 'Token(%r)' % self.name
84        return 'Token(%r, %s, %s)' % (self.name, self.start, self.end)
85
86    __repr__ = __str__
87
88
89def _GetString(source, start, i):
90    i = source.find('"', i+1)
91    while source[i-1] == '\\':
92        # Count the trailing backslashes.
93        backslash_count = 1
94        j = i - 2
95        while source[j] == '\\':
96            backslash_count += 1
97            j -= 1
98        # When trailing backslashes are even, they escape each other.
99        if (backslash_count % 2) == 0:
100            break
101        i = source.find('"', i+1)
102    return i + 1
103
104
105def _GetChar(source, start, i):
106    # NOTE(nnorwitz): may not be quite correct, should be good enough.
107    i = source.find("'", i+1)
108    while source[i-1] == '\\':
109        # Need to special case '\\'.
110        if (i - 2) > start and source[i-2] == '\\':
111            break
112        i = source.find("'", i+1)
113    # Try to handle unterminated single quotes (in a #if 0 block).
114    if i < 0:
115        i = start
116    return i + 1
117
118
119def GetTokens(source):
120    """Returns a sequence of Tokens.
121
122    Args:
123      source: string of C++ source code.
124
125    Yields:
126      Token that represents the next token in the source.
127    """
128    # Cache various valid character sets for speed.
129    valid_identifier_chars = VALID_IDENTIFIER_CHARS
130    hex_digits = HEX_DIGITS
131    int_or_float_digits = INT_OR_FLOAT_DIGITS
132    int_or_float_digits2 = int_or_float_digits | set('.')
133
134    # Only ignore errors while in a #if 0 block.
135    ignore_errors = False
136    count_ifs = 0
137
138    i = 0
139    end = len(source)
140    while i < end:
141        # Skip whitespace.
142        while i < end and source[i].isspace():
143            i += 1
144        if i >= end:
145            return
146
147        token_type = UNKNOWN
148        start = i
149        c = source[i]
150        if c.isalpha() or c == '_':              # Find a string token.
151            token_type = NAME
152            while source[i] in valid_identifier_chars:
153                i += 1
154            # String and character constants can look like a name if
155            # they are something like L"".
156            if (source[i] == "'" and (i - start) == 1 and
157                source[start:i] in 'uUL'):
158                # u, U, and L are valid C++0x character preffixes.
159                token_type = CONSTANT
160                i = _GetChar(source, start, i)
161            elif source[i] == "'" and source[start:i] in _STR_PREFIXES:
162                token_type = CONSTANT
163                i = _GetString(source, start, i)
164        elif c == '/' and source[i+1] == '/':    # Find // comments.
165            i = source.find('\n', i)
166            if i == -1:  # Handle EOF.
167                i = end
168            continue
169        elif c == '/' and source[i+1] == '*':    # Find /* comments. */
170            i = source.find('*/', i) + 2
171            continue
172        elif c in ':+-<>&|*=':                   # : or :: (plus other chars).
173            token_type = SYNTAX
174            i += 1
175            new_ch = source[i]
176            if new_ch == c and c != '>':         # Treat ">>" as two tokens.
177                i += 1
178            elif c == '-' and new_ch == '>':
179                i += 1
180            elif new_ch == '=':
181                i += 1
182        elif c in '()[]{}~!?^%;/.,':             # Handle single char tokens.
183            token_type = SYNTAX
184            i += 1
185            if c == '.' and source[i].isdigit():
186                token_type = CONSTANT
187                i += 1
188                while source[i] in int_or_float_digits:
189                    i += 1
190                # Handle float suffixes.
191                for suffix in ('l', 'f'):
192                    if suffix == source[i:i+1].lower():
193                        i += 1
194                        break
195        elif c.isdigit():                        # Find integer.
196            token_type = CONSTANT
197            if c == '0' and source[i+1] in 'xX':
198                # Handle hex digits.
199                i += 2
200                while source[i] in hex_digits:
201                    i += 1
202            else:
203                while source[i] in int_or_float_digits2:
204                    i += 1
205            # Handle integer (and float) suffixes.
206            for suffix in ('ull', 'll', 'ul', 'l', 'f', 'u'):
207                size = len(suffix)
208                if suffix == source[i:i+size].lower():
209                    i += size
210                    break
211        elif c == '"':                           # Find string.
212            token_type = CONSTANT
213            i = _GetString(source, start, i)
214        elif c == "'":                           # Find char.
215            token_type = CONSTANT
216            i = _GetChar(source, start, i)
217        elif c == '#':                           # Find pre-processor command.
218            token_type = PREPROCESSOR
219            got_if = source[i:i+3] == '#if' and source[i+3:i+4].isspace()
220            if got_if:
221                count_ifs += 1
222            elif source[i:i+6] == '#endif':
223                count_ifs -= 1
224                if count_ifs == 0:
225                    ignore_errors = False
226
227            # TODO(nnorwitz): handle preprocessor statements (\ continuations).
228            while 1:
229                i1 = source.find('\n', i)
230                i2 = source.find('//', i)
231                i3 = source.find('/*', i)
232                i4 = source.find('"', i)
233                # NOTE(nnorwitz): doesn't handle comments in #define macros.
234                # Get the first important symbol (newline, comment, EOF/end).
235                i = min([x for x in (i1, i2, i3, i4, end) if x != -1])
236
237                # Handle #include "dir//foo.h" properly.
238                if source[i] == '"':
239                    i = source.find('"', i+1) + 1
240                    assert i > 0
241                    continue
242                # Keep going if end of the line and the line ends with \.
243                if not (i == i1 and source[i-1] == '\\'):
244                    if got_if:
245                        condition = source[start+4:i].lstrip()
246                        if (condition.startswith('0') or
247                            condition.startswith('(0)')):
248                            ignore_errors = True
249                    break
250                i += 1
251        elif c == '\\':                          # Handle \ in code.
252            # This is different from the pre-processor \ handling.
253            i += 1
254            continue
255        elif ignore_errors:
256            # The tokenizer seems to be in pretty good shape.  This
257            # raise is conditionally disabled so that bogus code
258            # in an #if 0 block can be handled.  Since we will ignore
259            # it anyways, this is probably fine.  So disable the
260            # exception and  return the bogus char.
261            i += 1
262        else:
263            sys.stderr.write('Got invalid token in %s @ %d token:%s: %r\n' %
264                             ('?', i, c, source[i-10:i+10]))
265            raise RuntimeError('unexpected token')
266
267        if i <= 0:
268            print('Invalid index, exiting now.')
269            return
270        yield Token(token_type, source[start:i], start, i)
271
272
273if __name__ == '__main__':
274    def main(argv):
275        """Driver mostly for testing purposes."""
276        for filename in argv[1:]:
277            source = utils.ReadFile(filename)
278            if source is None:
279                continue
280
281            for token in GetTokens(source):
282                print('%-12s: %s' % (token.token_type, token.name))
283                # print('\r%6.2f%%' % (100.0 * index / token.end),)
284            sys.stdout.write('\n')
285
286
287    main(sys.argv)
trunk/3rdparty/googletest/googlemock/scripts/generator/cpp/utils.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2007 Neal Norwitz
4# Portions Copyright 2007 Google Inc.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Generic utilities for C++ parsing."""
19
20__author__ = 'nnorwitz@google.com (Neal Norwitz)'
21
22
23import sys
24
25
26# Set to True to see the start/end token indices.
27DEBUG = True
28
29
30def ReadFile(filename, print_error=True):
31    """Returns the contents of a file."""
32    try:
33        fp = open(filename)
34        try:
35            return fp.read()
36        finally:
37            fp.close()
38    except IOError:
39        if print_error:
40            print('Error reading %s: %s' % (filename, sys.exc_info()[1]))
41        return None
trunk/3rdparty/googletest/googlemock/scripts/generator/gmock_gen.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008 Google Inc. All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Driver for starting up Google Mock class generator."""
18
19__author__ = 'nnorwitz@google.com (Neal Norwitz)'
20
21import os
22import sys
23
24if __name__ == '__main__':
25  # Add the directory of this script to the path so we can import gmock_class.
26  sys.path.append(os.path.dirname(__file__))
27
28  from cpp import gmock_class
29  # Fix the docstring in case they require the usage.
30  gmock_class.__doc__ = gmock_class.__doc__.replace('gmock_class.py', __file__)
31  gmock_class.main()
trunk/3rdparty/googletest/googlemock/scripts/gmock-config.in
r0r249096
1#!/bin/sh
2
3# These variables are automatically filled in by the configure script.
4name="@PACKAGE_TARNAME@"
5version="@PACKAGE_VERSION@"
6
7show_usage()
8{
9  echo "Usage: gmock-config [OPTIONS...]"
10}
11
12show_help()
13{
14  show_usage
15  cat <<\EOF
16
17The `gmock-config' script provides access to the necessary compile and linking
18flags to connect with Google C++ Mocking Framework, both in a build prior to
19installation, and on the system proper after installation. The installation
20overrides may be issued in combination with any other queries, but will only
21affect installation queries if called on a built but not installed gmock. The
22installation queries may not be issued with any other types of queries, and
23only one installation query may be made at a time. The version queries and
24compiler flag queries may be combined as desired but not mixed. Different
25version queries are always combined with logical "and" semantics, and only the
26last of any particular query is used while all previous ones ignored. All
27versions must be specified as a sequence of numbers separated by periods.
28Compiler flag queries output the union of the sets of flags when combined.
29
30 Examples:
31  gmock-config --min-version=1.0 || echo "Insufficient Google Mock version."
32
33  g++ $(gmock-config --cppflags --cxxflags) -o foo.o -c foo.cpp
34  g++ $(gmock-config --ldflags --libs) -o foo foo.o
35
36  # When using a built but not installed Google Mock:
37  g++ $(../../my_gmock_build/scripts/gmock-config ...) ...
38
39  # When using an installed Google Mock, but with installation overrides:
40  export GMOCK_PREFIX="/opt"
41  g++ $(gmock-config --libdir="/opt/lib64" ...) ...
42
43 Help:
44  --usage                    brief usage information
45  --help                     display this help message
46
47 Installation Overrides:
48  --prefix=<dir>             overrides the installation prefix
49  --exec-prefix=<dir>        overrides the executable installation prefix
50  --libdir=<dir>             overrides the library installation prefix
51  --includedir=<dir>         overrides the header file installation prefix
52
53 Installation Queries:
54  --prefix                   installation prefix
55  --exec-prefix              executable installation prefix
56  --libdir                   library installation directory
57  --includedir               header file installation directory
58  --version                  the version of the Google Mock installation
59
60 Version Queries:
61  --min-version=VERSION      return 0 if the version is at least VERSION
62  --exact-version=VERSION    return 0 if the version is exactly VERSION
63  --max-version=VERSION      return 0 if the version is at most VERSION
64
65 Compilation Flag Queries:
66  --cppflags                 compile flags specific to the C-like preprocessors
67  --cxxflags                 compile flags appropriate for C++ programs
68  --ldflags                  linker flags
69  --libs                     libraries for linking
70
71EOF
72}
73
74# This function bounds our version with a min and a max. It uses some clever
75# POSIX-compliant variable expansion to portably do all the work in the shell
76# and avoid any dependency on a particular "sed" or "awk" implementation.
77# Notable is that it will only ever compare the first 3 components of versions.
78# Further components will be cleanly stripped off. All versions must be
79# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and
80# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should
81# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than
82# continuing to maintain our own shell version.
83check_versions()
84{
85  major_version=${version%%.*}
86  minor_version="0"
87  point_version="0"
88  if test "${version#*.}" != "${version}"; then
89    minor_version=${version#*.}
90    minor_version=${minor_version%%.*}
91  fi
92  if test "${version#*.*.}" != "${version}"; then
93    point_version=${version#*.*.}
94    point_version=${point_version%%.*}
95  fi
96
97  min_version="$1"
98  min_major_version=${min_version%%.*}
99  min_minor_version="0"
100  min_point_version="0"
101  if test "${min_version#*.}" != "${min_version}"; then
102    min_minor_version=${min_version#*.}
103    min_minor_version=${min_minor_version%%.*}
104  fi
105  if test "${min_version#*.*.}" != "${min_version}"; then
106    min_point_version=${min_version#*.*.}
107    min_point_version=${min_point_version%%.*}
108  fi
109
110  max_version="$2"
111  max_major_version=${max_version%%.*}
112  max_minor_version="0"
113  max_point_version="0"
114  if test "${max_version#*.}" != "${max_version}"; then
115    max_minor_version=${max_version#*.}
116    max_minor_version=${max_minor_version%%.*}
117  fi
118  if test "${max_version#*.*.}" != "${max_version}"; then
119    max_point_version=${max_version#*.*.}
120    max_point_version=${max_point_version%%.*}
121  fi
122
123  test $(($major_version)) -lt $(($min_major_version)) && exit 1
124  if test $(($major_version)) -eq $(($min_major_version)); then
125    test $(($minor_version)) -lt $(($min_minor_version)) && exit 1
126    if test $(($minor_version)) -eq $(($min_minor_version)); then
127      test $(($point_version)) -lt $(($min_point_version)) && exit 1
128    fi
129  fi
130
131  test $(($major_version)) -gt $(($max_major_version)) && exit 1
132  if test $(($major_version)) -eq $(($max_major_version)); then
133    test $(($minor_version)) -gt $(($max_minor_version)) && exit 1
134    if test $(($minor_version)) -eq $(($max_minor_version)); then
135      test $(($point_version)) -gt $(($max_point_version)) && exit 1
136    fi
137  fi
138
139  exit 0
140}
141
142# Show the usage line when no arguments are specified.
143if test $# -eq 0; then
144  show_usage
145  exit 1
146fi
147
148while test $# -gt 0; do
149  case $1 in
150    --usage)          show_usage;         exit 0;;
151    --help)           show_help;          exit 0;;
152
153    # Installation overrides
154    --prefix=*)       GMOCK_PREFIX=${1#--prefix=};;
155    --exec-prefix=*)  GMOCK_EXEC_PREFIX=${1#--exec-prefix=};;
156    --libdir=*)       GMOCK_LIBDIR=${1#--libdir=};;
157    --includedir=*)   GMOCK_INCLUDEDIR=${1#--includedir=};;
158
159    # Installation queries
160    --prefix|--exec-prefix|--libdir|--includedir|--version)
161      if test -n "${do_query}"; then
162        show_usage
163        exit 1
164      fi
165      do_query=${1#--}
166      ;;
167
168    # Version checking
169    --min-version=*)
170      do_check_versions=yes
171      min_version=${1#--min-version=}
172      ;;
173    --max-version=*)
174      do_check_versions=yes
175      max_version=${1#--max-version=}
176      ;;
177    --exact-version=*)
178      do_check_versions=yes
179      exact_version=${1#--exact-version=}
180      ;;
181
182    # Compiler flag output
183    --cppflags)       echo_cppflags=yes;;
184    --cxxflags)       echo_cxxflags=yes;;
185    --ldflags)        echo_ldflags=yes;;
186    --libs)           echo_libs=yes;;
187
188    # Everything else is an error
189    *)                show_usage;         exit 1;;
190  esac
191  shift
192done
193
194# These have defaults filled in by the configure script but can also be
195# overridden by environment variables or command line parameters.
196prefix="${GMOCK_PREFIX:-@prefix@}"
197exec_prefix="${GMOCK_EXEC_PREFIX:-@exec_prefix@}"
198libdir="${GMOCK_LIBDIR:-@libdir@}"
199includedir="${GMOCK_INCLUDEDIR:-@includedir@}"
200
201# We try and detect if our binary is not located at its installed location. If
202# it's not, we provide variables pointing to the source and build tree rather
203# than to the install tree. We also locate Google Test using the configured
204# gtest-config script rather than searching the PATH and our bindir for one.
205# This allows building against a just-built gmock rather than an installed
206# gmock.
207bindir="@bindir@"
208this_relative_bindir=`dirname $0`
209this_bindir=`cd ${this_relative_bindir}; pwd -P`
210if test "${this_bindir}" = "${this_bindir%${bindir}}"; then
211  # The path to the script doesn't end in the bindir sequence from Autoconf,
212  # assume that we are in a build tree.
213  build_dir=`dirname ${this_bindir}`
214  src_dir=`cd ${this_bindir}/@top_srcdir@; pwd -P`
215
216  # TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we
217  # should work to remove it, and/or remove libtool altogether, replacing it
218  # with direct references to the library and a link path.
219  gmock_libs="${build_dir}/lib/libgmock.la"
220  gmock_ldflags=""
221
222  # We provide hooks to include from either the source or build dir, where the
223  # build dir is always preferred. This will potentially allow us to write
224  # build rules for generated headers and have them automatically be preferred
225  # over provided versions.
226  gmock_cppflags="-I${build_dir}/include -I${src_dir}/include"
227  gmock_cxxflags=""
228
229  # Directly invoke the gtest-config script used during the build process.
230  gtest_config="@GTEST_CONFIG@"
231else
232  # We're using an installed gmock, although it may be staged under some
233  # prefix. Assume (as our own libraries do) that we can resolve the prefix,
234  # and are present in the dynamic link paths.
235  gmock_ldflags="-L${libdir}"
236  gmock_libs="-l${name}"
237  gmock_cppflags="-I${includedir}"
238  gmock_cxxflags=""
239
240  # We also prefer any gtest-config script installed in our prefix. Lacking
241  # one, we look in the PATH for one.
242  gtest_config="${bindir}/gtest-config"
243  if test ! -x "${gtest_config}"; then
244    gtest_config=`which gtest-config`
245  fi
246fi
247
248# Ensure that we have located a Google Test to link against.
249if ! test -x "${gtest_config}"; then
250  echo "Unable to locate Google Test, check your Google Mock configuration" \
251       "and installation" >&2
252  exit 1
253elif ! "${gtest_config}" "--exact-version=@GTEST_VERSION@"; then
254  echo "The Google Test found is not the same version as Google Mock was " \
255       "built against" >&2
256  exit 1
257fi
258
259# Add the necessary Google Test bits into the various flag variables
260gmock_cppflags="${gmock_cppflags} `${gtest_config} --cppflags`"
261gmock_cxxflags="${gmock_cxxflags} `${gtest_config} --cxxflags`"
262gmock_ldflags="${gmock_ldflags} `${gtest_config} --ldflags`"
263gmock_libs="${gmock_libs} `${gtest_config} --libs`"
264
265# Do an installation query if requested.
266if test -n "$do_query"; then
267  case $do_query in
268    prefix)           echo $prefix;       exit 0;;
269    exec-prefix)      echo $exec_prefix;  exit 0;;
270    libdir)           echo $libdir;       exit 0;;
271    includedir)       echo $includedir;   exit 0;;
272    version)          echo $version;      exit 0;;
273    *)                show_usage;         exit 1;;
274  esac
275fi
276
277# Do a version check if requested.
278if test "$do_check_versions" = "yes"; then
279  # Make sure we didn't receive a bad combination of parameters.
280  test "$echo_cppflags" = "yes" && show_usage && exit 1
281  test "$echo_cxxflags" = "yes" && show_usage && exit 1
282  test "$echo_ldflags" = "yes"  && show_usage && exit 1
283  test "$echo_libs" = "yes"     && show_usage && exit 1
284
285  if test "$exact_version" != ""; then
286    check_versions $exact_version $exact_version
287    # unreachable
288  else
289    check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999}
290    # unreachable
291  fi
292fi
293
294# Do the output in the correct order so that these can be used in-line of
295# a compiler invocation.
296output=""
297test "$echo_cppflags" = "yes" && output="$output $gmock_cppflags"
298test "$echo_cxxflags" = "yes" && output="$output $gmock_cxxflags"
299test "$echo_ldflags" = "yes"  && output="$output $gmock_ldflags"
300test "$echo_libs" = "yes"     && output="$output $gmock_libs"
301echo $output
302
303exit 0
trunk/3rdparty/googletest/googlemock/scripts/gmock_doctor.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Converts compiler's errors in code using Google Mock to plain English."""
33
34__author__ = 'wan@google.com (Zhanyong Wan)'
35
36import re
37import sys
38
39_VERSION = '1.0.3'
40
41_EMAIL = 'googlemock@googlegroups.com'
42
43_COMMON_GMOCK_SYMBOLS = [
44    # Matchers
45    '_',
46    'A',
47    'AddressSatisfies',
48    'AllOf',
49    'An',
50    'AnyOf',
51    'ContainerEq',
52    'Contains',
53    'ContainsRegex',
54    'DoubleEq',
55    'ElementsAre',
56    'ElementsAreArray',
57    'EndsWith',
58    'Eq',
59    'Field',
60    'FloatEq',
61    'Ge',
62    'Gt',
63    'HasSubstr',
64    'IsInitializedProto',
65    'Le',
66    'Lt',
67    'MatcherCast',
68    'Matches',
69    'MatchesRegex',
70    'NanSensitiveDoubleEq',
71    'NanSensitiveFloatEq',
72    'Ne',
73    'Not',
74    'NotNull',
75    'Pointee',
76    'Property',
77    'Ref',
78    'ResultOf',
79    'SafeMatcherCast',
80    'StartsWith',
81    'StrCaseEq',
82    'StrCaseNe',
83    'StrEq',
84    'StrNe',
85    'Truly',
86    'TypedEq',
87    'Value',
88
89    # Actions
90    'Assign',
91    'ByRef',
92    'DeleteArg',
93    'DoAll',
94    'DoDefault',
95    'IgnoreResult',
96    'Invoke',
97    'InvokeArgument',
98    'InvokeWithoutArgs',
99    'Return',
100    'ReturnNew',
101    'ReturnNull',
102    'ReturnRef',
103    'SaveArg',
104    'SetArgReferee',
105    'SetArgPointee',
106    'SetArgumentPointee',
107    'SetArrayArgument',
108    'SetErrnoAndReturn',
109    'Throw',
110    'WithArg',
111    'WithArgs',
112    'WithoutArgs',
113
114    # Cardinalities
115    'AnyNumber',
116    'AtLeast',
117    'AtMost',
118    'Between',
119    'Exactly',
120
121    # Sequences
122    'InSequence',
123    'Sequence',
124
125    # Misc
126    'DefaultValue',
127    'Mock',
128    ]
129
130# Regex for matching source file path and line number in the compiler's errors.
131_GCC_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(\d+:)?\s+'
132_CLANG_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(?P<column>\d+):\s+'
133_CLANG_NON_GMOCK_FILE_LINE_RE = (
134    r'(?P<file>.*[/\\^](?!gmock-)[^/\\]+):(?P<line>\d+):(?P<column>\d+):\s+')
135
136
137def _FindAllMatches(regex, s):
138  """Generates all matches of regex in string s."""
139
140  r = re.compile(regex)
141  return r.finditer(s)
142
143
144def _GenericDiagnoser(short_name, long_name, diagnoses, msg):
145  """Diagnoses the given disease by pattern matching.
146
147  Can provide different diagnoses for different patterns.
148
149  Args:
150    short_name: Short name of the disease.
151    long_name:  Long name of the disease.
152    diagnoses:  A list of pairs (regex, pattern for formatting the diagnosis
153                for matching regex).
154    msg:        Compiler's error messages.
155  Yields:
156    Tuples of the form
157      (short name of disease, long name of disease, diagnosis).
158  """
159  for regex, diagnosis in diagnoses:
160    if re.search(regex, msg):
161      diagnosis = '%(file)s:%(line)s:' + diagnosis
162      for m in _FindAllMatches(regex, msg):
163        yield (short_name, long_name, diagnosis % m.groupdict())
164
165
166def _NeedToReturnReferenceDiagnoser(msg):
167  """Diagnoses the NRR disease, given the error messages by the compiler."""
168
169  gcc_regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
170               + _GCC_FILE_LINE_RE + r'instantiated from here\n'
171               r'.*gmock-actions\.h.*error: creating array with negative size')
172  clang_regex = (r'error:.*array.*negative.*\r?\n'
173                 r'(.*\n)*?' +
174                 _CLANG_NON_GMOCK_FILE_LINE_RE +
175                 r'note: in instantiation of function template specialization '
176                 r'\'testing::internal::ReturnAction<(?P<type>.*)>'
177                 r'::operator Action<.*>\' requested here')
178  clang11_re = (r'use_ReturnRef_instead_of_Return_to_return_a_reference.*'
179                r'(.*\n)*?' + _CLANG_NON_GMOCK_FILE_LINE_RE)
180
181  diagnosis = """
182You are using a Return() action in a function that returns a reference to
183%(type)s.  Please use ReturnRef() instead."""
184  return _GenericDiagnoser('NRR', 'Need to Return Reference',
185                           [(clang_regex, diagnosis),
186                            (clang11_re, diagnosis % {'type': 'a type'}),
187                            (gcc_regex, diagnosis % {'type': 'a type'})],
188                           msg)
189
190
191def _NeedToReturnSomethingDiagnoser(msg):
192  """Diagnoses the NRS disease, given the error messages by the compiler."""
193
194  gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.'
195               r'*gmock.*actions\.h.*error: void value not ignored)'
196               r'|(error: control reaches end of non-void function)')
197  clang_regex1 = (_CLANG_FILE_LINE_RE +
198                  r'error: cannot initialize return object '
199                  r'of type \'Result\' \(aka \'(?P<return_type>.*)\'\) '
200                  r'with an rvalue of type \'void\'')
201  clang_regex2 = (_CLANG_FILE_LINE_RE +
202                  r'error: cannot initialize return object '
203                  r'of type \'(?P<return_type>.*)\' '
204                  r'with an rvalue of type \'void\'')
205  diagnosis = """
206You are using an action that returns void, but it needs to return
207%(return_type)s.  Please tell it *what* to return.  Perhaps you can use
208the pattern DoAll(some_action, Return(some_value))?"""
209  return _GenericDiagnoser(
210      'NRS',
211      'Need to Return Something',
212      [(gcc_regex, diagnosis % {'return_type': '*something*'}),
213       (clang_regex1, diagnosis),
214       (clang_regex2, diagnosis)],
215      msg)
216
217
218def _NeedToReturnNothingDiagnoser(msg):
219  """Diagnoses the NRN disease, given the error messages by the compiler."""
220
221  gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
222               r'.*gmock-actions\.h.*error: instantiation of '
223               r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
224               r'as type \'void\'')
225  clang_regex1 = (r'error: field has incomplete type '
226                  r'\'Result\' \(aka \'void\'\)(\r)?\n'
227                  r'(.*\n)*?' +
228                  _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
229                  r'of function template specialization '
230                  r'\'testing::internal::ReturnAction<(?P<return_type>.*)>'
231                  r'::operator Action<void \(.*\)>\' requested here')
232  clang_regex2 = (r'error: field has incomplete type '
233                  r'\'Result\' \(aka \'void\'\)(\r)?\n'
234                  r'(.*\n)*?' +
235                  _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
236                  r'of function template specialization '
237                  r'\'testing::internal::DoBothAction<.*>'
238                  r'::operator Action<(?P<return_type>.*) \(.*\)>\' '
239                  r'requested here')
240  diagnosis = """
241You are using an action that returns %(return_type)s, but it needs to return
242void.  Please use a void-returning action instead.
243
244All actions but the last in DoAll(...) must return void.  Perhaps you need
245to re-arrange the order of actions in a DoAll(), if you are using one?"""
246  return _GenericDiagnoser(
247      'NRN',
248      'Need to Return Nothing',
249      [(gcc_regex, diagnosis % {'return_type': '*something*'}),
250       (clang_regex1, diagnosis),
251       (clang_regex2, diagnosis)],
252      msg)
253
254
255def _IncompleteByReferenceArgumentDiagnoser(msg):
256  """Diagnoses the IBRA disease, given the error messages by the compiler."""
257
258  gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
259               r'.*gtest-printers\.h.*error: invalid application of '
260               r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
261
262  clang_regex = (r'.*gtest-printers\.h.*error: invalid application of '
263                 r'\'sizeof\' to an incomplete type '
264                 r'\'(?P<type>.*)( const)?\'\r?\n'
265                 r'(.*\n)*?' +
266                 _CLANG_NON_GMOCK_FILE_LINE_RE +
267                 r'note: in instantiation of member function '
268                 r'\'testing::internal2::TypeWithoutFormatter<.*>::'
269                 r'PrintValue\' requested here')
270  diagnosis = """
271In order to mock this function, Google Mock needs to see the definition
272of type "%(type)s" - declaration alone is not enough.  Either #include
273the header that defines it, or change the argument to be passed
274by pointer."""
275
276  return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
277                           [(gcc_regex, diagnosis),
278                            (clang_regex, diagnosis)],
279                           msg)
280
281
282def _OverloadedFunctionMatcherDiagnoser(msg):
283  """Diagnoses the OFM disease, given the error messages by the compiler."""
284
285  gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
286               r'call to \'Truly\(<unresolved overloaded function type>\)')
287  clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function for '
288                 r'call to \'Truly')
289  diagnosis = """
290The argument you gave to Truly() is an overloaded function.  Please tell
291your compiler which overloaded version you want to use.
292
293For example, if you want to use the version whose signature is
294  bool Foo(int n);
295you should write
296  Truly(static_cast<bool (*)(int n)>(Foo))"""
297  return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
298                           [(gcc_regex, diagnosis),
299                            (clang_regex, diagnosis)],
300                           msg)
301
302
303def _OverloadedFunctionActionDiagnoser(msg):
304  """Diagnoses the OFA disease, given the error messages by the compiler."""
305
306  gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to '
307               r'\'Invoke\(<unresolved overloaded function type>')
308  clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching '
309                 r'function for call to \'Invoke\'\r?\n'
310                 r'(.*\n)*?'
311                 r'.*\bgmock-generated-actions\.h:\d+:\d+:\s+'
312                 r'note: candidate template ignored:\s+'
313                 r'couldn\'t infer template argument \'FunctionImpl\'')
314  diagnosis = """
315Function you are passing to Invoke is overloaded.  Please tell your compiler
316which overloaded version you want to use.
317
318For example, if you want to use the version whose signature is
319  bool MyFunction(int n, double x);
320you should write something like
321  Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
322  return _GenericDiagnoser('OFA', 'Overloaded Function Action',
323                           [(gcc_regex, diagnosis),
324                            (clang_regex, diagnosis)],
325                           msg)
326
327
328def _OverloadedMethodActionDiagnoser(msg):
329  """Diagnoses the OMA disease, given the error messages by the compiler."""
330
331  gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
332               r'call to \'Invoke\(.+, <unresolved overloaded function '
333               r'type>\)')
334  clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function '
335                 r'for call to \'Invoke\'\r?\n'
336                 r'(.*\n)*?'
337                 r'.*\bgmock-generated-actions\.h:\d+:\d+: '
338                 r'note: candidate function template not viable: '
339                 r'requires .*, but 2 (arguments )?were provided')
340  diagnosis = """
341The second argument you gave to Invoke() is an overloaded method.  Please
342tell your compiler which overloaded version you want to use.
343
344For example, if you want to use the version whose signature is
345  class Foo {
346    ...
347    bool Bar(int n, double x);
348  };
349you should write something like
350  Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
351  return _GenericDiagnoser('OMA', 'Overloaded Method Action',
352                           [(gcc_regex, diagnosis),
353                            (clang_regex, diagnosis)],
354                           msg)
355
356
357def _MockObjectPointerDiagnoser(msg):
358  """Diagnoses the MOP disease, given the error messages by the compiler."""
359
360  gcc_regex = (_GCC_FILE_LINE_RE + r'error: request for member '
361               r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
362               r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
363  clang_regex = (_CLANG_FILE_LINE_RE + r'error: member reference type '
364                 r'\'(?P<class_name>.*?) *\' is a pointer; '
365                 r'(did you mean|maybe you meant) to use \'->\'\?')
366  diagnosis = """
367The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
368not a *pointer* to it.  Please write '*(%(mock_object)s)' instead of
369'%(mock_object)s' as your first argument.
370
371For example, given the mock class:
372
373  class %(class_name)s : public ... {
374    ...
375    MOCK_METHOD0(%(method)s, ...);
376  };
377
378and the following mock instance:
379
380  %(class_name)s* mock_ptr = ...
381
382you should use the EXPECT_CALL like this:
383
384  EXPECT_CALL(*mock_ptr, %(method)s(...));"""
385
386  return _GenericDiagnoser(
387      'MOP',
388      'Mock Object Pointer',
389      [(gcc_regex, diagnosis),
390       (clang_regex, diagnosis % {'mock_object': 'mock_object',
391                                  'method': 'method',
392                                  'class_name': '%(class_name)s'})],
393       msg)
394
395
396def _NeedToUseSymbolDiagnoser(msg):
397  """Diagnoses the NUS disease, given the error messages by the compiler."""
398
399  gcc_regex = (_GCC_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
400               r'(was not declared in this scope|has not been declared)')
401  clang_regex = (_CLANG_FILE_LINE_RE +
402                 r'error: (use of undeclared identifier|unknown type name|'
403                 r'no template named) \'(?P<symbol>[^\']+)\'')
404  diagnosis = """
405'%(symbol)s' is defined by Google Mock in the testing namespace.
406Did you forget to write
407  using testing::%(symbol)s;
408?"""
409  for m in (list(_FindAllMatches(gcc_regex, msg)) +
410            list(_FindAllMatches(clang_regex, msg))):
411    symbol = m.groupdict()['symbol']
412    if symbol in _COMMON_GMOCK_SYMBOLS:
413      yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())
414
415
416def _NeedToUseReturnNullDiagnoser(msg):
417  """Diagnoses the NRNULL disease, given the error messages by the compiler."""
418
419  gcc_regex = ('instantiated from \'testing::internal::ReturnAction<R>'
420               '::operator testing::Action<Func>\(\) const.*\n' +
421               _GCC_FILE_LINE_RE + r'instantiated from here\n'
422               r'.*error: no matching function for call to \'ImplicitCast_\('
423               r'(:?long )?int&\)')
424  clang_regex = (r'\bgmock-actions.h:.* error: no matching function for '
425                 r'call to \'ImplicitCast_\'\r?\n'
426                 r'(.*\n)*?' +
427                 _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
428                 r'of function template specialization '
429                 r'\'testing::internal::ReturnAction<(int|long)>::operator '
430                 r'Action<(?P<type>.*)\(\)>\' requested here')
431  diagnosis = """
432You are probably calling Return(NULL) and the compiler isn't sure how to turn
433NULL into %(type)s. Use ReturnNull() instead.
434Note: the line number may be off; please fix all instances of Return(NULL)."""
435  return _GenericDiagnoser(
436      'NRNULL', 'Need to use ReturnNull',
437      [(clang_regex, diagnosis),
438       (gcc_regex, diagnosis % {'type': 'the right type'})],
439      msg)
440
441
442def _TypeInTemplatedBaseDiagnoser(msg):
443  """Diagnoses the TTB disease, given the error messages by the compiler."""
444
445  # This version works when the type is used as the mock function's return
446  # type.
447  gcc_4_3_1_regex_type_in_retval = (
448      r'In member function \'int .*\n' + _GCC_FILE_LINE_RE +
449      r'error: a function call cannot appear in a constant-expression')
450  gcc_4_4_0_regex_type_in_retval = (
451      r'error: a function call cannot appear in a constant-expression'
452      + _GCC_FILE_LINE_RE + r'error: template argument 1 is invalid\n')
453  # This version works when the type is used as the mock function's sole
454  # parameter type.
455  gcc_regex_type_of_sole_param = (
456      _GCC_FILE_LINE_RE +
457      r'error: \'(?P<type>.+)\' was not declared in this scope\n'
458      r'.*error: template argument 1 is invalid\n')
459  # This version works when the type is used as a parameter of a mock
460  # function that has multiple parameters.
461  gcc_regex_type_of_a_param = (
462      r'error: expected `;\' before \'::\' token\n'
463      + _GCC_FILE_LINE_RE +
464      r'error: \'(?P<type>.+)\' was not declared in this scope\n'
465      r'.*error: template argument 1 is invalid\n'
466      r'.*error: \'.+\' was not declared in this scope')
467  clang_regex_type_of_retval_or_sole_param = (
468      _CLANG_FILE_LINE_RE +
469      r'error: use of undeclared identifier \'(?P<type>.*)\'\n'
470      r'(.*\n)*?'
471      r'(?P=file):(?P=line):\d+: error: '
472      r'non-friend class member \'Result\' cannot have a qualified name'
473      )
474  clang_regex_type_of_a_param = (
475      _CLANG_FILE_LINE_RE +
476      r'error: C\+\+ requires a type specifier for all declarations\n'
477      r'(.*\n)*?'
478      r'(?P=file):(?P=line):(?P=column): error: '
479      r'C\+\+ requires a type specifier for all declarations'
480      )
481  clang_regex_unknown_type = (
482      _CLANG_FILE_LINE_RE +
483      r'error: unknown type name \'(?P<type>[^\']+)\''
484      )
485
486  diagnosis = """
487In a mock class template, types or typedefs defined in the base class
488template are *not* automatically visible.  This is how C++ works.  Before
489you can use a type or typedef named %(type)s defined in base class Base<T>, you
490need to make it visible.  One way to do it is:
491
492  typedef typename Base<T>::%(type)s %(type)s;"""
493
494  for diag in _GenericDiagnoser(
495      'TTB', 'Type in Template Base',
496      [(gcc_4_3_1_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
497       (gcc_4_4_0_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
498       (gcc_regex_type_of_sole_param, diagnosis),
499       (gcc_regex_type_of_a_param, diagnosis),
500       (clang_regex_type_of_retval_or_sole_param, diagnosis),
501       (clang_regex_type_of_a_param, diagnosis % {'type': 'Foo'})],
502      msg):
503    yield diag
504  # Avoid overlap with the NUS pattern.
505  for m in _FindAllMatches(clang_regex_unknown_type, msg):
506    type_ = m.groupdict()['type']
507    if type_ not in _COMMON_GMOCK_SYMBOLS:
508      yield ('TTB', 'Type in Template Base', diagnosis % m.groupdict())
509
510
511def _WrongMockMethodMacroDiagnoser(msg):
512  """Diagnoses the WMM disease, given the error messages by the compiler."""
513
514  gcc_regex = (_GCC_FILE_LINE_RE +
515               r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
516               r'.*\n'
517               r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
518  clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
519                 r'error:.*array.*negative.*r?\n'
520                 r'(.*\n)*?'
521                 r'(?P=file):(?P=line):(?P=column): error: too few arguments '
522                 r'to function call, expected (?P<args>\d+), '
523                 r'have (?P<wrong_args>\d+)')
524  clang11_re = (_CLANG_NON_GMOCK_FILE_LINE_RE +
525                r'.*this_method_does_not_take_'
526                r'(?P<wrong_args>\d+)_argument.*')
527  diagnosis = """
528You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
529%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
530MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
531  return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
532                           [(gcc_regex, diagnosis),
533                            (clang11_re, diagnosis % {'wrong_args': 'm',
534                                                      'args': 'n'}),
535                            (clang_regex, diagnosis)],
536                           msg)
537
538
539def _WrongParenPositionDiagnoser(msg):
540  """Diagnoses the WPP disease, given the error messages by the compiler."""
541
542  gcc_regex = (_GCC_FILE_LINE_RE +
543               r'error:.*testing::internal::MockSpec<.* has no member named \''
544               r'(?P<method>\w+)\'')
545  clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
546                 r'error: no member named \'(?P<method>\w+)\' in '
547                 r'\'testing::internal::MockSpec<.*>\'')
548  diagnosis = """
549The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
550".%(method)s".  For example, you should write:
551  EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
552instead of:
553  EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
554  return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
555                           [(gcc_regex, diagnosis),
556                            (clang_regex, diagnosis)],
557                           msg)
558
559
560_DIAGNOSERS = [
561    _IncompleteByReferenceArgumentDiagnoser,
562    _MockObjectPointerDiagnoser,
563    _NeedToReturnNothingDiagnoser,
564    _NeedToReturnReferenceDiagnoser,
565    _NeedToReturnSomethingDiagnoser,
566    _NeedToUseReturnNullDiagnoser,
567    _NeedToUseSymbolDiagnoser,
568    _OverloadedFunctionActionDiagnoser,
569    _OverloadedFunctionMatcherDiagnoser,
570    _OverloadedMethodActionDiagnoser,
571    _TypeInTemplatedBaseDiagnoser,
572    _WrongMockMethodMacroDiagnoser,
573    _WrongParenPositionDiagnoser,
574    ]
575
576
577def Diagnose(msg):
578  """Generates all possible diagnoses given the compiler error message."""
579
580  msg = re.sub(r'\x1b\[[^m]*m', '', msg)  # Strips all color formatting.
581  # Assuming the string is using the UTF-8 encoding, replaces the left and
582  # the right single quote characters with apostrophes.
583  msg = re.sub(r'(\xe2\x80\x98|\xe2\x80\x99)', "'", msg)
584
585  diagnoses = []
586  for diagnoser in _DIAGNOSERS:
587    for diag in diagnoser(msg):
588      diagnosis = '[%s - %s]\n%s' % diag
589      if not diagnosis in diagnoses:
590        diagnoses.append(diagnosis)
591  return diagnoses
592
593
594def main():
595  print ('Google Mock Doctor v%s - '
596         'diagnoses problems in code using Google Mock.' % _VERSION)
597
598  if sys.stdin.isatty():
599    print ('Please copy and paste the compiler errors here.  Press c-D when '
600           'you are done:')
601  else:
602    print ('Waiting for compiler errors on stdin . . .')
603
604  msg = sys.stdin.read().strip()
605  diagnoses = Diagnose(msg)
606  count = len(diagnoses)
607  if not count:
608    print ("""
609Your compiler complained:
6108<------------------------------------------------------------
611%s
612------------------------------------------------------------>8
613
614Uh-oh, I'm not smart enough to figure out what the problem is. :-(
615However...
616If you send your source code and the compiler's error messages to
617%s, you can be helped and I can get smarter --
618win-win for us!""" % (msg, _EMAIL))
619  else:
620    print ('------------------------------------------------------------')
621    print ('Your code appears to have the following',)
622    if count > 1:
623      print ('%s diseases:' % (count,))
624    else:
625      print ('disease:')
626    i = 0
627    for d in diagnoses:
628      i += 1
629      if count > 1:
630        print ('\n#%s:' % (i,))
631      print (d)
632    print ("""
633How did I do?  If you think I'm wrong or unhelpful, please send your
634source code and the compiler's error messages to %s.
635Then you can be helped and I can get smarter -- I promise I won't be upset!""" %
636           _EMAIL)
637
638
639if __name__ == '__main__':
640  main()
trunk/3rdparty/googletest/googlemock/scripts/upload.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2007 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Tool for uploading diffs from a version control system to the codereview app.
18
19Usage summary: upload.py [options] [-- diff_options]
20
21Diff options are passed to the diff command of the underlying system.
22
23Supported version control systems:
24  Git
25  Mercurial
26  Subversion
27
28It is important for Git/Mercurial users to specify a tree/node/branch to diff
29against by using the '--rev' option.
30"""
31# This code is derived from appcfg.py in the App Engine SDK (open source),
32# and from ASPN recipe #146306.
33
34import cookielib
35import getpass
36import logging
37import md5
38import mimetypes
39import optparse
40import os
41import re
42import socket
43import subprocess
44import sys
45import urllib
46import urllib2
47import urlparse
48
49try:
50  import readline
51except ImportError:
52  pass
53
54# The logging verbosity:
55#  0: Errors only.
56#  1: Status messages.
57#  2: Info logs.
58#  3: Debug logs.
59verbosity = 1
60
61# Max size of patch or base file.
62MAX_UPLOAD_SIZE = 900 * 1024
63
64
65def GetEmail(prompt):
66  """Prompts the user for their email address and returns it.
67
68  The last used email address is saved to a file and offered up as a suggestion
69  to the user. If the user presses enter without typing in anything the last
70  used email address is used. If the user enters a new address, it is saved
71  for next time we prompt.
72
73  """
74  last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
75  last_email = ""
76  if os.path.exists(last_email_file_name):
77    try:
78      last_email_file = open(last_email_file_name, "r")
79      last_email = last_email_file.readline().strip("\n")
80      last_email_file.close()
81      prompt += " [%s]" % last_email
82    except IOError, e:
83      pass
84  email = raw_input(prompt + ": ").strip()
85  if email:
86    try:
87      last_email_file = open(last_email_file_name, "w")
88      last_email_file.write(email)
89      last_email_file.close()
90    except IOError, e:
91      pass
92  else:
93    email = last_email
94  return email
95
96
97def StatusUpdate(msg):
98  """Print a status message to stdout.
99
100  If 'verbosity' is greater than 0, print the message.
101
102  Args:
103    msg: The string to print.
104  """
105  if verbosity > 0:
106    print msg
107
108
109def ErrorExit(msg):
110  """Print an error message to stderr and exit."""
111  print >>sys.stderr, msg
112  sys.exit(1)
113
114
115class ClientLoginError(urllib2.HTTPError):
116  """Raised to indicate there was an error authenticating with ClientLogin."""
117
118  def __init__(self, url, code, msg, headers, args):
119    urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
120    self.args = args
121    self.reason = args["Error"]
122
123
124class AbstractRpcServer(object):
125  """Provides a common interface for a simple RPC server."""
126
127  def __init__(self, host, auth_function, host_override=None, extra_headers={},
128               save_cookies=False):
129    """Creates a new HttpRpcServer.
130
131    Args:
132      host: The host to send requests to.
133      auth_function: A function that takes no arguments and returns an
134        (email, password) tuple when called. Will be called if authentication
135        is required.
136      host_override: The host header to send to the server (defaults to host).
137      extra_headers: A dict of extra headers to append to every request.
138      save_cookies: If True, save the authentication cookies to local disk.
139        If False, use an in-memory cookiejar instead.  Subclasses must
140        implement this functionality.  Defaults to False.
141    """
142    self.host = host
143    self.host_override = host_override
144    self.auth_function = auth_function
145    self.authenticated = False
146    self.extra_headers = extra_headers
147    self.save_cookies = save_cookies
148    self.opener = self._GetOpener()
149    if self.host_override:
150      logging.info("Server: %s; Host: %s", self.host, self.host_override)
151    else:
152      logging.info("Server: %s", self.host)
153
154  def _GetOpener(self):
155    """Returns an OpenerDirector for making HTTP requests.
156
157    Returns:
158      A urllib2.OpenerDirector object.
159    """
160    raise NotImplementedError()
161
162  def _CreateRequest(self, url, data=None):
163    """Creates a new urllib request."""
164    logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
165    req = urllib2.Request(url, data=data)
166    if self.host_override:
167      req.add_header("Host", self.host_override)
168    for key, value in self.extra_headers.iteritems():
169      req.add_header(key, value)
170    return req
171
172  def _GetAuthToken(self, email, password):
173    """Uses ClientLogin to authenticate the user, returning an auth token.
174
175    Args:
176      email:    The user's email address
177      password: The user's password
178
179    Raises:
180      ClientLoginError: If there was an error authenticating with ClientLogin.
181      HTTPError: If there was some other form of HTTP error.
182
183    Returns:
184      The authentication token returned by ClientLogin.
185    """
186    account_type = "GOOGLE"
187    if self.host.endswith(".google.com"):
188      # Needed for use inside Google.
189      account_type = "HOSTED"
190    req = self._CreateRequest(
191        url="https://www.google.com/accounts/ClientLogin",
192        data=urllib.urlencode({
193            "Email": email,
194            "Passwd": password,
195            "service": "ah",
196            "source": "rietveld-codereview-upload",
197            "accountType": account_type,
198        }),
199    )
200    try:
201      response = self.opener.open(req)
202      response_body = response.read()
203      response_dict = dict(x.split("=")
204                           for x in response_body.split("\n") if x)
205      return response_dict["Auth"]
206    except urllib2.HTTPError, e:
207      if e.code == 403:
208        body = e.read()
209        response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
210        raise ClientLoginError(req.get_full_url(), e.code, e.msg,
211                               e.headers, response_dict)
212      else:
213        raise
214
215  def _GetAuthCookie(self, auth_token):
216    """Fetches authentication cookies for an authentication token.
217
218    Args:
219      auth_token: The authentication token returned by ClientLogin.
220
221    Raises:
222      HTTPError: If there was an error fetching the authentication cookies.
223    """
224    # This is a dummy value to allow us to identify when we're successful.
225    continue_location = "http://localhost/"
226    args = {"continue": continue_location, "auth": auth_token}
227    req = self._CreateRequest("http://%s/_ah/login?%s" %
228                              (self.host, urllib.urlencode(args)))
229    try:
230      response = self.opener.open(req)
231    except urllib2.HTTPError, e:
232      response = e
233    if (response.code != 302 or
234        response.info()["location"] != continue_location):
235      raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
236                              response.headers, response.fp)
237    self.authenticated = True
238
239  def _Authenticate(self):
240    """Authenticates the user.
241
242    The authentication process works as follows:
243     1) We get a username and password from the user
244     2) We use ClientLogin to obtain an AUTH token for the user
245        (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
246     3) We pass the auth token to /_ah/login on the server to obtain an
247        authentication cookie. If login was successful, it tries to redirect
248        us to the URL we provided.
249
250    If we attempt to access the upload API without first obtaining an
251    authentication cookie, it returns a 401 response and directs us to
252    authenticate ourselves with ClientLogin.
253    """
254    for i in range(3):
255      credentials = self.auth_function()
256      try:
257        auth_token = self._GetAuthToken(credentials[0], credentials[1])
258      except ClientLoginError, e:
259        if e.reason == "BadAuthentication":
260          print >>sys.stderr, "Invalid username or password."
261          continue
262        if e.reason == "CaptchaRequired":
263          print >>sys.stderr, (
264              "Please go to\n"
265              "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
266              "and verify you are a human.  Then try again.")
267          break
268        if e.reason == "NotVerified":
269          print >>sys.stderr, "Account not verified."
270          break
271        if e.reason == "TermsNotAgreed":
272          print >>sys.stderr, "User has not agreed to TOS."
273          break
274        if e.reason == "AccountDeleted":
275          print >>sys.stderr, "The user account has been deleted."
276          break
277        if e.reason == "AccountDisabled":
278          print >>sys.stderr, "The user account has been disabled."
279          break
280        if e.reason == "ServiceDisabled":
281          print >>sys.stderr, ("The user's access to the service has been "
282                               "disabled.")
283          break
284        if e.reason == "ServiceUnavailable":
285          print >>sys.stderr, "The service is not available; try again later."
286          break
287        raise
288      self._GetAuthCookie(auth_token)
289      return
290
291  def Send(self, request_path, payload=None,
292           content_type="application/octet-stream",
293           timeout=None,
294           **kwargs):
295    """Sends an RPC and returns the response.
296
297    Args:
298      request_path: The path to send the request to, eg /api/appversion/create.
299      payload: The body of the request, or None to send an empty request.
300      content_type: The Content-Type header to use.
301      timeout: timeout in seconds; default None i.e. no timeout.
302        (Note: for large requests on OS X, the timeout doesn't work right.)
303      kwargs: Any keyword arguments are converted into query string parameters.
304
305    Returns:
306      The response body, as a string.
307    """
308    # TODO: Don't require authentication.  Let the server say
309    # whether it is necessary.
310    if not self.authenticated:
311      self._Authenticate()
312
313    old_timeout = socket.getdefaulttimeout()
314    socket.setdefaulttimeout(timeout)
315    try:
316      tries = 0
317      while True:
318        tries += 1
319        args = dict(kwargs)
320        url = "http://%s%s" % (self.host, request_path)
321        if args:
322          url += "?" + urllib.urlencode(args)
323        req = self._CreateRequest(url=url, data=payload)
324        req.add_header("Content-Type", content_type)
325        try:
326          f = self.opener.open(req)
327          response = f.read()
328          f.close()
329          return response
330        except urllib2.HTTPError, e:
331          if tries > 3:
332            raise
333          elif e.code == 401:
334            self._Authenticate()
335##           elif e.code >= 500 and e.code < 600:
336##             # Server Error - try again.
337##             continue
338          else:
339            raise
340    finally:
341      socket.setdefaulttimeout(old_timeout)
342
343
344class HttpRpcServer(AbstractRpcServer):
345  """Provides a simplified RPC-style interface for HTTP requests."""
346
347  def _Authenticate(self):
348    """Save the cookie jar after authentication."""
349    super(HttpRpcServer, self)._Authenticate()
350    if self.save_cookies:
351      StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
352      self.cookie_jar.save()
353
354  def _GetOpener(self):
355    """Returns an OpenerDirector that supports cookies and ignores redirects.
356
357    Returns:
358      A urllib2.OpenerDirector object.
359    """
360    opener = urllib2.OpenerDirector()
361    opener.add_handler(urllib2.ProxyHandler())
362    opener.add_handler(urllib2.UnknownHandler())
363    opener.add_handler(urllib2.HTTPHandler())
364    opener.add_handler(urllib2.HTTPDefaultErrorHandler())
365    opener.add_handler(urllib2.HTTPSHandler())
366    opener.add_handler(urllib2.HTTPErrorProcessor())
367    if self.save_cookies:
368      self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
369      self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
370      if os.path.exists(self.cookie_file):
371        try:
372          self.cookie_jar.load()
373          self.authenticated = True
374          StatusUpdate("Loaded authentication cookies from %s" %
375                       self.cookie_file)
376        except (cookielib.LoadError, IOError):
377          # Failed to load cookies - just ignore them.
378          pass
379      else:
380        # Create an empty cookie file with mode 600
381        fd = os.open(self.cookie_file, os.O_CREAT, 0600)
382        os.close(fd)
383      # Always chmod the cookie file
384      os.chmod(self.cookie_file, 0600)
385    else:
386      # Don't save cookies across runs of update.py.
387      self.cookie_jar = cookielib.CookieJar()
388    opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
389    return opener
390
391
392parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
393parser.add_option("-y", "--assume_yes", action="store_true",
394                  dest="assume_yes", default=False,
395                  help="Assume that the answer to yes/no questions is 'yes'.")
396# Logging
397group = parser.add_option_group("Logging options")
398group.add_option("-q", "--quiet", action="store_const", const=0,
399                 dest="verbose", help="Print errors only.")
400group.add_option("-v", "--verbose", action="store_const", const=2,
401                 dest="verbose", default=1,
402                 help="Print info level logs (default).")
403group.add_option("--noisy", action="store_const", const=3,
404                 dest="verbose", help="Print all logs.")
405# Review server
406group = parser.add_option_group("Review server options")
407group.add_option("-s", "--server", action="store", dest="server",
408                 default="codereview.appspot.com",
409                 metavar="SERVER",
410                 help=("The server to upload to. The format is host[:port]. "
411                       "Defaults to 'codereview.appspot.com'."))
412group.add_option("-e", "--email", action="store", dest="email",
413                 metavar="EMAIL", default=None,
414                 help="The username to use. Will prompt if omitted.")
415group.add_option("-H", "--host", action="store", dest="host",
416                 metavar="HOST", default=None,
417                 help="Overrides the Host header sent with all RPCs.")
418group.add_option("--no_cookies", action="store_false",
419                 dest="save_cookies", default=True,
420                 help="Do not save authentication cookies to local disk.")
421# Issue
422group = parser.add_option_group("Issue options")
423group.add_option("-d", "--description", action="store", dest="description",
424                 metavar="DESCRIPTION", default=None,
425                 help="Optional description when creating an issue.")
426group.add_option("-f", "--description_file", action="store",
427                 dest="description_file", metavar="DESCRIPTION_FILE",
428                 default=None,
429                 help="Optional path of a file that contains "
430                      "the description when creating an issue.")
431group.add_option("-r", "--reviewers", action="store", dest="reviewers",
432                 metavar="REVIEWERS", default=None,
433                 help="Add reviewers (comma separated email addresses).")
434group.add_option("--cc", action="store", dest="cc",
435                 metavar="CC", default=None,
436                 help="Add CC (comma separated email addresses).")
437# Upload options
438group = parser.add_option_group("Patch options")
439group.add_option("-m", "--message", action="store", dest="message",
440                 metavar="MESSAGE", default=None,
441                 help="A message to identify the patch. "
442                      "Will prompt if omitted.")
443group.add_option("-i", "--issue", type="int", action="store",
444                 metavar="ISSUE", default=None,
445                 help="Issue number to which to add. Defaults to new issue.")
446group.add_option("--download_base", action="store_true",
447                 dest="download_base", default=False,
448                 help="Base files will be downloaded by the server "
449                 "(side-by-side diffs may not work on files with CRs).")
450group.add_option("--rev", action="store", dest="revision",
451                 metavar="REV", default=None,
452                 help="Branch/tree/revision to diff against (used by DVCS).")
453group.add_option("--send_mail", action="store_true",
454                 dest="send_mail", default=False,
455                 help="Send notification email to reviewers.")
456
457
458def GetRpcServer(options):
459  """Returns an instance of an AbstractRpcServer.
460
461  Returns:
462    A new AbstractRpcServer, on which RPC calls can be made.
463  """
464
465  rpc_server_class = HttpRpcServer
466
467  def GetUserCredentials():
468    """Prompts the user for a username and password."""
469    email = options.email
470    if email is None:
471      email = GetEmail("Email (login for uploading to %s)" % options.server)
472    password = getpass.getpass("Password for %s: " % email)
473    return (email, password)
474
475  # If this is the dev_appserver, use fake authentication.
476  host = (options.host or options.server).lower()
477  if host == "localhost" or host.startswith("localhost:"):
478    email = options.email
479    if email is None:
480      email = "test@example.com"
481      logging.info("Using debug user %s.  Override with --email" % email)
482    server = rpc_server_class(
483        options.server,
484        lambda: (email, "password"),
485        host_override=options.host,
486        extra_headers={"Cookie":
487                       'dev_appserver_login="%s:False"' % email},
488        save_cookies=options.save_cookies)
489    # Don't try to talk to ClientLogin.
490    server.authenticated = True
491    return server
492
493  return rpc_server_class(options.server, GetUserCredentials,
494                          host_override=options.host,
495                          save_cookies=options.save_cookies)
496
497
498def EncodeMultipartFormData(fields, files):
499  """Encode form fields for multipart/form-data.
500
501  Args:
502    fields: A sequence of (name, value) elements for regular form fields.
503    files: A sequence of (name, filename, value) elements for data to be
504           uploaded as files.
505  Returns:
506    (content_type, body) ready for httplib.HTTP instance.
507
508  Source:
509    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
510  """
511  BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
512  CRLF = '\r\n'
513  lines = []
514  for (key, value) in fields:
515    lines.append('--' + BOUNDARY)
516    lines.append('Content-Disposition: form-data; name="%s"' % key)
517    lines.append('')
518    lines.append(value)
519  for (key, filename, value) in files:
520    lines.append('--' + BOUNDARY)
521    lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
522             (key, filename))
523    lines.append('Content-Type: %s' % GetContentType(filename))
524    lines.append('')
525    lines.append(value)
526  lines.append('--' + BOUNDARY + '--')
527  lines.append('')
528  body = CRLF.join(lines)
529  content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
530  return content_type, body
531
532
533def GetContentType(filename):
534  """Helper to guess the content-type from the filename."""
535  return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
536
537
538# Use a shell for subcommands on Windows to get a PATH search.
539use_shell = sys.platform.startswith("win")
540
541def RunShellWithReturnCode(command, print_output=False,
542                           universal_newlines=True):
543  """Executes a command and returns the output from stdout and the return code.
544
545  Args:
546    command: Command to execute.
547    print_output: If True, the output is printed to stdout.
548                  If False, both stdout and stderr are ignored.
549    universal_newlines: Use universal_newlines flag (default: True).
550
551  Returns:
552    Tuple (output, return code)
553  """
554  logging.info("Running %s", command)
555  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
556                       shell=use_shell, universal_newlines=universal_newlines)
557  if print_output:
558    output_array = []
559    while True:
560      line = p.stdout.readline()
561      if not line:
562        break
563      print line.strip("\n")
564      output_array.append(line)
565    output = "".join(output_array)
566  else:
567    output = p.stdout.read()
568  p.wait()
569  errout = p.stderr.read()
570  if print_output and errout:
571    print >>sys.stderr, errout
572  p.stdout.close()
573  p.stderr.close()
574  return output, p.returncode
575
576
577def RunShell(command, silent_ok=False, universal_newlines=True,
578             print_output=False):
579  data, retcode = RunShellWithReturnCode(command, print_output,
580                                         universal_newlines)
581  if retcode:
582    ErrorExit("Got error status from %s:\n%s" % (command, data))
583  if not silent_ok and not data:
584    ErrorExit("No output from %s" % command)
585  return data
586
587
588class VersionControlSystem(object):
589  """Abstract base class providing an interface to the VCS."""
590
591  def __init__(self, options):
592    """Constructor.
593
594    Args:
595      options: Command line options.
596    """
597    self.options = options
598
599  def GenerateDiff(self, args):
600    """Return the current diff as a string.
601
602    Args:
603      args: Extra arguments to pass to the diff command.
604    """
605    raise NotImplementedError(
606        "abstract method -- subclass %s must override" % self.__class__)
607
608  def GetUnknownFiles(self):
609    """Return a list of files unknown to the VCS."""
610    raise NotImplementedError(
611        "abstract method -- subclass %s must override" % self.__class__)
612
613  def CheckForUnknownFiles(self):
614    """Show an "are you sure?" prompt if there are unknown files."""
615    unknown_files = self.GetUnknownFiles()
616    if unknown_files:
617      print "The following files are not added to version control:"
618      for line in unknown_files:
619        print line
620      prompt = "Are you sure to continue?(y/N) "
621      answer = raw_input(prompt).strip()
622      if answer != "y":
623        ErrorExit("User aborted")
624
625  def GetBaseFile(self, filename):
626    """Get the content of the upstream version of a file.
627
628    Returns:
629      A tuple (base_content, new_content, is_binary, status)
630        base_content: The contents of the base file.
631        new_content: For text files, this is empty.  For binary files, this is
632          the contents of the new file, since the diff output won't contain
633          information to reconstruct the current file.
634        is_binary: True iff the file is binary.
635        status: The status of the file.
636    """
637
638    raise NotImplementedError(
639        "abstract method -- subclass %s must override" % self.__class__)
640
641
642  def GetBaseFiles(self, diff):
643    """Helper that calls GetBase file for each file in the patch.
644
645    Returns:
646      A dictionary that maps from filename to GetBaseFile's tuple.  Filenames
647      are retrieved based on lines that start with "Index:" or
648      "Property changes on:".
649    """
650    files = {}
651    for line in diff.splitlines(True):
652      if line.startswith('Index:') or line.startswith('Property changes on:'):
653        unused, filename = line.split(':', 1)
654        # On Windows if a file has property changes its filename uses '\'
655        # instead of '/'.
656        filename = filename.strip().replace('\\', '/')
657        files[filename] = self.GetBaseFile(filename)
658    return files
659
660
661  def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
662                      files):
663    """Uploads the base files (and if necessary, the current ones as well)."""
664
665    def UploadFile(filename, file_id, content, is_binary, status, is_base):
666      """Uploads a file to the server."""
667      file_too_large = False
668      if is_base:
669        type = "base"
670      else:
671        type = "current"
672      if len(content) > MAX_UPLOAD_SIZE:
673        print ("Not uploading the %s file for %s because it's too large." %
674               (type, filename))
675        file_too_large = True
676        content = ""
677      checksum = md5.new(content).hexdigest()
678      if options.verbose > 0 and not file_too_large:
679        print "Uploading %s file for %s" % (type, filename)
680      url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
681      form_fields = [("filename", filename),
682                     ("status", status),
683                     ("checksum", checksum),
684                     ("is_binary", str(is_binary)),
685                     ("is_current", str(not is_base)),
686                    ]
687      if file_too_large:
688        form_fields.append(("file_too_large", "1"))
689      if options.email:
690        form_fields.append(("user", options.email))
691      ctype, body = EncodeMultipartFormData(form_fields,
692                                            [("data", filename, content)])
693      response_body = rpc_server.Send(url, body,
694                                      content_type=ctype)
695      if not response_body.startswith("OK"):
696        StatusUpdate("  --> %s" % response_body)
697        sys.exit(1)
698
699    patches = dict()
700    [patches.setdefault(v, k) for k, v in patch_list]
701    for filename in patches.keys():
702      base_content, new_content, is_binary, status = files[filename]
703      file_id_str = patches.get(filename)
704      if file_id_str.find("nobase") != -1:
705        base_content = None
706        file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
707      file_id = int(file_id_str)
708      if base_content != None:
709        UploadFile(filename, file_id, base_content, is_binary, status, True)
710      if new_content != None:
711        UploadFile(filename, file_id, new_content, is_binary, status, False)
712
713  def IsImage(self, filename):
714    """Returns true if the filename has an image extension."""
715    mimetype =  mimetypes.guess_type(filename)[0]
716    if not mimetype:
717      return False
718    return mimetype.startswith("image/")
719
720
721class SubversionVCS(VersionControlSystem):
722  """Implementation of the VersionControlSystem interface for Subversion."""
723
724  def __init__(self, options):
725    super(SubversionVCS, self).__init__(options)
726    if self.options.revision:
727      match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
728      if not match:
729        ErrorExit("Invalid Subversion revision %s." % self.options.revision)
730      self.rev_start = match.group(1)
731      self.rev_end = match.group(3)
732    else:
733      self.rev_start = self.rev_end = None
734    # Cache output from "svn list -r REVNO dirname".
735    # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
736    self.svnls_cache = {}
737    # SVN base URL is required to fetch files deleted in an older revision.
738    # Result is cached to not guess it over and over again in GetBaseFile().
739    required = self.options.download_base or self.options.revision is not None
740    self.svn_base = self._GuessBase(required)
741
742  def GuessBase(self, required):
743    """Wrapper for _GuessBase."""
744    return self.svn_base
745
746  def _GuessBase(self, required):
747    """Returns the SVN base URL.
748
749    Args:
750      required: If true, exits if the url can't be guessed, otherwise None is
751        returned.
752    """
753    info = RunShell(["svn", "info"])
754    for line in info.splitlines():
755      words = line.split()
756      if len(words) == 2 and words[0] == "URL:":
757        url = words[1]
758        scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
759        username, netloc = urllib.splituser(netloc)
760        if username:
761          logging.info("Removed username from base URL")
762        if netloc.endswith("svn.python.org"):
763          if netloc == "svn.python.org":
764            if path.startswith("/projects/"):
765              path = path[9:]
766          elif netloc != "pythondev@svn.python.org":
767            ErrorExit("Unrecognized Python URL: %s" % url)
768          base = "http://svn.python.org/view/*checkout*%s/" % path
769          logging.info("Guessed Python base = %s", base)
770        elif netloc.endswith("svn.collab.net"):
771          if path.startswith("/repos/"):
772            path = path[6:]
773          base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
774          logging.info("Guessed CollabNet base = %s", base)
775        elif netloc.endswith(".googlecode.com"):
776          path = path + "/"
777          base = urlparse.urlunparse(("http", netloc, path, params,
778                                      query, fragment))
779          logging.info("Guessed Google Code base = %s", base)
780        else:
781          path = path + "/"
782          base = urlparse.urlunparse((scheme, netloc, path, params,
783                                      query, fragment))
784          logging.info("Guessed base = %s", base)
785        return base
786    if required:
787      ErrorExit("Can't find URL in output from svn info")
788    return None
789
790  def GenerateDiff(self, args):
791    cmd = ["svn", "diff"]
792    if self.options.revision:
793      cmd += ["-r", self.options.revision]
794    cmd.extend(args)
795    data = RunShell(cmd)
796    count = 0
797    for line in data.splitlines():
798      if line.startswith("Index:") or line.startswith("Property changes on:"):
799        count += 1
800        logging.info(line)
801    if not count:
802      ErrorExit("No valid patches found in output from svn diff")
803    return data
804
805  def _CollapseKeywords(self, content, keyword_str):
806    """Collapses SVN keywords."""
807    # svn cat translates keywords but svn diff doesn't. As a result of this
808    # behavior patching.PatchChunks() fails with a chunk mismatch error.
809    # This part was originally written by the Review Board development team
810    # who had the same problem (http://reviews.review-board.org/r/276/).
811    # Mapping of keywords to known aliases
812    svn_keywords = {
813      # Standard keywords
814      'Date':                ['Date', 'LastChangedDate'],
815      'Revision':            ['Revision', 'LastChangedRevision', 'Rev'],
816      'Author':              ['Author', 'LastChangedBy'],
817      'HeadURL':             ['HeadURL', 'URL'],
818      'Id':                  ['Id'],
819
820      # Aliases
821      'LastChangedDate':     ['LastChangedDate', 'Date'],
822      'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
823      'LastChangedBy':       ['LastChangedBy', 'Author'],
824      'URL':                 ['URL', 'HeadURL'],
825    }
826
827    def repl(m):
828       if m.group(2):
829         return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
830       return "$%s$" % m.group(1)
831    keywords = [keyword
832                for name in keyword_str.split(" ")
833                for keyword in svn_keywords.get(name, [])]
834    return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
835
836  def GetUnknownFiles(self):
837    status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
838    unknown_files = []
839    for line in status.split("\n"):
840      if line and line[0] == "?":
841        unknown_files.append(line)
842    return unknown_files
843
844  def ReadFile(self, filename):
845    """Returns the contents of a file."""
846    file = open(filename, 'rb')
847    result = ""
848    try:
849      result = file.read()
850    finally:
851      file.close()
852    return result
853
854  def GetStatus(self, filename):
855    """Returns the status of a file."""
856    if not self.options.revision:
857      status = RunShell(["svn", "status", "--ignore-externals", filename])
858      if not status:
859        ErrorExit("svn status returned no output for %s" % filename)
860      status_lines = status.splitlines()
861      # If file is in a cl, the output will begin with
862      # "\n--- Changelist 'cl_name':\n".  See
863      # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
864      if (len(status_lines) == 3 and
865          not status_lines[0] and
866          status_lines[1].startswith("--- Changelist")):
867        status = status_lines[2]
868      else:
869        status = status_lines[0]
870    # If we have a revision to diff against we need to run "svn list"
871    # for the old and the new revision and compare the results to get
872    # the correct status for a file.
873    else:
874      dirname, relfilename = os.path.split(filename)
875      if dirname not in self.svnls_cache:
876        cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
877        out, returncode = RunShellWithReturnCode(cmd)
878        if returncode:
879          ErrorExit("Failed to get status for %s." % filename)
880        old_files = out.splitlines()
881        args = ["svn", "list"]
882        if self.rev_end:
883          args += ["-r", self.rev_end]
884        cmd = args + [dirname or "."]
885        out, returncode = RunShellWithReturnCode(cmd)
886        if returncode:
887          ErrorExit("Failed to run command %s" % cmd)
888        self.svnls_cache[dirname] = (old_files, out.splitlines())
889      old_files, new_files = self.svnls_cache[dirname]
890      if relfilename in old_files and relfilename not in new_files:
891        status = "D   "
892      elif relfilename in old_files and relfilename in new_files:
893        status = "M   "
894      else:
895        status = "A   "
896    return status
897
898  def GetBaseFile(self, filename):
899    status = self.GetStatus(filename)
900    base_content = None
901    new_content = None
902
903    # If a file is copied its status will be "A  +", which signifies
904    # "addition-with-history".  See "svn st" for more information.  We need to
905    # upload the original file or else diff parsing will fail if the file was
906    # edited.
907    if status[0] == "A" and status[3] != "+":
908      # We'll need to upload the new content if we're adding a binary file
909      # since diff's output won't contain it.
910      mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
911                          silent_ok=True)
912      base_content = ""
913      is_binary = mimetype and not mimetype.startswith("text/")
914      if is_binary and self.IsImage(filename):
915        new_content = self.ReadFile(filename)
916    elif (status[0] in ("M", "D", "R") or
917          (status[0] == "A" and status[3] == "+") or  # Copied file.
918          (status[0] == " " and status[1] == "M")):  # Property change.
919      args = []
920      if self.options.revision:
921        url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
922      else:
923        # Don't change filename, it's needed later.
924        url = filename
925        args += ["-r", "BASE"]
926      cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
927      mimetype, returncode = RunShellWithReturnCode(cmd)
928      if returncode:
929        # File does not exist in the requested revision.
930        # Reset mimetype, it contains an error message.
931        mimetype = ""
932      get_base = False
933      is_binary = mimetype and not mimetype.startswith("text/")
934      if status[0] == " ":
935        # Empty base content just to force an upload.
936        base_content = ""
937      elif is_binary:
938        if self.IsImage(filename):
939          get_base = True
940          if status[0] == "M":
941            if not self.rev_end:
942              new_content = self.ReadFile(filename)
943            else:
944              url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
945              new_content = RunShell(["svn", "cat", url],
946                                     universal_newlines=True, silent_ok=True)
947        else:
948          base_content = ""
949      else:
950        get_base = True
951
952      if get_base:
953        if is_binary:
954          universal_newlines = False
955        else:
956          universal_newlines = True
957        if self.rev_start:
958          # "svn cat -r REV delete_file.txt" doesn't work. cat requires
959          # the full URL with "@REV" appended instead of using "-r" option.
960          url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
961          base_content = RunShell(["svn", "cat", url],
962                                  universal_newlines=universal_newlines,
963                                  silent_ok=True)
964        else:
965          base_content = RunShell(["svn", "cat", filename],
966                                  universal_newlines=universal_newlines,
967                                  silent_ok=True)
968        if not is_binary:
969          args = []
970          if self.rev_start:
971            url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
972          else:
973            url = filename
974            args += ["-r", "BASE"]
975          cmd = ["svn"] + args + ["propget", "svn:keywords", url]
976          keywords, returncode = RunShellWithReturnCode(cmd)
977          if keywords and not returncode:
978            base_content = self._CollapseKeywords(base_content, keywords)
979    else:
980      StatusUpdate("svn status returned unexpected output: %s" % status)
981      sys.exit(1)
982    return base_content, new_content, is_binary, status[0:5]
983
984
985class GitVCS(VersionControlSystem):
986  """Implementation of the VersionControlSystem interface for Git."""
987
988  def __init__(self, options):
989    super(GitVCS, self).__init__(options)
990    # Map of filename -> hash of base file.
991    self.base_hashes = {}
992
993  def GenerateDiff(self, extra_args):
994    # This is more complicated than svn's GenerateDiff because we must convert
995    # the diff output to include an svn-style "Index:" line as well as record
996    # the hashes of the base files, so we can upload them along with our diff.
997    if self.options.revision:
998      extra_args = [self.options.revision] + extra_args
999    gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
1000    svndiff = []
1001    filecount = 0
1002    filename = None
1003    for line in gitdiff.splitlines():
1004      match = re.match(r"diff --git a/(.*) b/.*$", line)
1005      if match:
1006        filecount += 1
1007        filename = match.group(1)
1008        svndiff.append("Index: %s\n" % filename)
1009      else:
1010        # The "index" line in a git diff looks like this (long hashes elided):
1011        #   index 82c0d44..b2cee3f 100755
1012        # We want to save the left hash, as that identifies the base file.
1013        match = re.match(r"index (\w+)\.\.", line)
1014        if match:
1015          self.base_hashes[filename] = match.group(1)
1016      svndiff.append(line + "\n")
1017    if not filecount:
1018      ErrorExit("No valid patches found in output from git diff")
1019    return "".join(svndiff)
1020
1021  def GetUnknownFiles(self):
1022    status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
1023                      silent_ok=True)
1024    return status.splitlines()
1025
1026  def GetBaseFile(self, filename):
1027    hash = self.base_hashes[filename]
1028    base_content = None
1029    new_content = None
1030    is_binary = False
1031    if hash == "0" * 40:  # All-zero hash indicates no base file.
1032      status = "A"
1033      base_content = ""
1034    else:
1035      status = "M"
1036      base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
1037      if returncode:
1038        ErrorExit("Got error status from 'git show %s'" % hash)
1039    return (base_content, new_content, is_binary, status)
1040
1041
1042class MercurialVCS(VersionControlSystem):
1043  """Implementation of the VersionControlSystem interface for Mercurial."""
1044
1045  def __init__(self, options, repo_dir):
1046    super(MercurialVCS, self).__init__(options)
1047    # Absolute path to repository (we can be in a subdir)
1048    self.repo_dir = os.path.normpath(repo_dir)
1049    # Compute the subdir
1050    cwd = os.path.normpath(os.getcwd())
1051    assert cwd.startswith(self.repo_dir)
1052    self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
1053    if self.options.revision:
1054      self.base_rev = self.options.revision
1055    else:
1056      self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
1057
1058  def _GetRelPath(self, filename):
1059    """Get relative path of a file according to the current directory,
1060    given its logical path in the repo."""
1061    assert filename.startswith(self.subdir), filename
1062    return filename[len(self.subdir):].lstrip(r"\/")
1063
1064  def GenerateDiff(self, extra_args):
1065    # If no file specified, restrict to the current subdir
1066    extra_args = extra_args or ["."]
1067    cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
1068    data = RunShell(cmd, silent_ok=True)
1069    svndiff = []
1070    filecount = 0
1071    for line in data.splitlines():
1072      m = re.match("diff --git a/(\S+) b/(\S+)", line)
1073      if m:
1074        # Modify line to make it look like as it comes from svn diff.
1075        # With this modification no changes on the server side are required
1076        # to make upload.py work with Mercurial repos.
1077        # NOTE: for proper handling of moved/copied files, we have to use
1078        # the second filename.
1079        filename = m.group(2)
1080        svndiff.append("Index: %s" % filename)
1081        svndiff.append("=" * 67)
1082        filecount += 1
1083        logging.info(line)
1084      else:
1085        svndiff.append(line)
1086    if not filecount:
1087      ErrorExit("No valid patches found in output from hg diff")
1088    return "\n".join(svndiff) + "\n"
1089
1090  def GetUnknownFiles(self):
1091    """Return a list of files unknown to the VCS."""
1092    args = []
1093    status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
1094        silent_ok=True)
1095    unknown_files = []
1096    for line in status.splitlines():
1097      st, fn = line.split(" ", 1)
1098      if st == "?":
1099        unknown_files.append(fn)
1100    return unknown_files
1101
1102  def GetBaseFile(self, filename):
1103    # "hg status" and "hg cat" both take a path relative to the current subdir
1104    # rather than to the repo root, but "hg diff" has given us the full path
1105    # to the repo root.
1106    base_content = ""
1107    new_content = None
1108    is_binary = False
1109    oldrelpath = relpath = self._GetRelPath(filename)
1110    # "hg status -C" returns two lines for moved/copied files, one otherwise
1111    out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
1112    out = out.splitlines()
1113    # HACK: strip error message about missing file/directory if it isn't in
1114    # the working copy
1115    if out[0].startswith('%s: ' % relpath):
1116      out = out[1:]
1117    if len(out) > 1:
1118      # Moved/copied => considered as modified, use old filename to
1119      # retrieve base contents
1120      oldrelpath = out[1].strip()
1121      status = "M"
1122    else:
1123      status, _ = out[0].split(' ', 1)
1124    if status != "A":
1125      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
1126        silent_ok=True)
1127      is_binary = "\0" in base_content  # Mercurial's heuristic
1128    if status != "R":
1129      new_content = open(relpath, "rb").read()
1130      is_binary = is_binary or "\0" in new_content
1131    if is_binary and base_content:
1132      # Fetch again without converting newlines
1133      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
1134        silent_ok=True, universal_newlines=False)
1135    if not is_binary or not self.IsImage(relpath):
1136      new_content = None
1137    return base_content, new_content, is_binary, status
1138
1139
1140# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
1141def SplitPatch(data):
1142  """Splits a patch into separate pieces for each file.
1143
1144  Args:
1145    data: A string containing the output of svn diff.
1146
1147  Returns:
1148    A list of 2-tuple (filename, text) where text is the svn diff output
1149      pertaining to filename.
1150  """
1151  patches = []
1152  filename = None
1153  diff = []
1154  for line in data.splitlines(True):
1155    new_filename = None
1156    if line.startswith('Index:'):
1157      unused, new_filename = line.split(':', 1)
1158      new_filename = new_filename.strip()
1159    elif line.startswith('Property changes on:'):
1160      unused, temp_filename = line.split(':', 1)
1161      # When a file is modified, paths use '/' between directories, however
1162      # when a property is modified '\' is used on Windows.  Make them the same
1163      # otherwise the file shows up twice.
1164      temp_filename = temp_filename.strip().replace('\\', '/')
1165      if temp_filename != filename:
1166        # File has property changes but no modifications, create a new diff.
1167        new_filename = temp_filename
1168    if new_filename:
1169      if filename and diff:
1170        patches.append((filename, ''.join(diff)))
1171      filename = new_filename
1172      diff = [line]
1173      continue
1174    if diff is not None:
1175      diff.append(line)
1176  if filename and diff:
1177    patches.append((filename, ''.join(diff)))
1178  return patches
1179
1180
1181def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
1182  """Uploads a separate patch for each file in the diff output.
1183
1184  Returns a list of [patch_key, filename] for each file.
1185  """
1186  patches = SplitPatch(data)
1187  rv = []
1188  for patch in patches:
1189    if len(patch[1]) > MAX_UPLOAD_SIZE:
1190      print ("Not uploading the patch for " + patch[0] +
1191             " because the file is too large.")
1192      continue
1193    form_fields = [("filename", patch[0])]
1194    if not options.download_base:
1195      form_fields.append(("content_upload", "1"))
1196    files = [("data", "data.diff", patch[1])]
1197    ctype, body = EncodeMultipartFormData(form_fields, files)
1198    url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
1199    print "Uploading patch for " + patch[0]
1200    response_body = rpc_server.Send(url, body, content_type=ctype)
1201    lines = response_body.splitlines()
1202    if not lines or lines[0] != "OK":
1203      StatusUpdate("  --> %s" % response_body)
1204      sys.exit(1)
1205    rv.append([lines[1], patch[0]])
1206  return rv
1207
1208
1209def GuessVCS(options):
1210  """Helper to guess the version control system.
1211
1212  This examines the current directory, guesses which VersionControlSystem
1213  we're using, and returns an instance of the appropriate class.  Exit with an
1214  error if we can't figure it out.
1215
1216  Returns:
1217    A VersionControlSystem instance. Exits if the VCS can't be guessed.
1218  """
1219  # Mercurial has a command to get the base directory of a repository
1220  # Try running it, but don't die if we don't have hg installed.
1221  # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
1222  try:
1223    out, returncode = RunShellWithReturnCode(["hg", "root"])
1224    if returncode == 0:
1225      return MercurialVCS(options, out.strip())
1226  except OSError, (errno, message):
1227    if errno != 2:  # ENOENT -- they don't have hg installed.
1228      raise
1229
1230  # Subversion has a .svn in all working directories.
1231  if os.path.isdir('.svn'):
1232    logging.info("Guessed VCS = Subversion")
1233    return SubversionVCS(options)
1234
1235  # Git has a command to test if you're in a git tree.
1236  # Try running it, but don't die if we don't have git installed.
1237  try:
1238    out, returncode = RunShellWithReturnCode(["git", "rev-parse",
1239                                              "--is-inside-work-tree"])
1240    if returncode == 0:
1241      return GitVCS(options)
1242  except OSError, (errno, message):
1243    if errno != 2:  # ENOENT -- they don't have git installed.
1244      raise
1245
1246  ErrorExit(("Could not guess version control system. "
1247             "Are you in a working copy directory?"))
1248
1249
1250def RealMain(argv, data=None):
1251  """The real main function.
1252
1253  Args:
1254    argv: Command line arguments.
1255    data: Diff contents. If None (default) the diff is generated by
1256      the VersionControlSystem implementation returned by GuessVCS().
1257
1258  Returns:
1259    A 2-tuple (issue id, patchset id).
1260    The patchset id is None if the base files are not uploaded by this
1261    script (applies only to SVN checkouts).
1262  """
1263  logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
1264                              "%(lineno)s %(message)s "))
1265  os.environ['LC_ALL'] = 'C'
1266  options, args = parser.parse_args(argv[1:])
1267  global verbosity
1268  verbosity = options.verbose
1269  if verbosity >= 3:
1270    logging.getLogger().setLevel(logging.DEBUG)
1271  elif verbosity >= 2:
1272    logging.getLogger().setLevel(logging.INFO)
1273  vcs = GuessVCS(options)
1274  if isinstance(vcs, SubversionVCS):
1275    # base field is only allowed for Subversion.
1276    # Note: Fetching base files may become deprecated in future releases.
1277    base = vcs.GuessBase(options.download_base)
1278  else:
1279    base = None
1280  if not base and options.download_base:
1281    options.download_base = True
1282    logging.info("Enabled upload of base file")
1283  if not options.assume_yes:
1284    vcs.CheckForUnknownFiles()
1285  if data is None:
1286    data = vcs.GenerateDiff(args)
1287  files = vcs.GetBaseFiles(data)
1288  if verbosity >= 1:
1289    print "Upload server:", options.server, "(change with -s/--server)"
1290  if options.issue:
1291    prompt = "Message describing this patch set: "
1292  else:
1293    prompt = "New issue subject: "
1294  message = options.message or raw_input(prompt).strip()
1295  if not message:
1296    ErrorExit("A non-empty message is required")
1297  rpc_server = GetRpcServer(options)
1298  form_fields = [("subject", message)]
1299  if base:
1300    form_fields.append(("base", base))
1301  if options.issue:
1302    form_fields.append(("issue", str(options.issue)))
1303  if options.email:
1304    form_fields.append(("user", options.email))
1305  if options.reviewers:
1306    for reviewer in options.reviewers.split(','):
1307      if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
1308        ErrorExit("Invalid email address: %s" % reviewer)
1309    form_fields.append(("reviewers", options.reviewers))
1310  if options.cc:
1311    for cc in options.cc.split(','):
1312      if "@" in cc and not cc.split("@")[1].count(".") == 1:
1313        ErrorExit("Invalid email address: %s" % cc)
1314    form_fields.append(("cc", options.cc))
1315  description = options.description
1316  if options.description_file:
1317    if options.description:
1318      ErrorExit("Can't specify description and description_file")
1319    file = open(options.description_file, 'r')
1320    description = file.read()
1321    file.close()
1322  if description:
1323    form_fields.append(("description", description))
1324  # Send a hash of all the base file so the server can determine if a copy
1325  # already exists in an earlier patchset.
1326  base_hashes = ""
1327  for file, info in files.iteritems():
1328    if not info[0] is None:
1329      checksum = md5.new(info[0]).hexdigest()
1330      if base_hashes:
1331        base_hashes += "|"
1332      base_hashes += checksum + ":" + file
1333  form_fields.append(("base_hashes", base_hashes))
1334  # If we're uploading base files, don't send the email before the uploads, so
1335  # that it contains the file status.
1336  if options.send_mail and options.download_base:
1337    form_fields.append(("send_mail", "1"))
1338  if not options.download_base:
1339    form_fields.append(("content_upload", "1"))
1340  if len(data) > MAX_UPLOAD_SIZE:
1341    print "Patch is large, so uploading file patches separately."
1342    uploaded_diff_file = []
1343    form_fields.append(("separate_patches", "1"))
1344  else:
1345    uploaded_diff_file = [("data", "data.diff", data)]
1346  ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
1347  response_body = rpc_server.Send("/upload", body, content_type=ctype)
1348  patchset = None
1349  if not options.download_base or not uploaded_diff_file:
1350    lines = response_body.splitlines()
1351    if len(lines) >= 2:
1352      msg = lines[0]
1353      patchset = lines[1].strip()
1354      patches = [x.split(" ", 1) for x in lines[2:]]
1355    else:
1356      msg = response_body
1357  else:
1358    msg = response_body
1359  StatusUpdate(msg)
1360  if not response_body.startswith("Issue created.") and \
1361  not response_body.startswith("Issue updated."):
1362    sys.exit(0)
1363  issue = msg[msg.rfind("/")+1:]
1364
1365  if not uploaded_diff_file:
1366    result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
1367    if not options.download_base:
1368      patches = result
1369
1370  if not options.download_base:
1371    vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
1372    if options.send_mail:
1373      rpc_server.Send("/" + issue + "/mail", payload="")
1374  return issue, patchset
1375
1376
1377def main():
1378  try:
1379    RealMain(sys.argv)
1380  except KeyboardInterrupt:
1381    print
1382    StatusUpdate("Interrupted.")
1383    sys.exit(1)
1384
1385
1386if __name__ == "__main__":
1387  main()
trunk/3rdparty/googletest/googlemock/scripts/upload_gmock.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""upload_gmock.py v0.1.0 -- uploads a Google Mock patch for review.
33
34This simple wrapper passes all command line flags and
35--cc=googlemock@googlegroups.com to upload.py.
36
37USAGE: upload_gmock.py [options for upload.py]
38"""
39
40__author__ = 'wan@google.com (Zhanyong Wan)'
41
42import os
43import sys
44
45CC_FLAG = '--cc='
46GMOCK_GROUP = 'googlemock@googlegroups.com'
47
48
49def main():
50  # Finds the path to upload.py, assuming it is in the same directory
51  # as this file.
52  my_dir = os.path.dirname(os.path.abspath(__file__))
53  upload_py_path = os.path.join(my_dir, 'upload.py')
54
55  # Adds Google Mock discussion group to the cc line if it's not there
56  # already.
57  upload_py_argv = [upload_py_path]
58  found_cc_flag = False
59  for arg in sys.argv[1:]:
60    if arg.startswith(CC_FLAG):
61      found_cc_flag = True
62      cc_line = arg[len(CC_FLAG):]
63      cc_list = [addr for addr in cc_line.split(',') if addr]
64      if GMOCK_GROUP not in cc_list:
65        cc_list.append(GMOCK_GROUP)
66      upload_py_argv.append(CC_FLAG + ','.join(cc_list))
67    else:
68      upload_py_argv.append(arg)
69
70  if not found_cc_flag:
71    upload_py_argv.append(CC_FLAG + GMOCK_GROUP)
72
73  # Invokes upload.py with the modified command line flags.
74  os.execv(upload_py_path, upload_py_argv)
75
76
77if __name__ == '__main__':
78  main()
trunk/3rdparty/googletest/googlemock/src/gmock-all.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Google C++ Mocking Framework (Google Mock)
33//
34// This file #includes all Google Mock implementation .cc files.  The
35// purpose is to allow a user to build Google Mock by compiling this
36// file alone.
37
38// This line ensures that gmock.h can be compiled on its own, even
39// when it's fused.
40#include "gmock/gmock.h"
41
42// The following lines pull in the real gmock *.cc files.
43#include "src/gmock-cardinalities.cc"
44#include "src/gmock-internal-utils.cc"
45#include "src/gmock-matchers.cc"
46#include "src/gmock-spec-builders.cc"
47#include "src/gmock.cc"
trunk/3rdparty/googletest/googlemock/src/gmock-cardinalities.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements cardinalities.
35
36#include "gmock/gmock-cardinalities.h"
37
38#include <limits.h>
39#include <ostream>  // NOLINT
40#include <sstream>
41#include <string>
42#include "gmock/internal/gmock-internal-utils.h"
43#include "gtest/gtest.h"
44
45namespace testing {
46
47namespace {
48
49// Implements the Between(m, n) cardinality.
50class BetweenCardinalityImpl : public CardinalityInterface {
51 public:
52  BetweenCardinalityImpl(int min, int max)
53      : min_(min >= 0 ? min : 0),
54        max_(max >= min_ ? max : min_) {
55    std::stringstream ss;
56    if (min < 0) {
57      ss << "The invocation lower bound must be >= 0, "
58         << "but is actually " << min << ".";
59      internal::Expect(false, __FILE__, __LINE__, ss.str());
60    } else if (max < 0) {
61      ss << "The invocation upper bound must be >= 0, "
62         << "but is actually " << max << ".";
63      internal::Expect(false, __FILE__, __LINE__, ss.str());
64    } else if (min > max) {
65      ss << "The invocation upper bound (" << max
66         << ") must be >= the invocation lower bound (" << min
67         << ").";
68      internal::Expect(false, __FILE__, __LINE__, ss.str());
69    }
70  }
71
72  // Conservative estimate on the lower/upper bound of the number of
73  // calls allowed.
74  virtual int ConservativeLowerBound() const { return min_; }
75  virtual int ConservativeUpperBound() const { return max_; }
76
77  virtual bool IsSatisfiedByCallCount(int call_count) const {
78    return min_ <= call_count && call_count <= max_;
79  }
80
81  virtual bool IsSaturatedByCallCount(int call_count) const {
82    return call_count >= max_;
83  }
84
85  virtual void DescribeTo(::std::ostream* os) const;
86
87 private:
88  const int min_;
89  const int max_;
90
91  GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
92};
93
94// Formats "n times" in a human-friendly way.
95inline internal::string FormatTimes(int n) {
96  if (n == 1) {
97    return "once";
98  } else if (n == 2) {
99    return "twice";
100  } else {
101    std::stringstream ss;
102    ss << n << " times";
103    return ss.str();
104  }
105}
106
107// Describes the Between(m, n) cardinality in human-friendly text.
108void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
109  if (min_ == 0) {
110    if (max_ == 0) {
111      *os << "never called";
112    } else if (max_ == INT_MAX) {
113      *os << "called any number of times";
114    } else {
115      *os << "called at most " << FormatTimes(max_);
116    }
117  } else if (min_ == max_) {
118    *os << "called " << FormatTimes(min_);
119  } else if (max_ == INT_MAX) {
120    *os << "called at least " << FormatTimes(min_);
121  } else {
122    // 0 < min_ < max_ < INT_MAX
123    *os << "called between " << min_ << " and " << max_ << " times";
124  }
125}
126
127}  // Unnamed namespace
128
129// Describes the given call count to an ostream.
130void Cardinality::DescribeActualCallCountTo(int actual_call_count,
131                                            ::std::ostream* os) {
132  if (actual_call_count > 0) {
133    *os << "called " << FormatTimes(actual_call_count);
134  } else {
135    *os << "never called";
136  }
137}
138
139// Creates a cardinality that allows at least n calls.
140GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
141
142// Creates a cardinality that allows at most n calls.
143GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
144
145// Creates a cardinality that allows any number of calls.
146GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
147
148// Creates a cardinality that allows between min and max calls.
149GTEST_API_ Cardinality Between(int min, int max) {
150  return Cardinality(new BetweenCardinalityImpl(min, max));
151}
152
153// Creates a cardinality that allows exactly n calls.
154GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
155
156}  // namespace testing
trunk/3rdparty/googletest/googlemock/src/gmock-internal-utils.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file defines some utilities useful for implementing Google
35// Mock.  They are subject to change without notice, so please DO NOT
36// USE THEM IN USER CODE.
37
38#include "gmock/internal/gmock-internal-utils.h"
39
40#include <ctype.h>
41#include <ostream>  // NOLINT
42#include <string>
43#include "gmock/gmock.h"
44#include "gmock/internal/gmock-port.h"
45#include "gtest/gtest.h"
46
47namespace testing {
48namespace internal {
49
50// Converts an identifier name to a space-separated list of lower-case
51// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
52// treated as one word.  For example, both "FooBar123" and
53// "foo_bar_123" are converted to "foo bar 123".
54GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
55  string result;
56  char prev_char = '\0';
57  for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
58    // We don't care about the current locale as the input is
59    // guaranteed to be a valid C++ identifier name.
60    const bool starts_new_word = IsUpper(*p) ||
61        (!IsAlpha(prev_char) && IsLower(*p)) ||
62        (!IsDigit(prev_char) && IsDigit(*p));
63
64    if (IsAlNum(*p)) {
65      if (starts_new_word && result != "")
66        result += ' ';
67      result += ToLower(*p);
68    }
69  }
70  return result;
71}
72
73// This class reports Google Mock failures as Google Test failures.  A
74// user can define another class in a similar fashion if he intends to
75// use Google Mock with a testing framework other than Google Test.
76class GoogleTestFailureReporter : public FailureReporterInterface {
77 public:
78  virtual void ReportFailure(FailureType type, const char* file, int line,
79                             const string& message) {
80    AssertHelper(type == kFatal ?
81                 TestPartResult::kFatalFailure :
82                 TestPartResult::kNonFatalFailure,
83                 file,
84                 line,
85                 message.c_str()) = Message();
86    if (type == kFatal) {
87      posix::Abort();
88    }
89  }
90};
91
92// Returns the global failure reporter.  Will create a
93// GoogleTestFailureReporter and return it the first time called.
94GTEST_API_ FailureReporterInterface* GetFailureReporter() {
95  // Points to the global failure reporter used by Google Mock.  gcc
96  // guarantees that the following use of failure_reporter is
97  // thread-safe.  We may need to add additional synchronization to
98  // protect failure_reporter if we port Google Mock to other
99  // compilers.
100  static FailureReporterInterface* const failure_reporter =
101      new GoogleTestFailureReporter();
102  return failure_reporter;
103}
104
105// Protects global resources (stdout in particular) used by Log().
106static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
107
108// Returns true iff a log with the given severity is visible according
109// to the --gmock_verbose flag.
110GTEST_API_ bool LogIsVisible(LogSeverity severity) {
111  if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
112    // Always show the log if --gmock_verbose=info.
113    return true;
114  } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
115    // Always hide it if --gmock_verbose=error.
116    return false;
117  } else {
118    // If --gmock_verbose is neither "info" nor "error", we treat it
119    // as "warning" (its default value).
120    return severity == kWarning;
121  }
122}
123
124// Prints the given message to stdout iff 'severity' >= the level
125// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
126// 0, also prints the stack trace excluding the top
127// stack_frames_to_skip frames.  In opt mode, any positive
128// stack_frames_to_skip is treated as 0, since we don't know which
129// function calls will be inlined by the compiler and need to be
130// conservative.
131GTEST_API_ void Log(LogSeverity severity,
132                    const string& message,
133                    int stack_frames_to_skip) {
134  if (!LogIsVisible(severity))
135    return;
136
137  // Ensures that logs from different threads don't interleave.
138  MutexLock l(&g_log_mutex);
139
140  // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
141  // macro.
142
143  if (severity == kWarning) {
144    // Prints a GMOCK WARNING marker to make the warnings easily searchable.
145    std::cout << "\nGMOCK WARNING:";
146  }
147  // Pre-pends a new-line to message if it doesn't start with one.
148  if (message.empty() || message[0] != '\n') {
149    std::cout << "\n";
150  }
151  std::cout << message;
152  if (stack_frames_to_skip >= 0) {
153#ifdef NDEBUG
154    // In opt mode, we have to be conservative and skip no stack frame.
155    const int actual_to_skip = 0;
156#else
157    // In dbg mode, we can do what the caller tell us to do (plus one
158    // for skipping this function's stack frame).
159    const int actual_to_skip = stack_frames_to_skip + 1;
160#endif  // NDEBUG
161
162    // Appends a new-line to message if it doesn't end with one.
163    if (!message.empty() && *message.rbegin() != '\n') {
164      std::cout << "\n";
165    }
166    std::cout << "Stack trace:\n"
167         << ::testing::internal::GetCurrentOsStackTraceExceptTop(
168             ::testing::UnitTest::GetInstance(), actual_to_skip);
169  }
170  std::cout << ::std::flush;
171}
172
173}  // namespace internal
174}  // namespace testing
trunk/3rdparty/googletest/googlemock/src/gmock-matchers.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements Matcher<const string&>, Matcher<string>, and
35// utilities for defining matchers.
36
37#include "gmock/gmock-matchers.h"
38#include "gmock/gmock-generated-matchers.h"
39
40#include <string.h>
41#include <sstream>
42#include <string>
43
44namespace testing {
45
46// Constructs a matcher that matches a const string& whose value is
47// equal to s.
48Matcher<const internal::string&>::Matcher(const internal::string& s) {
49  *this = Eq(s);
50}
51
52// Constructs a matcher that matches a const string& whose value is
53// equal to s.
54Matcher<const internal::string&>::Matcher(const char* s) {
55  *this = Eq(internal::string(s));
56}
57
58// Constructs a matcher that matches a string whose value is equal to s.
59Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
60
61// Constructs a matcher that matches a string whose value is equal to s.
62Matcher<internal::string>::Matcher(const char* s) {
63  *this = Eq(internal::string(s));
64}
65
66#if GTEST_HAS_STRING_PIECE_
67// Constructs a matcher that matches a const StringPiece& whose value is
68// equal to s.
69Matcher<const StringPiece&>::Matcher(const internal::string& s) {
70  *this = Eq(s);
71}
72
73// Constructs a matcher that matches a const StringPiece& whose value is
74// equal to s.
75Matcher<const StringPiece&>::Matcher(const char* s) {
76  *this = Eq(internal::string(s));
77}
78
79// Constructs a matcher that matches a const StringPiece& whose value is
80// equal to s.
81Matcher<const StringPiece&>::Matcher(StringPiece s) {
82  *this = Eq(s.ToString());
83}
84
85// Constructs a matcher that matches a StringPiece whose value is equal to s.
86Matcher<StringPiece>::Matcher(const internal::string& s) {
87  *this = Eq(s);
88}
89
90// Constructs a matcher that matches a StringPiece whose value is equal to s.
91Matcher<StringPiece>::Matcher(const char* s) {
92  *this = Eq(internal::string(s));
93}
94
95// Constructs a matcher that matches a StringPiece whose value is equal to s.
96Matcher<StringPiece>::Matcher(StringPiece s) {
97  *this = Eq(s.ToString());
98}
99#endif  // GTEST_HAS_STRING_PIECE_
100
101namespace internal {
102
103// Joins a vector of strings as if they are fields of a tuple; returns
104// the joined string.
105GTEST_API_ string JoinAsTuple(const Strings& fields) {
106  switch (fields.size()) {
107    case 0:
108      return "";
109    case 1:
110      return fields[0];
111    default:
112      string result = "(" + fields[0];
113      for (size_t i = 1; i < fields.size(); i++) {
114        result += ", ";
115        result += fields[i];
116      }
117      result += ")";
118      return result;
119  }
120}
121
122// Returns the description for a matcher defined using the MATCHER*()
123// macro where the user-supplied description string is "", if
124// 'negation' is false; otherwise returns the description of the
125// negation of the matcher.  'param_values' contains a list of strings
126// that are the print-out of the matcher's parameters.
127GTEST_API_ string FormatMatcherDescription(bool negation,
128                                           const char* matcher_name,
129                                           const Strings& param_values) {
130  string result = ConvertIdentifierNameToWords(matcher_name);
131  if (param_values.size() >= 1)
132    result += " " + JoinAsTuple(param_values);
133  return negation ? "not (" + result + ")" : result;
134}
135
136// FindMaxBipartiteMatching and its helper class.
137//
138// Uses the well-known Ford-Fulkerson max flow method to find a maximum
139// bipartite matching. Flow is considered to be from left to right.
140// There is an implicit source node that is connected to all of the left
141// nodes, and an implicit sink node that is connected to all of the
142// right nodes. All edges have unit capacity.
143//
144// Neither the flow graph nor the residual flow graph are represented
145// explicitly. Instead, they are implied by the information in 'graph' and
146// a vector<int> called 'left_' whose elements are initialized to the
147// value kUnused. This represents the initial state of the algorithm,
148// where the flow graph is empty, and the residual flow graph has the
149// following edges:
150//   - An edge from source to each left_ node
151//   - An edge from each right_ node to sink
152//   - An edge from each left_ node to each right_ node, if the
153//     corresponding edge exists in 'graph'.
154//
155// When the TryAugment() method adds a flow, it sets left_[l] = r for some
156// nodes l and r. This induces the following changes:
157//   - The edges (source, l), (l, r), and (r, sink) are added to the
158//     flow graph.
159//   - The same three edges are removed from the residual flow graph.
160//   - The reverse edges (l, source), (r, l), and (sink, r) are added
161//     to the residual flow graph, which is a directional graph
162//     representing unused flow capacity.
163//
164// When the method augments a flow (moving left_[l] from some r1 to some
165// other r2), this can be thought of as "undoing" the above steps with
166// respect to r1 and "redoing" them with respect to r2.
167//
168// It bears repeating that the flow graph and residual flow graph are
169// never represented explicitly, but can be derived by looking at the
170// information in 'graph' and in left_.
171//
172// As an optimization, there is a second vector<int> called right_ which
173// does not provide any new information. Instead, it enables more
174// efficient queries about edges entering or leaving the right-side nodes
175// of the flow or residual flow graphs. The following invariants are
176// maintained:
177//
178// left[l] == kUnused or right[left[l]] == l
179// right[r] == kUnused or left[right[r]] == r
180//
181// . [ source ]                                        .
182// .   |||                                             .
183// .   |||                                             .
184// .   ||\--> left[0]=1  ---\    right[0]=-1 ----\     .
185// .   ||                   |                    |     .
186// .   |\---> left[1]=-1    \--> right[1]=0  ---\|     .
187// .   |                                        ||     .
188// .   \----> left[2]=2  ------> right[2]=2  --\||     .
189// .                                           |||     .
190// .         elements           matchers       vvv     .
191// .                                         [ sink ]  .
192//
193// See Also:
194//   [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
195//       "Introduction to Algorithms (Second ed.)", pp. 651-664.
196//   [2] "Ford-Fulkerson algorithm", Wikipedia,
197//       'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
198class MaxBipartiteMatchState {
199 public:
200  explicit MaxBipartiteMatchState(const MatchMatrix& graph)
201      : graph_(&graph),
202        left_(graph_->LhsSize(), kUnused),
203        right_(graph_->RhsSize(), kUnused) {
204  }
205
206  // Returns the edges of a maximal match, each in the form {left, right}.
207  ElementMatcherPairs Compute() {
208    // 'seen' is used for path finding { 0: unseen, 1: seen }.
209    ::std::vector<char> seen;
210    // Searches the residual flow graph for a path from each left node to
211    // the sink in the residual flow graph, and if one is found, add flow
212    // to the graph. It's okay to search through the left nodes once. The
213    // edge from the implicit source node to each previously-visited left
214    // node will have flow if that left node has any path to the sink
215    // whatsoever. Subsequent augmentations can only add flow to the
216    // network, and cannot take away that previous flow unit from the source.
217    // Since the source-to-left edge can only carry one flow unit (or,
218    // each element can be matched to only one matcher), there is no need
219    // to visit the left nodes more than once looking for augmented paths.
220    // The flow is known to be possible or impossible by looking at the
221    // node once.
222    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
223      // Reset the path-marking vector and try to find a path from
224      // source to sink starting at the left_[ilhs] node.
225      GTEST_CHECK_(left_[ilhs] == kUnused)
226          << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
227      // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
228      seen.assign(graph_->RhsSize(), 0);
229      TryAugment(ilhs, &seen);
230    }
231    ElementMatcherPairs result;
232    for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
233      size_t irhs = left_[ilhs];
234      if (irhs == kUnused) continue;
235      result.push_back(ElementMatcherPair(ilhs, irhs));
236    }
237    return result;
238  }
239
240 private:
241  static const size_t kUnused = static_cast<size_t>(-1);
242
243  // Perform a depth-first search from left node ilhs to the sink.  If a
244  // path is found, flow is added to the network by linking the left and
245  // right vector elements corresponding each segment of the path.
246  // Returns true if a path to sink was found, which means that a unit of
247  // flow was added to the network. The 'seen' vector elements correspond
248  // to right nodes and are marked to eliminate cycles from the search.
249  //
250  // Left nodes will only be explored at most once because they
251  // are accessible from at most one right node in the residual flow
252  // graph.
253  //
254  // Note that left_[ilhs] is the only element of left_ that TryAugment will
255  // potentially transition from kUnused to another value. Any other
256  // left_ element holding kUnused before TryAugment will be holding it
257  // when TryAugment returns.
258  //
259  bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
260    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
261      if ((*seen)[irhs])
262        continue;
263      if (!graph_->HasEdge(ilhs, irhs))
264        continue;
265      // There's an available edge from ilhs to irhs.
266      (*seen)[irhs] = 1;
267      // Next a search is performed to determine whether
268      // this edge is a dead end or leads to the sink.
269      //
270      // right_[irhs] == kUnused means that there is residual flow from
271      // right node irhs to the sink, so we can use that to finish this
272      // flow path and return success.
273      //
274      // Otherwise there is residual flow to some ilhs. We push flow
275      // along that path and call ourselves recursively to see if this
276      // ultimately leads to sink.
277      if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
278        // Add flow from left_[ilhs] to right_[irhs].
279        left_[ilhs] = irhs;
280        right_[irhs] = ilhs;
281        return true;
282      }
283    }
284    return false;
285  }
286
287  const MatchMatrix* graph_;  // not owned
288  // Each element of the left_ vector represents a left hand side node
289  // (i.e. an element) and each element of right_ is a right hand side
290  // node (i.e. a matcher). The values in the left_ vector indicate
291  // outflow from that node to a node on the the right_ side. The values
292  // in the right_ indicate inflow, and specify which left_ node is
293  // feeding that right_ node, if any. For example, left_[3] == 1 means
294  // there's a flow from element #3 to matcher #1. Such a flow would also
295  // be redundantly represented in the right_ vector as right_[1] == 3.
296  // Elements of left_ and right_ are either kUnused or mutually
297  // referent. Mutually referent means that left_[right_[i]] = i and
298  // right_[left_[i]] = i.
299  ::std::vector<size_t> left_;
300  ::std::vector<size_t> right_;
301
302  GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
303};
304
305const size_t MaxBipartiteMatchState::kUnused;
306
307GTEST_API_ ElementMatcherPairs
308FindMaxBipartiteMatching(const MatchMatrix& g) {
309  return MaxBipartiteMatchState(g).Compute();
310}
311
312static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
313                                     ::std::ostream* stream) {
314  typedef ElementMatcherPairs::const_iterator Iter;
315  ::std::ostream& os = *stream;
316  os << "{";
317  const char *sep = "";
318  for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
319    os << sep << "\n  ("
320       << "element #" << it->first << ", "
321       << "matcher #" << it->second << ")";
322    sep = ",";
323  }
324  os << "\n}";
325}
326
327// Tries to find a pairing, and explains the result.
328GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
329                            MatchResultListener* listener) {
330  ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
331
332  size_t max_flow = matches.size();
333  bool result = (max_flow == matrix.RhsSize());
334
335  if (!result) {
336    if (listener->IsInterested()) {
337      *listener << "where no permutation of the elements can "
338                   "satisfy all matchers, and the closest match is "
339                << max_flow << " of " << matrix.RhsSize()
340                << " matchers with the pairings:\n";
341      LogElementMatcherPairVec(matches, listener->stream());
342    }
343    return false;
344  }
345
346  if (matches.size() > 1) {
347    if (listener->IsInterested()) {
348      const char *sep = "where:\n";
349      for (size_t mi = 0; mi < matches.size(); ++mi) {
350        *listener << sep << " - element #" << matches[mi].first
351                  << " is matched by matcher #" << matches[mi].second;
352        sep = ",\n";
353      }
354    }
355  }
356  return true;
357}
358
359bool MatchMatrix::NextGraph() {
360  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
361    for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
362      char& b = matched_[SpaceIndex(ilhs, irhs)];
363      if (!b) {
364        b = 1;
365        return true;
366      }
367      b = 0;
368    }
369  }
370  return false;
371}
372
373void MatchMatrix::Randomize() {
374  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
375    for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
376      char& b = matched_[SpaceIndex(ilhs, irhs)];
377      b = static_cast<char>(rand() & 1);  // NOLINT
378    }
379  }
380}
381
382string MatchMatrix::DebugString() const {
383  ::std::stringstream ss;
384  const char *sep = "";
385  for (size_t i = 0; i < LhsSize(); ++i) {
386    ss << sep;
387    for (size_t j = 0; j < RhsSize(); ++j) {
388      ss << HasEdge(i, j);
389    }
390    sep = ";";
391  }
392  return ss.str();
393}
394
395void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
396    ::std::ostream* os) const {
397  if (matcher_describers_.empty()) {
398    *os << "is empty";
399    return;
400  }
401  if (matcher_describers_.size() == 1) {
402    *os << "has " << Elements(1) << " and that element ";
403    matcher_describers_[0]->DescribeTo(os);
404    return;
405  }
406  *os << "has " << Elements(matcher_describers_.size())
407      << " and there exists some permutation of elements such that:\n";
408  const char* sep = "";
409  for (size_t i = 0; i != matcher_describers_.size(); ++i) {
410    *os << sep << " - element #" << i << " ";
411    matcher_describers_[i]->DescribeTo(os);
412    sep = ", and\n";
413  }
414}
415
416void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
417    ::std::ostream* os) const {
418  if (matcher_describers_.empty()) {
419    *os << "isn't empty";
420    return;
421  }
422  if (matcher_describers_.size() == 1) {
423    *os << "doesn't have " << Elements(1)
424        << ", or has " << Elements(1) << " that ";
425    matcher_describers_[0]->DescribeNegationTo(os);
426    return;
427  }
428  *os << "doesn't have " << Elements(matcher_describers_.size())
429      << ", or there exists no permutation of elements such that:\n";
430  const char* sep = "";
431  for (size_t i = 0; i != matcher_describers_.size(); ++i) {
432    *os << sep << " - element #" << i << " ";
433    matcher_describers_[i]->DescribeTo(os);
434    sep = ", and\n";
435  }
436}
437
438// Checks that all matchers match at least one element, and that all
439// elements match at least one matcher. This enables faster matching
440// and better error reporting.
441// Returns false, writing an explanation to 'listener', if and only
442// if the success criteria are not met.
443bool UnorderedElementsAreMatcherImplBase::
444VerifyAllElementsAndMatchersAreMatched(
445    const ::std::vector<string>& element_printouts,
446    const MatchMatrix& matrix,
447    MatchResultListener* listener) const {
448  bool result = true;
449  ::std::vector<char> element_matched(matrix.LhsSize(), 0);
450  ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
451
452  for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
453    for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
454      char matched = matrix.HasEdge(ilhs, irhs);
455      element_matched[ilhs] |= matched;
456      matcher_matched[irhs] |= matched;
457    }
458  }
459
460  {
461    const char* sep =
462        "where the following matchers don't match any elements:\n";
463    for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
464      if (matcher_matched[mi])
465        continue;
466      result = false;
467      if (listener->IsInterested()) {
468        *listener << sep << "matcher #" << mi << ": ";
469        matcher_describers_[mi]->DescribeTo(listener->stream());
470        sep = ",\n";
471      }
472    }
473  }
474
475  {
476    const char* sep =
477        "where the following elements don't match any matchers:\n";
478    const char* outer_sep = "";
479    if (!result) {
480      outer_sep = "\nand ";
481    }
482    for (size_t ei = 0; ei < element_matched.size(); ++ei) {
483      if (element_matched[ei])
484        continue;
485      result = false;
486      if (listener->IsInterested()) {
487        *listener << outer_sep << sep << "element #" << ei << ": "
488                  << element_printouts[ei];
489        sep = ",\n";
490        outer_sep = "";
491      }
492    }
493  }
494  return result;
495}
496
497}  // namespace internal
498}  // namespace testing
trunk/3rdparty/googletest/googlemock/src/gmock-spec-builders.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements the spec builder syntax (ON_CALL and
35// EXPECT_CALL).
36
37#include "gmock/gmock-spec-builders.h"
38
39#include <stdlib.h>
40#include <iostream>  // NOLINT
41#include <map>
42#include <set>
43#include <string>
44#include "gmock/gmock.h"
45#include "gtest/gtest.h"
46
47#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
48# include <unistd.h>  // NOLINT
49#endif
50
51namespace testing {
52namespace internal {
53
54// Protects the mock object registry (in class Mock), all function
55// mockers, and all expectations.
56GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
57
58// Logs a message including file and line number information.
59GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
60                                const char* file, int line,
61                                const string& message) {
62  ::std::ostringstream s;
63  s << file << ":" << line << ": " << message << ::std::endl;
64  Log(severity, s.str(), 0);
65}
66
67// Constructs an ExpectationBase object.
68ExpectationBase::ExpectationBase(const char* a_file,
69                                 int a_line,
70                                 const string& a_source_text)
71    : file_(a_file),
72      line_(a_line),
73      source_text_(a_source_text),
74      cardinality_specified_(false),
75      cardinality_(Exactly(1)),
76      call_count_(0),
77      retired_(false),
78      extra_matcher_specified_(false),
79      repeated_action_specified_(false),
80      retires_on_saturation_(false),
81      last_clause_(kNone),
82      action_count_checked_(false) {}
83
84// Destructs an ExpectationBase object.
85ExpectationBase::~ExpectationBase() {}
86
87// Explicitly specifies the cardinality of this expectation.  Used by
88// the subclasses to implement the .Times() clause.
89void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
90  cardinality_specified_ = true;
91  cardinality_ = a_cardinality;
92}
93
94// Retires all pre-requisites of this expectation.
95void ExpectationBase::RetireAllPreRequisites()
96    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
97  if (is_retired()) {
98    // We can take this short-cut as we never retire an expectation
99    // until we have retired all its pre-requisites.
100    return;
101  }
102
103  for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
104       it != immediate_prerequisites_.end(); ++it) {
105    ExpectationBase* const prerequisite = it->expectation_base().get();
106    if (!prerequisite->is_retired()) {
107      prerequisite->RetireAllPreRequisites();
108      prerequisite->Retire();
109    }
110  }
111}
112
113// Returns true iff all pre-requisites of this expectation have been
114// satisfied.
115bool ExpectationBase::AllPrerequisitesAreSatisfied() const
116    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
117  g_gmock_mutex.AssertHeld();
118  for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
119       it != immediate_prerequisites_.end(); ++it) {
120    if (!(it->expectation_base()->IsSatisfied()) ||
121        !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
122      return false;
123  }
124  return true;
125}
126
127// Adds unsatisfied pre-requisites of this expectation to 'result'.
128void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
129    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
130  g_gmock_mutex.AssertHeld();
131  for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
132       it != immediate_prerequisites_.end(); ++it) {
133    if (it->expectation_base()->IsSatisfied()) {
134      // If *it is satisfied and has a call count of 0, some of its
135      // pre-requisites may not be satisfied yet.
136      if (it->expectation_base()->call_count_ == 0) {
137        it->expectation_base()->FindUnsatisfiedPrerequisites(result);
138      }
139    } else {
140      // Now that we know *it is unsatisfied, we are not so interested
141      // in whether its pre-requisites are satisfied.  Therefore we
142      // don't recursively call FindUnsatisfiedPrerequisites() here.
143      *result += *it;
144    }
145  }
146}
147
148// Describes how many times a function call matching this
149// expectation has occurred.
150void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
151    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
152  g_gmock_mutex.AssertHeld();
153
154  // Describes how many times the function is expected to be called.
155  *os << "         Expected: to be ";
156  cardinality().DescribeTo(os);
157  *os << "\n           Actual: ";
158  Cardinality::DescribeActualCallCountTo(call_count(), os);
159
160  // Describes the state of the expectation (e.g. is it satisfied?
161  // is it active?).
162  *os << " - " << (IsOverSaturated() ? "over-saturated" :
163                   IsSaturated() ? "saturated" :
164                   IsSatisfied() ? "satisfied" : "unsatisfied")
165      << " and "
166      << (is_retired() ? "retired" : "active");
167}
168
169// Checks the action count (i.e. the number of WillOnce() and
170// WillRepeatedly() clauses) against the cardinality if this hasn't
171// been done before.  Prints a warning if there are too many or too
172// few actions.
173void ExpectationBase::CheckActionCountIfNotDone() const
174    GTEST_LOCK_EXCLUDED_(mutex_) {
175  bool should_check = false;
176  {
177    MutexLock l(&mutex_);
178    if (!action_count_checked_) {
179      action_count_checked_ = true;
180      should_check = true;
181    }
182  }
183
184  if (should_check) {
185    if (!cardinality_specified_) {
186      // The cardinality was inferred - no need to check the action
187      // count against it.
188      return;
189    }
190
191    // The cardinality was explicitly specified.
192    const int action_count = static_cast<int>(untyped_actions_.size());
193    const int upper_bound = cardinality().ConservativeUpperBound();
194    const int lower_bound = cardinality().ConservativeLowerBound();
195    bool too_many;  // True if there are too many actions, or false
196    // if there are too few.
197    if (action_count > upper_bound ||
198        (action_count == upper_bound && repeated_action_specified_)) {
199      too_many = true;
200    } else if (0 < action_count && action_count < lower_bound &&
201               !repeated_action_specified_) {
202      too_many = false;
203    } else {
204      return;
205    }
206
207    ::std::stringstream ss;
208    DescribeLocationTo(&ss);
209    ss << "Too " << (too_many ? "many" : "few")
210       << " actions specified in " << source_text() << "...\n"
211       << "Expected to be ";
212    cardinality().DescribeTo(&ss);
213    ss << ", but has " << (too_many ? "" : "only ")
214       << action_count << " WillOnce()"
215       << (action_count == 1 ? "" : "s");
216    if (repeated_action_specified_) {
217      ss << " and a WillRepeatedly()";
218    }
219    ss << ".";
220    Log(kWarning, ss.str(), -1);  // -1 means "don't print stack trace".
221  }
222}
223
224// Implements the .Times() clause.
225void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
226  if (last_clause_ == kTimes) {
227    ExpectSpecProperty(false,
228                       ".Times() cannot appear "
229                       "more than once in an EXPECT_CALL().");
230  } else {
231    ExpectSpecProperty(last_clause_ < kTimes,
232                       ".Times() cannot appear after "
233                       ".InSequence(), .WillOnce(), .WillRepeatedly(), "
234                       "or .RetiresOnSaturation().");
235  }
236  last_clause_ = kTimes;
237
238  SpecifyCardinality(a_cardinality);
239}
240
241// Points to the implicit sequence introduced by a living InSequence
242// object (if any) in the current thread or NULL.
243GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
244
245// Reports an uninteresting call (whose description is in msg) in the
246// manner specified by 'reaction'.
247void ReportUninterestingCall(CallReaction reaction, const string& msg) {
248  // Include a stack trace only if --gmock_verbose=info is specified.
249  const int stack_frames_to_skip =
250      GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
251  switch (reaction) {
252    case kAllow:
253      Log(kInfo, msg, stack_frames_to_skip);
254      break;
255    case kWarn:
256      Log(kWarning,
257          msg +
258          "\nNOTE: You can safely ignore the above warning unless this "
259          "call should not happen.  Do not suppress it by blindly adding "
260          "an EXPECT_CALL() if you don't mean to enforce the call.  "
261          "See http://code.google.com/p/googlemock/wiki/CookBook#"
262          "Knowing_When_to_Expect for details.\n",
263          stack_frames_to_skip);
264      break;
265    default:  // FAIL
266      Expect(false, NULL, -1, msg);
267  }
268}
269
270UntypedFunctionMockerBase::UntypedFunctionMockerBase()
271    : mock_obj_(NULL), name_("") {}
272
273UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
274
275// Sets the mock object this mock method belongs to, and registers
276// this information in the global mock registry.  Will be called
277// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
278// method.
279void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
280    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
281  {
282    MutexLock l(&g_gmock_mutex);
283    mock_obj_ = mock_obj;
284  }
285  Mock::Register(mock_obj, this);
286}
287
288// Sets the mock object this mock method belongs to, and sets the name
289// of the mock function.  Will be called upon each invocation of this
290// mock function.
291void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
292                                                const char* name)
293    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
294  // We protect name_ under g_gmock_mutex in case this mock function
295  // is called from two threads concurrently.
296  MutexLock l(&g_gmock_mutex);
297  mock_obj_ = mock_obj;
298  name_ = name;
299}
300
301// Returns the name of the function being mocked.  Must be called
302// after RegisterOwner() or SetOwnerAndName() has been called.
303const void* UntypedFunctionMockerBase::MockObject() const
304    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
305  const void* mock_obj;
306  {
307    // We protect mock_obj_ under g_gmock_mutex in case this mock
308    // function is called from two threads concurrently.
309    MutexLock l(&g_gmock_mutex);
310    Assert(mock_obj_ != NULL, __FILE__, __LINE__,
311           "MockObject() must not be called before RegisterOwner() or "
312           "SetOwnerAndName() has been called.");
313    mock_obj = mock_obj_;
314  }
315  return mock_obj;
316}
317
318// Returns the name of this mock method.  Must be called after
319// SetOwnerAndName() has been called.
320const char* UntypedFunctionMockerBase::Name() const
321    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
322  const char* name;
323  {
324    // We protect name_ under g_gmock_mutex in case this mock
325    // function is called from two threads concurrently.
326    MutexLock l(&g_gmock_mutex);
327    Assert(name_ != NULL, __FILE__, __LINE__,
328           "Name() must not be called before SetOwnerAndName() has "
329           "been called.");
330    name = name_;
331  }
332  return name;
333}
334
335// Calculates the result of invoking this mock function with the given
336// arguments, prints it, and returns it.  The caller is responsible
337// for deleting the result.
338UntypedActionResultHolderBase*
339UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
340    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
341  if (untyped_expectations_.size() == 0) {
342    // No expectation is set on this mock method - we have an
343    // uninteresting call.
344
345    // We must get Google Mock's reaction on uninteresting calls
346    // made on this mock object BEFORE performing the action,
347    // because the action may DELETE the mock object and make the
348    // following expression meaningless.
349    const CallReaction reaction =
350        Mock::GetReactionOnUninterestingCalls(MockObject());
351
352    // True iff we need to print this call's arguments and return
353    // value.  This definition must be kept in sync with
354    // the behavior of ReportUninterestingCall().
355    const bool need_to_report_uninteresting_call =
356        // If the user allows this uninteresting call, we print it
357        // only when he wants informational messages.
358        reaction == kAllow ? LogIsVisible(kInfo) :
359        // If the user wants this to be a warning, we print it only
360        // when he wants to see warnings.
361        reaction == kWarn ? LogIsVisible(kWarning) :
362        // Otherwise, the user wants this to be an error, and we
363        // should always print detailed information in the error.
364        true;
365
366    if (!need_to_report_uninteresting_call) {
367      // Perform the action without printing the call information.
368      return this->UntypedPerformDefaultAction(untyped_args, "");
369    }
370
371    // Warns about the uninteresting call.
372    ::std::stringstream ss;
373    this->UntypedDescribeUninterestingCall(untyped_args, &ss);
374
375    // Calculates the function result.
376    UntypedActionResultHolderBase* const result =
377        this->UntypedPerformDefaultAction(untyped_args, ss.str());
378
379    // Prints the function result.
380    if (result != NULL)
381      result->PrintAsActionResult(&ss);
382
383    ReportUninterestingCall(reaction, ss.str());
384    return result;
385  }
386
387  bool is_excessive = false;
388  ::std::stringstream ss;
389  ::std::stringstream why;
390  ::std::stringstream loc;
391  const void* untyped_action = NULL;
392
393  // The UntypedFindMatchingExpectation() function acquires and
394  // releases g_gmock_mutex.
395  const ExpectationBase* const untyped_expectation =
396      this->UntypedFindMatchingExpectation(
397          untyped_args, &untyped_action, &is_excessive,
398          &ss, &why);
399  const bool found = untyped_expectation != NULL;
400
401  // True iff we need to print the call's arguments and return value.
402  // This definition must be kept in sync with the uses of Expect()
403  // and Log() in this function.
404  const bool need_to_report_call =
405      !found || is_excessive || LogIsVisible(kInfo);
406  if (!need_to_report_call) {
407    // Perform the action without printing the call information.
408    return
409        untyped_action == NULL ?
410        this->UntypedPerformDefaultAction(untyped_args, "") :
411        this->UntypedPerformAction(untyped_action, untyped_args);
412  }
413
414  ss << "    Function call: " << Name();
415  this->UntypedPrintArgs(untyped_args, &ss);
416
417  // In case the action deletes a piece of the expectation, we
418  // generate the message beforehand.
419  if (found && !is_excessive) {
420    untyped_expectation->DescribeLocationTo(&loc);
421  }
422
423  UntypedActionResultHolderBase* const result =
424      untyped_action == NULL ?
425      this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
426      this->UntypedPerformAction(untyped_action, untyped_args);
427  if (result != NULL)
428    result->PrintAsActionResult(&ss);
429  ss << "\n" << why.str();
430
431  if (!found) {
432    // No expectation matches this call - reports a failure.
433    Expect(false, NULL, -1, ss.str());
434  } else if (is_excessive) {
435    // We had an upper-bound violation and the failure message is in ss.
436    Expect(false, untyped_expectation->file(),
437           untyped_expectation->line(), ss.str());
438  } else {
439    // We had an expected call and the matching expectation is
440    // described in ss.
441    Log(kInfo, loc.str() + ss.str(), 2);
442  }
443
444  return result;
445}
446
447// Returns an Expectation object that references and co-owns exp,
448// which must be an expectation on this mock function.
449Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
450  for (UntypedExpectations::const_iterator it =
451           untyped_expectations_.begin();
452       it != untyped_expectations_.end(); ++it) {
453    if (it->get() == exp) {
454      return Expectation(*it);
455    }
456  }
457
458  Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
459  return Expectation();
460  // The above statement is just to make the code compile, and will
461  // never be executed.
462}
463
464// Verifies that all expectations on this mock function have been
465// satisfied.  Reports one or more Google Test non-fatal failures
466// and returns false if not.
467bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
468    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
469  g_gmock_mutex.AssertHeld();
470  bool expectations_met = true;
471  for (UntypedExpectations::const_iterator it =
472           untyped_expectations_.begin();
473       it != untyped_expectations_.end(); ++it) {
474    ExpectationBase* const untyped_expectation = it->get();
475    if (untyped_expectation->IsOverSaturated()) {
476      // There was an upper-bound violation.  Since the error was
477      // already reported when it occurred, there is no need to do
478      // anything here.
479      expectations_met = false;
480    } else if (!untyped_expectation->IsSatisfied()) {
481      expectations_met = false;
482      ::std::stringstream ss;
483      ss  << "Actual function call count doesn't match "
484          << untyped_expectation->source_text() << "...\n";
485      // No need to show the source file location of the expectation
486      // in the description, as the Expect() call that follows already
487      // takes care of it.
488      untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
489      untyped_expectation->DescribeCallCountTo(&ss);
490      Expect(false, untyped_expectation->file(),
491             untyped_expectation->line(), ss.str());
492    }
493  }
494
495  // Deleting our expectations may trigger other mock objects to be deleted, for
496  // example if an action contains a reference counted smart pointer to that
497  // mock object, and that is the last reference. So if we delete our
498  // expectations within the context of the global mutex we may deadlock when
499  // this method is called again. Instead, make a copy of the set of
500  // expectations to delete, clear our set within the mutex, and then clear the
501  // copied set outside of it.
502  UntypedExpectations expectations_to_delete;
503  untyped_expectations_.swap(expectations_to_delete);
504
505  g_gmock_mutex.Unlock();
506  expectations_to_delete.clear();
507  g_gmock_mutex.Lock();
508
509  return expectations_met;
510}
511
512}  // namespace internal
513
514// Class Mock.
515
516namespace {
517
518typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
519
520// The current state of a mock object.  Such information is needed for
521// detecting leaked mock objects and explicitly verifying a mock's
522// expectations.
523struct MockObjectState {
524  MockObjectState()
525      : first_used_file(NULL), first_used_line(-1), leakable(false) {}
526
527  // Where in the source file an ON_CALL or EXPECT_CALL is first
528  // invoked on this mock object.
529  const char* first_used_file;
530  int first_used_line;
531  ::std::string first_used_test_case;
532  ::std::string first_used_test;
533  bool leakable;  // true iff it's OK to leak the object.
534  FunctionMockers function_mockers;  // All registered methods of the object.
535};
536
537// A global registry holding the state of all mock objects that are
538// alive.  A mock object is added to this registry the first time
539// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It
540// is removed from the registry in the mock object's destructor.
541class MockObjectRegistry {
542 public:
543  // Maps a mock object (identified by its address) to its state.
544  typedef std::map<const void*, MockObjectState> StateMap;
545
546  // This destructor will be called when a program exits, after all
547  // tests in it have been run.  By then, there should be no mock
548  // object alive.  Therefore we report any living object as test
549  // failure, unless the user explicitly asked us to ignore it.
550  ~MockObjectRegistry() {
551    // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
552    // a macro.
553
554    if (!GMOCK_FLAG(catch_leaked_mocks))
555      return;
556
557    int leaked_count = 0;
558    for (StateMap::const_iterator it = states_.begin(); it != states_.end();
559         ++it) {
560      if (it->second.leakable)  // The user said it's fine to leak this object.
561        continue;
562
563      // TODO(wan@google.com): Print the type of the leaked object.
564      // This can help the user identify the leaked object.
565      std::cout << "\n";
566      const MockObjectState& state = it->second;
567      std::cout << internal::FormatFileLocation(state.first_used_file,
568                                                state.first_used_line);
569      std::cout << " ERROR: this mock object";
570      if (state.first_used_test != "") {
571        std::cout << " (used in test " << state.first_used_test_case << "."
572             << state.first_used_test << ")";
573      }
574      std::cout << " should be deleted but never is. Its address is @"
575           << it->first << ".";
576      leaked_count++;
577    }
578    if (leaked_count > 0) {
579      std::cout << "\nERROR: " << leaked_count
580           << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
581           << " found at program exit.\n";
582      std::cout.flush();
583      ::std::cerr.flush();
584      // RUN_ALL_TESTS() has already returned when this destructor is
585      // called.  Therefore we cannot use the normal Google Test
586      // failure reporting mechanism.
587      _exit(1);  // We cannot call exit() as it is not reentrant and
588                 // may already have been called.
589    }
590  }
591
592  StateMap& states() { return states_; }
593
594 private:
595  StateMap states_;
596};
597
598// Protected by g_gmock_mutex.
599MockObjectRegistry g_mock_object_registry;
600
601// Maps a mock object to the reaction Google Mock should have when an
602// uninteresting method is called.  Protected by g_gmock_mutex.
603std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
604
605// Sets the reaction Google Mock should have when an uninteresting
606// method of the given mock object is called.
607void SetReactionOnUninterestingCalls(const void* mock_obj,
608                                     internal::CallReaction reaction)
609    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
610  internal::MutexLock l(&internal::g_gmock_mutex);
611  g_uninteresting_call_reaction[mock_obj] = reaction;
612}
613
614}  // namespace
615
616// Tells Google Mock to allow uninteresting calls on the given mock
617// object.
618void Mock::AllowUninterestingCalls(const void* mock_obj)
619    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
620  SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
621}
622
623// Tells Google Mock to warn the user about uninteresting calls on the
624// given mock object.
625void Mock::WarnUninterestingCalls(const void* mock_obj)
626    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
627  SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
628}
629
630// Tells Google Mock to fail uninteresting calls on the given mock
631// object.
632void Mock::FailUninterestingCalls(const void* mock_obj)
633    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
634  SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
635}
636
637// Tells Google Mock the given mock object is being destroyed and its
638// entry in the call-reaction table should be removed.
639void Mock::UnregisterCallReaction(const void* mock_obj)
640    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
641  internal::MutexLock l(&internal::g_gmock_mutex);
642  g_uninteresting_call_reaction.erase(mock_obj);
643}
644
645// Returns the reaction Google Mock will have on uninteresting calls
646// made on the given mock object.
647internal::CallReaction Mock::GetReactionOnUninterestingCalls(
648    const void* mock_obj)
649        GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
650  internal::MutexLock l(&internal::g_gmock_mutex);
651  return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
652      internal::kDefault : g_uninteresting_call_reaction[mock_obj];
653}
654
655// Tells Google Mock to ignore mock_obj when checking for leaked mock
656// objects.
657void Mock::AllowLeak(const void* mock_obj)
658    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
659  internal::MutexLock l(&internal::g_gmock_mutex);
660  g_mock_object_registry.states()[mock_obj].leakable = true;
661}
662
663// Verifies and clears all expectations on the given mock object.  If
664// the expectations aren't satisfied, generates one or more Google
665// Test non-fatal failures and returns false.
666bool Mock::VerifyAndClearExpectations(void* mock_obj)
667    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
668  internal::MutexLock l(&internal::g_gmock_mutex);
669  return VerifyAndClearExpectationsLocked(mock_obj);
670}
671
672// Verifies all expectations on the given mock object and clears its
673// default actions and expectations.  Returns true iff the
674// verification was successful.
675bool Mock::VerifyAndClear(void* mock_obj)
676    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
677  internal::MutexLock l(&internal::g_gmock_mutex);
678  ClearDefaultActionsLocked(mock_obj);
679  return VerifyAndClearExpectationsLocked(mock_obj);
680}
681
682// Verifies and clears all expectations on the given mock object.  If
683// the expectations aren't satisfied, generates one or more Google
684// Test non-fatal failures and returns false.
685bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
686    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
687  internal::g_gmock_mutex.AssertHeld();
688  if (g_mock_object_registry.states().count(mock_obj) == 0) {
689    // No EXPECT_CALL() was set on the given mock object.
690    return true;
691  }
692
693  // Verifies and clears the expectations on each mock method in the
694  // given mock object.
695  bool expectations_met = true;
696  FunctionMockers& mockers =
697      g_mock_object_registry.states()[mock_obj].function_mockers;
698  for (FunctionMockers::const_iterator it = mockers.begin();
699       it != mockers.end(); ++it) {
700    if (!(*it)->VerifyAndClearExpectationsLocked()) {
701      expectations_met = false;
702    }
703  }
704
705  // We don't clear the content of mockers, as they may still be
706  // needed by ClearDefaultActionsLocked().
707  return expectations_met;
708}
709
710// Registers a mock object and a mock method it owns.
711void Mock::Register(const void* mock_obj,
712                    internal::UntypedFunctionMockerBase* mocker)
713    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
714  internal::MutexLock l(&internal::g_gmock_mutex);
715  g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
716}
717
718// Tells Google Mock where in the source code mock_obj is used in an
719// ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
720// information helps the user identify which object it is.
721void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
722                                           const char* file, int line)
723    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
724  internal::MutexLock l(&internal::g_gmock_mutex);
725  MockObjectState& state = g_mock_object_registry.states()[mock_obj];
726  if (state.first_used_file == NULL) {
727    state.first_used_file = file;
728    state.first_used_line = line;
729    const TestInfo* const test_info =
730        UnitTest::GetInstance()->current_test_info();
731    if (test_info != NULL) {
732      // TODO(wan@google.com): record the test case name when the
733      // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
734      // TearDownTestCase().
735      state.first_used_test_case = test_info->test_case_name();
736      state.first_used_test = test_info->name();
737    }
738  }
739}
740
741// Unregisters a mock method; removes the owning mock object from the
742// registry when the last mock method associated with it has been
743// unregistered.  This is called only in the destructor of
744// FunctionMockerBase.
745void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
746    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
747  internal::g_gmock_mutex.AssertHeld();
748  for (MockObjectRegistry::StateMap::iterator it =
749           g_mock_object_registry.states().begin();
750       it != g_mock_object_registry.states().end(); ++it) {
751    FunctionMockers& mockers = it->second.function_mockers;
752    if (mockers.erase(mocker) > 0) {
753      // mocker was in mockers and has been just removed.
754      if (mockers.empty()) {
755        g_mock_object_registry.states().erase(it);
756      }
757      return;
758    }
759  }
760}
761
762// Clears all ON_CALL()s set on the given mock object.
763void Mock::ClearDefaultActionsLocked(void* mock_obj)
764    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
765  internal::g_gmock_mutex.AssertHeld();
766
767  if (g_mock_object_registry.states().count(mock_obj) == 0) {
768    // No ON_CALL() was set on the given mock object.
769    return;
770  }
771
772  // Clears the default actions for each mock method in the given mock
773  // object.
774  FunctionMockers& mockers =
775      g_mock_object_registry.states()[mock_obj].function_mockers;
776  for (FunctionMockers::const_iterator it = mockers.begin();
777       it != mockers.end(); ++it) {
778    (*it)->ClearDefaultActionsLocked();
779  }
780
781  // We don't clear the content of mockers, as they may still be
782  // needed by VerifyAndClearExpectationsLocked().
783}
784
785Expectation::Expectation() {}
786
787Expectation::Expectation(
788    const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
789    : expectation_base_(an_expectation_base) {}
790
791Expectation::~Expectation() {}
792
793// Adds an expectation to a sequence.
794void Sequence::AddExpectation(const Expectation& expectation) const {
795  if (*last_expectation_ != expectation) {
796    if (last_expectation_->expectation_base() != NULL) {
797      expectation.expectation_base()->immediate_prerequisites_
798          += *last_expectation_;
799    }
800    *last_expectation_ = expectation;
801  }
802}
803
804// Creates the implicit sequence if there isn't one.
805InSequence::InSequence() {
806  if (internal::g_gmock_implicit_sequence.get() == NULL) {
807    internal::g_gmock_implicit_sequence.set(new Sequence);
808    sequence_created_ = true;
809  } else {
810    sequence_created_ = false;
811  }
812}
813
814// Deletes the implicit sequence if it was created by the constructor
815// of this object.
816InSequence::~InSequence() {
817  if (sequence_created_) {
818    delete internal::g_gmock_implicit_sequence.get();
819    internal::g_gmock_implicit_sequence.set(NULL);
820  }
821}
822
823}  // namespace testing
trunk/3rdparty/googletest/googlemock/src/gmock.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gmock/gmock.h"
33#include "gmock/internal/gmock-port.h"
34
35namespace testing {
36
37// TODO(wan@google.com): support using environment variables to
38// control the flag values, like what Google Test does.
39
40GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
41                   "true iff Google Mock should report leaked mock objects "
42                   "as failures.");
43
44GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
45                     "Controls how verbose Google Mock's output is."
46                     "  Valid values:\n"
47                     "  info    - prints all messages.\n"
48                     "  warning - prints warnings and errors.\n"
49                     "  error   - prints errors only.");
50
51namespace internal {
52
53// Parses a string as a command line flag.  The string should have the
54// format "--gmock_flag=value".  When def_optional is true, the
55// "=value" part can be omitted.
56//
57// Returns the value of the flag, or NULL if the parsing failed.
58static const char* ParseGoogleMockFlagValue(const char* str,
59                                            const char* flag,
60                                            bool def_optional) {
61  // str and flag must not be NULL.
62  if (str == NULL || flag == NULL) return NULL;
63
64  // The flag must start with "--gmock_".
65  const std::string flag_str = std::string("--gmock_") + flag;
66  const size_t flag_len = flag_str.length();
67  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
68
69  // Skips the flag name.
70  const char* flag_end = str + flag_len;
71
72  // When def_optional is true, it's OK to not have a "=value" part.
73  if (def_optional && (flag_end[0] == '\0')) {
74    return flag_end;
75  }
76
77  // If def_optional is true and there are more characters after the
78  // flag name, or if def_optional is false, there must be a '=' after
79  // the flag name.
80  if (flag_end[0] != '=') return NULL;
81
82  // Returns the string after "=".
83  return flag_end + 1;
84}
85
86// Parses a string for a Google Mock bool flag, in the form of
87// "--gmock_flag=value".
88//
89// On success, stores the value of the flag in *value, and returns
90// true.  On failure, returns false without changing *value.
91static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
92                                    bool* value) {
93  // Gets the value of the flag as a string.
94  const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
95
96  // Aborts if the parsing failed.
97  if (value_str == NULL) return false;
98
99  // Converts the string value to a bool.
100  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
101  return true;
102}
103
104// Parses a string for a Google Mock string flag, in the form of
105// "--gmock_flag=value".
106//
107// On success, stores the value of the flag in *value, and returns
108// true.  On failure, returns false without changing *value.
109template <typename String>
110static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
111                                      String* value) {
112  // Gets the value of the flag as a string.
113  const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
114
115  // Aborts if the parsing failed.
116  if (value_str == NULL) return false;
117
118  // Sets *value to the value of the flag.
119  *value = value_str;
120  return true;
121}
122
123// The internal implementation of InitGoogleMock().
124//
125// The type parameter CharType can be instantiated to either char or
126// wchar_t.
127template <typename CharType>
128void InitGoogleMockImpl(int* argc, CharType** argv) {
129  // Makes sure Google Test is initialized.  InitGoogleTest() is
130  // idempotent, so it's fine if the user has already called it.
131  InitGoogleTest(argc, argv);
132  if (*argc <= 0) return;
133
134  for (int i = 1; i != *argc; i++) {
135    const std::string arg_string = StreamableToString(argv[i]);
136    const char* const arg = arg_string.c_str();
137
138    // Do we see a Google Mock flag?
139    if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
140                                &GMOCK_FLAG(catch_leaked_mocks)) ||
141        ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
142      // Yes.  Shift the remainder of the argv list left by one.  Note
143      // that argv has (*argc + 1) elements, the last one always being
144      // NULL.  The following loop moves the trailing NULL element as
145      // well.
146      for (int j = i; j != *argc; j++) {
147        argv[j] = argv[j + 1];
148      }
149
150      // Decrements the argument count.
151      (*argc)--;
152
153      // We also need to decrement the iterator as we just removed
154      // an element.
155      i--;
156    }
157  }
158}
159
160}  // namespace internal
161
162// Initializes Google Mock.  This must be called before running the
163// tests.  In particular, it parses a command line for the flags that
164// Google Mock recognizes.  Whenever a Google Mock flag is seen, it is
165// removed from argv, and *argc is decremented.
166//
167// No value is returned.  Instead, the Google Mock flag variables are
168// updated.
169//
170// Since Google Test is needed for Google Mock to work, this function
171// also initializes Google Test and parses its flags, if that hasn't
172// been done.
173GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
174  internal::InitGoogleMockImpl(argc, argv);
175}
176
177// This overloaded version can be used in Windows programs compiled in
178// UNICODE mode.
179GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
180  internal::InitGoogleMockImpl(argc, argv);
181}
182
183}  // namespace testing
trunk/3rdparty/googletest/googlemock/src/gmock_main.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include <iostream>
33#include "gmock/gmock.h"
34#include "gtest/gtest.h"
35
36// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which
37// causes a link error when _tmain is defined in a static library and UNICODE
38// is enabled. For this reason instead of _tmain, main function is used on
39// Windows. See the following link to track the current status of this bug:
40// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464  // NOLINT
41#if GTEST_OS_WINDOWS_MOBILE
42# include <tchar.h>  // NOLINT
43
44GTEST_API_ int _tmain(int argc, TCHAR** argv) {
45#else
46GTEST_API_ int main(int argc, char** argv) {
47#endif  // GTEST_OS_WINDOWS_MOBILE
48  std::cout << "Running main() from gmock_main.cc\n";
49  // Since Google Mock depends on Google Test, InitGoogleMock() is
50  // also responsible for initializing Google Test.  Therefore there's
51  // no need for calling testing::InitGoogleTest() separately.
52  testing::InitGoogleMock(&argc, argv);
53  return RUN_ALL_TESTS();
54}
trunk/3rdparty/googletest/googlemock/test/gmock-actions_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the built-in actions.
35
36#include "gmock/gmock-actions.h"
37#include <algorithm>
38#include <iterator>
39#include <memory>
40#include <string>
41#include "gmock/gmock.h"
42#include "gmock/internal/gmock-port.h"
43#include "gtest/gtest.h"
44#include "gtest/gtest-spi.h"
45
46namespace {
47
48// This list should be kept sorted.
49using testing::Action;
50using testing::ActionInterface;
51using testing::Assign;
52using testing::ByMove;
53using testing::ByRef;
54using testing::DefaultValue;
55using testing::DoDefault;
56using testing::IgnoreResult;
57using testing::Invoke;
58using testing::InvokeWithoutArgs;
59using testing::MakePolymorphicAction;
60using testing::Ne;
61using testing::PolymorphicAction;
62using testing::Return;
63using testing::ReturnNull;
64using testing::ReturnRef;
65using testing::ReturnRefOfCopy;
66using testing::SetArgPointee;
67using testing::SetArgumentPointee;
68using testing::_;
69using testing::get;
70using testing::internal::BuiltInDefaultValue;
71using testing::internal::Int64;
72using testing::internal::UInt64;
73using testing::make_tuple;
74using testing::tuple;
75using testing::tuple_element;
76
77#if !GTEST_OS_WINDOWS_MOBILE
78using testing::SetErrnoAndReturn;
79#endif
80
81#if GTEST_HAS_PROTOBUF_
82using testing::internal::TestMessage;
83#endif  // GTEST_HAS_PROTOBUF_
84
85// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
86TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
87  EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
88  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL);
89  EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL);
90}
91
92// Tests that BuiltInDefaultValue<T*>::Exists() return true.
93TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
94  EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
95  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
96  EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
97}
98
99// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
100// built-in numeric type.
101TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
102  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
103  EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
104  EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
105#if GMOCK_HAS_SIGNED_WCHAR_T_
106  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
107  EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
108#endif
109#if GMOCK_WCHAR_T_IS_NATIVE_
110  EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
111#endif
112  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT
113  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());  // NOLINT
114  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());  // NOLINT
115  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
116  EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
117  EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
118  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());  // NOLINT
119  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());  // NOLINT
120  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());  // NOLINT
121  EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
122  EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
123  EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
124  EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
125}
126
127// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
128// built-in numeric type.
129TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
130  EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
131  EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
132  EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
133#if GMOCK_HAS_SIGNED_WCHAR_T_
134  EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists());
135  EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists());
136#endif
137#if GMOCK_WCHAR_T_IS_NATIVE_
138  EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
139#endif
140  EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT
141  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());  // NOLINT
142  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());  // NOLINT
143  EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
144  EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
145  EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
146  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());  // NOLINT
147  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());  // NOLINT
148  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());  // NOLINT
149  EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
150  EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
151  EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
152  EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
153}
154
155// Tests that BuiltInDefaultValue<bool>::Get() returns false.
156TEST(BuiltInDefaultValueTest, IsFalseForBool) {
157  EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
158}
159
160// Tests that BuiltInDefaultValue<bool>::Exists() returns true.
161TEST(BuiltInDefaultValueTest, BoolExists) {
162  EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
163}
164
165// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
166// string type.
167TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
168#if GTEST_HAS_GLOBAL_STRING
169  EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
170#endif  // GTEST_HAS_GLOBAL_STRING
171
172  EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
173}
174
175// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
176// string type.
177TEST(BuiltInDefaultValueTest, ExistsForString) {
178#if GTEST_HAS_GLOBAL_STRING
179  EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
180#endif  // GTEST_HAS_GLOBAL_STRING
181
182  EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
183}
184
185// Tests that BuiltInDefaultValue<const T>::Get() returns the same
186// value as BuiltInDefaultValue<T>::Get() does.
187TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
188  EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
189  EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
190  EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL);
191  EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
192}
193
194// A type that's default constructible.
195class MyDefaultConstructible {
196 public:
197  MyDefaultConstructible() : value_(42) {}
198
199  int value() const { return value_; }
200
201 private:
202  int value_;
203};
204
205// A type that's not default constructible.
206class MyNonDefaultConstructible {
207 public:
208  // Does not have a default ctor.
209  explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
210
211  int value() const { return value_; }
212
213 private:
214  int value_;
215};
216
217#if GTEST_LANG_CXX11
218
219TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
220  EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
221}
222
223TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
224  EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
225}
226
227#endif  // GTEST_LANG_CXX11
228
229TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
230  EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
231}
232
233// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
234TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
235  EXPECT_DEATH_IF_SUPPORTED({
236    BuiltInDefaultValue<int&>::Get();
237  }, "");
238  EXPECT_DEATH_IF_SUPPORTED({
239    BuiltInDefaultValue<const char&>::Get();
240  }, "");
241}
242
243TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
244  EXPECT_DEATH_IF_SUPPORTED({
245    BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
246  }, "");
247}
248
249// Tests that DefaultValue<T>::IsSet() is false initially.
250TEST(DefaultValueTest, IsInitiallyUnset) {
251  EXPECT_FALSE(DefaultValue<int>::IsSet());
252  EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
253  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
254}
255
256// Tests that DefaultValue<T> can be set and then unset.
257TEST(DefaultValueTest, CanBeSetAndUnset) {
258  EXPECT_TRUE(DefaultValue<int>::Exists());
259  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
260
261  DefaultValue<int>::Set(1);
262  DefaultValue<const MyNonDefaultConstructible>::Set(
263      MyNonDefaultConstructible(42));
264
265  EXPECT_EQ(1, DefaultValue<int>::Get());
266  EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
267
268  EXPECT_TRUE(DefaultValue<int>::Exists());
269  EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
270
271  DefaultValue<int>::Clear();
272  DefaultValue<const MyNonDefaultConstructible>::Clear();
273
274  EXPECT_FALSE(DefaultValue<int>::IsSet());
275  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
276
277  EXPECT_TRUE(DefaultValue<int>::Exists());
278  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
279}
280
281// Tests that DefaultValue<T>::Get() returns the
282// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
283// false.
284TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
285  EXPECT_FALSE(DefaultValue<int>::IsSet());
286  EXPECT_TRUE(DefaultValue<int>::Exists());
287  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
288  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
289
290  EXPECT_EQ(0, DefaultValue<int>::Get());
291
292  EXPECT_DEATH_IF_SUPPORTED({
293    DefaultValue<MyNonDefaultConstructible>::Get();
294  }, "");
295}
296
297#if GTEST_HAS_STD_UNIQUE_PTR_
298TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
299  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
300  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL);
301  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
302    return std::unique_ptr<int>(new int(42));
303  });
304  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
305  std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
306  EXPECT_EQ(42, *i);
307}
308#endif  // GTEST_HAS_STD_UNIQUE_PTR_
309
310// Tests that DefaultValue<void>::Get() returns void.
311TEST(DefaultValueTest, GetWorksForVoid) {
312  return DefaultValue<void>::Get();
313}
314
315// Tests using DefaultValue with a reference type.
316
317// Tests that DefaultValue<T&>::IsSet() is false initially.
318TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
319  EXPECT_FALSE(DefaultValue<int&>::IsSet());
320  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
321  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
322}
323
324// Tests that DefaultValue<T&>::Exists is false initiallly.
325TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
326  EXPECT_FALSE(DefaultValue<int&>::Exists());
327  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
328  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
329}
330
331// Tests that DefaultValue<T&> can be set and then unset.
332TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
333  int n = 1;
334  DefaultValue<const int&>::Set(n);
335  MyNonDefaultConstructible x(42);
336  DefaultValue<MyNonDefaultConstructible&>::Set(x);
337
338  EXPECT_TRUE(DefaultValue<const int&>::Exists());
339  EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
340
341  EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
342  EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
343
344  DefaultValue<const int&>::Clear();
345  DefaultValue<MyNonDefaultConstructible&>::Clear();
346
347  EXPECT_FALSE(DefaultValue<const int&>::Exists());
348  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
349
350  EXPECT_FALSE(DefaultValue<const int&>::IsSet());
351  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
352}
353
354// Tests that DefaultValue<T&>::Get() returns the
355// BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
356// false.
357TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
358  EXPECT_FALSE(DefaultValue<int&>::IsSet());
359  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
360
361  EXPECT_DEATH_IF_SUPPORTED({
362    DefaultValue<int&>::Get();
363  }, "");
364  EXPECT_DEATH_IF_SUPPORTED({
365    DefaultValue<MyNonDefaultConstructible>::Get();
366  }, "");
367}
368
369// Tests that ActionInterface can be implemented by defining the
370// Perform method.
371
372typedef int MyGlobalFunction(bool, int);
373
374class MyActionImpl : public ActionInterface<MyGlobalFunction> {
375 public:
376  virtual int Perform(const tuple<bool, int>& args) {
377    return get<0>(args) ? get<1>(args) : 0;
378  }
379};
380
381TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
382  MyActionImpl my_action_impl;
383  (void)my_action_impl;
384}
385
386TEST(ActionInterfaceTest, MakeAction) {
387  Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
388
389  // When exercising the Perform() method of Action<F>, we must pass
390  // it a tuple whose size and type are compatible with F's argument
391  // types.  For example, if F is int(), then Perform() takes a
392  // 0-tuple; if F is void(bool, int), then Perform() takes a
393  // tuple<bool, int>, and so on.
394  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
395}
396
397// Tests that Action<F> can be contructed from a pointer to
398// ActionInterface<F>.
399TEST(ActionTest, CanBeConstructedFromActionInterface) {
400  Action<MyGlobalFunction> action(new MyActionImpl);
401}
402
403// Tests that Action<F> delegates actual work to ActionInterface<F>.
404TEST(ActionTest, DelegatesWorkToActionInterface) {
405  const Action<MyGlobalFunction> action(new MyActionImpl);
406
407  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
408  EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
409}
410
411// Tests that Action<F> can be copied.
412TEST(ActionTest, IsCopyable) {
413  Action<MyGlobalFunction> a1(new MyActionImpl);
414  Action<MyGlobalFunction> a2(a1);  // Tests the copy constructor.
415
416  // a1 should continue to work after being copied from.
417  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
418  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
419
420  // a2 should work like the action it was copied from.
421  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
422  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
423
424  a2 = a1;  // Tests the assignment operator.
425
426  // a1 should continue to work after being copied from.
427  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
428  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
429
430  // a2 should work like the action it was copied from.
431  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
432  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
433}
434
435// Tests that an Action<From> object can be converted to a
436// compatible Action<To> object.
437
438class IsNotZero : public ActionInterface<bool(int)> {  // NOLINT
439 public:
440  virtual bool Perform(const tuple<int>& arg) {
441    return get<0>(arg) != 0;
442  }
443};
444
445#if !GTEST_OS_SYMBIAN
446// Compiling this test on Nokia's Symbian compiler fails with:
447//  'Result' is not a member of class 'testing::internal::Function<int>'
448//  (point of instantiation: '@unnamed@gmock_actions_test_cc@::
449//      ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
450// with no obvious fix.
451TEST(ActionTest, CanBeConvertedToOtherActionType) {
452  const Action<bool(int)> a1(new IsNotZero);  // NOLINT
453  const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT
454  EXPECT_EQ(1, a2.Perform(make_tuple('a')));
455  EXPECT_EQ(0, a2.Perform(make_tuple('\0')));
456}
457#endif  // !GTEST_OS_SYMBIAN
458
459// The following two classes are for testing MakePolymorphicAction().
460
461// Implements a polymorphic action that returns the second of the
462// arguments it receives.
463class ReturnSecondArgumentAction {
464 public:
465  // We want to verify that MakePolymorphicAction() can work with a
466  // polymorphic action whose Perform() method template is either
467  // const or not.  This lets us verify the non-const case.
468  template <typename Result, typename ArgumentTuple>
469  Result Perform(const ArgumentTuple& args) { return get<1>(args); }
470};
471
472// Implements a polymorphic action that can be used in a nullary
473// function to return 0.
474class ReturnZeroFromNullaryFunctionAction {
475 public:
476  // For testing that MakePolymorphicAction() works when the
477  // implementation class' Perform() method template takes only one
478  // template parameter.
479  //
480  // We want to verify that MakePolymorphicAction() can work with a
481  // polymorphic action whose Perform() method template is either
482  // const or not.  This lets us verify the const case.
483  template <typename Result>
484  Result Perform(const tuple<>&) const { return 0; }
485};
486
487// These functions verify that MakePolymorphicAction() returns a
488// PolymorphicAction<T> where T is the argument's type.
489
490PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
491  return MakePolymorphicAction(ReturnSecondArgumentAction());
492}
493
494PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
495ReturnZeroFromNullaryFunction() {
496  return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
497}
498
499// Tests that MakePolymorphicAction() turns a polymorphic action
500// implementation class into a polymorphic action.
501TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
502  Action<int(bool, int, double)> a1 = ReturnSecondArgument();  // NOLINT
503  EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0)));
504}
505
506// Tests that MakePolymorphicAction() works when the implementation
507// class' Perform() method template has only one template parameter.
508TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
509  Action<int()> a1 = ReturnZeroFromNullaryFunction();
510  EXPECT_EQ(0, a1.Perform(make_tuple()));
511
512  Action<void*()> a2 = ReturnZeroFromNullaryFunction();
513  EXPECT_TRUE(a2.Perform(make_tuple()) == NULL);
514}
515
516// Tests that Return() works as an action for void-returning
517// functions.
518TEST(ReturnTest, WorksForVoid) {
519  const Action<void(int)> ret = Return();  // NOLINT
520  return ret.Perform(make_tuple(1));
521}
522
523// Tests that Return(v) returns v.
524TEST(ReturnTest, ReturnsGivenValue) {
525  Action<int()> ret = Return(1);  // NOLINT
526  EXPECT_EQ(1, ret.Perform(make_tuple()));
527
528  ret = Return(-5);
529  EXPECT_EQ(-5, ret.Perform(make_tuple()));
530}
531
532// Tests that Return("string literal") works.
533TEST(ReturnTest, AcceptsStringLiteral) {
534  Action<const char*()> a1 = Return("Hello");
535  EXPECT_STREQ("Hello", a1.Perform(make_tuple()));
536
537  Action<std::string()> a2 = Return("world");
538  EXPECT_EQ("world", a2.Perform(make_tuple()));
539}
540
541// Test struct which wraps a vector of integers. Used in
542// 'SupportsWrapperReturnType' test.
543struct IntegerVectorWrapper {
544  std::vector<int> * v;
545  IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {}  // NOLINT
546};
547
548// Tests that Return() works when return type is a wrapper type.
549TEST(ReturnTest, SupportsWrapperReturnType) {
550  // Initialize vector of integers.
551  std::vector<int> v;
552  for (int i = 0; i < 5; ++i) v.push_back(i);
553
554  // Return() called with 'v' as argument. The Action will return the same data
555  // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
556  Action<IntegerVectorWrapper()> a = Return(v);
557  const std::vector<int>& result = *(a.Perform(make_tuple()).v);
558  EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
559}
560
561// Tests that Return(v) is covaraint.
562
563struct Base {
564  bool operator==(const Base&) { return true; }
565};
566
567struct Derived : public Base {
568  bool operator==(const Derived&) { return true; }
569};
570
571TEST(ReturnTest, IsCovariant) {
572  Base base;
573  Derived derived;
574  Action<Base*()> ret = Return(&base);
575  EXPECT_EQ(&base, ret.Perform(make_tuple()));
576
577  ret = Return(&derived);
578  EXPECT_EQ(&derived, ret.Perform(make_tuple()));
579}
580
581// Tests that the type of the value passed into Return is converted into T
582// when the action is cast to Action<T(...)> rather than when the action is
583// performed. See comments on testing::internal::ReturnAction in
584// gmock-actions.h for more information.
585class FromType {
586 public:
587  explicit FromType(bool* is_converted) : converted_(is_converted) {}
588  bool* converted() const { return converted_; }
589
590 private:
591  bool* const converted_;
592
593  GTEST_DISALLOW_ASSIGN_(FromType);
594};
595
596class ToType {
597 public:
598  // Must allow implicit conversion due to use in ImplicitCast_<T>.
599  ToType(const FromType& x) { *x.converted() = true; }  // NOLINT
600};
601
602TEST(ReturnTest, ConvertsArgumentWhenConverted) {
603  bool converted = false;
604  FromType x(&converted);
605  Action<ToType()> action(Return(x));
606  EXPECT_TRUE(converted) << "Return must convert its argument in its own "
607                         << "conversion operator.";
608  converted = false;
609  action.Perform(tuple<>());
610  EXPECT_FALSE(converted) << "Action must NOT convert its argument "
611                          << "when performed.";
612}
613
614class DestinationType {};
615
616class SourceType {
617 public:
618  // Note: a non-const typecast operator.
619  operator DestinationType() { return DestinationType(); }
620};
621
622TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
623  SourceType s;
624  Action<DestinationType()> action(Return(s));
625}
626
627// Tests that ReturnNull() returns NULL in a pointer-returning function.
628TEST(ReturnNullTest, WorksInPointerReturningFunction) {
629  const Action<int*()> a1 = ReturnNull();
630  EXPECT_TRUE(a1.Perform(make_tuple()) == NULL);
631
632  const Action<const char*(bool)> a2 = ReturnNull();  // NOLINT
633  EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
634}
635
636#if GTEST_HAS_STD_UNIQUE_PTR_
637// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
638// functions.
639TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
640  const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
641  EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr);
642
643  const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
644  EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr);
645}
646#endif  // GTEST_HAS_STD_UNIQUE_PTR_
647
648// Tests that ReturnRef(v) works for reference types.
649TEST(ReturnRefTest, WorksForReference) {
650  const int n = 0;
651  const Action<const int&(bool)> ret = ReturnRef(n);  // NOLINT
652
653  EXPECT_EQ(&n, &ret.Perform(make_tuple(true)));
654}
655
656// Tests that ReturnRef(v) is covariant.
657TEST(ReturnRefTest, IsCovariant) {
658  Base base;
659  Derived derived;
660  Action<Base&()> a = ReturnRef(base);
661  EXPECT_EQ(&base, &a.Perform(make_tuple()));
662
663  a = ReturnRef(derived);
664  EXPECT_EQ(&derived, &a.Perform(make_tuple()));
665}
666
667// Tests that ReturnRefOfCopy(v) works for reference types.
668TEST(ReturnRefOfCopyTest, WorksForReference) {
669  int n = 42;
670  const Action<const int&()> ret = ReturnRefOfCopy(n);
671
672  EXPECT_NE(&n, &ret.Perform(make_tuple()));
673  EXPECT_EQ(42, ret.Perform(make_tuple()));
674
675  n = 43;
676  EXPECT_NE(&n, &ret.Perform(make_tuple()));
677  EXPECT_EQ(42, ret.Perform(make_tuple()));
678}
679
680// Tests that ReturnRefOfCopy(v) is covariant.
681TEST(ReturnRefOfCopyTest, IsCovariant) {
682  Base base;
683  Derived derived;
684  Action<Base&()> a = ReturnRefOfCopy(base);
685  EXPECT_NE(&base, &a.Perform(make_tuple()));
686
687  a = ReturnRefOfCopy(derived);
688  EXPECT_NE(&derived, &a.Perform(make_tuple()));
689}
690
691// Tests that DoDefault() does the default action for the mock method.
692
693class MockClass {
694 public:
695  MockClass() {}
696
697  MOCK_METHOD1(IntFunc, int(bool flag));  // NOLINT
698  MOCK_METHOD0(Foo, MyNonDefaultConstructible());
699#if GTEST_HAS_STD_UNIQUE_PTR_
700  MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
701  MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
702  MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
703#endif
704
705 private:
706  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
707};
708
709// Tests that DoDefault() returns the built-in default value for the
710// return type by default.
711TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
712  MockClass mock;
713  EXPECT_CALL(mock, IntFunc(_))
714      .WillOnce(DoDefault());
715  EXPECT_EQ(0, mock.IntFunc(true));
716}
717
718// Tests that DoDefault() throws (when exceptions are enabled) or aborts
719// the process when there is no built-in default value for the return type.
720TEST(DoDefaultDeathTest, DiesForUnknowType) {
721  MockClass mock;
722  EXPECT_CALL(mock, Foo())
723      .WillRepeatedly(DoDefault());
724#if GTEST_HAS_EXCEPTIONS
725  EXPECT_ANY_THROW(mock.Foo());
726#else
727  EXPECT_DEATH_IF_SUPPORTED({
728    mock.Foo();
729  }, "");
730#endif
731}
732
733// Tests that using DoDefault() inside a composite action leads to a
734// run-time error.
735
736void VoidFunc(bool /* flag */) {}
737
738TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
739  MockClass mock;
740  EXPECT_CALL(mock, IntFunc(_))
741      .WillRepeatedly(DoAll(Invoke(VoidFunc),
742                            DoDefault()));
743
744  // Ideally we should verify the error message as well.  Sadly,
745  // EXPECT_DEATH() can only capture stderr, while Google Mock's
746  // errors are printed on stdout.  Therefore we have to settle for
747  // not verifying the message.
748  EXPECT_DEATH_IF_SUPPORTED({
749    mock.IntFunc(true);
750  }, "");
751}
752
753// Tests that DoDefault() returns the default value set by
754// DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
755TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
756  DefaultValue<int>::Set(1);
757  MockClass mock;
758  EXPECT_CALL(mock, IntFunc(_))
759      .WillOnce(DoDefault());
760  EXPECT_EQ(1, mock.IntFunc(false));
761  DefaultValue<int>::Clear();
762}
763
764// Tests that DoDefault() does the action specified by ON_CALL().
765TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
766  MockClass mock;
767  ON_CALL(mock, IntFunc(_))
768      .WillByDefault(Return(2));
769  EXPECT_CALL(mock, IntFunc(_))
770      .WillOnce(DoDefault());
771  EXPECT_EQ(2, mock.IntFunc(false));
772}
773
774// Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
775TEST(DoDefaultTest, CannotBeUsedInOnCall) {
776  MockClass mock;
777  EXPECT_NONFATAL_FAILURE({  // NOLINT
778    ON_CALL(mock, IntFunc(_))
779      .WillByDefault(DoDefault());
780  }, "DoDefault() cannot be used in ON_CALL()");
781}
782
783// Tests that SetArgPointee<N>(v) sets the variable pointed to by
784// the N-th (0-based) argument to v.
785TEST(SetArgPointeeTest, SetsTheNthPointee) {
786  typedef void MyFunction(bool, int*, char*);
787  Action<MyFunction> a = SetArgPointee<1>(2);
788
789  int n = 0;
790  char ch = '\0';
791  a.Perform(make_tuple(true, &n, &ch));
792  EXPECT_EQ(2, n);
793  EXPECT_EQ('\0', ch);
794
795  a = SetArgPointee<2>('a');
796  n = 0;
797  ch = '\0';
798  a.Perform(make_tuple(true, &n, &ch));
799  EXPECT_EQ(0, n);
800  EXPECT_EQ('a', ch);
801}
802
803#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
804// Tests that SetArgPointee<N>() accepts a string literal.
805// GCC prior to v4.0 and the Symbian compiler do not support this.
806TEST(SetArgPointeeTest, AcceptsStringLiteral) {
807  typedef void MyFunction(std::string*, const char**);
808  Action<MyFunction> a = SetArgPointee<0>("hi");
809  std::string str;
810  const char* ptr = NULL;
811  a.Perform(make_tuple(&str, &ptr));
812  EXPECT_EQ("hi", str);
813  EXPECT_TRUE(ptr == NULL);
814
815  a = SetArgPointee<1>("world");
816  str = "";
817  a.Perform(make_tuple(&str, &ptr));
818  EXPECT_EQ("", str);
819  EXPECT_STREQ("world", ptr);
820}
821
822TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
823  typedef void MyFunction(const wchar_t**);
824  Action<MyFunction> a = SetArgPointee<0>(L"world");
825  const wchar_t* ptr = NULL;
826  a.Perform(make_tuple(&ptr));
827  EXPECT_STREQ(L"world", ptr);
828
829# if GTEST_HAS_STD_WSTRING
830
831  typedef void MyStringFunction(std::wstring*);
832  Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
833  std::wstring str = L"";
834  a2.Perform(make_tuple(&str));
835  EXPECT_EQ(L"world", str);
836
837# endif
838}
839#endif
840
841// Tests that SetArgPointee<N>() accepts a char pointer.
842TEST(SetArgPointeeTest, AcceptsCharPointer) {
843  typedef void MyFunction(bool, std::string*, const char**);
844  const char* const hi = "hi";
845  Action<MyFunction> a = SetArgPointee<1>(hi);
846  std::string str;
847  const char* ptr = NULL;
848  a.Perform(make_tuple(true, &str, &ptr));
849  EXPECT_EQ("hi", str);
850  EXPECT_TRUE(ptr == NULL);
851
852  char world_array[] = "world";
853  char* const world = world_array;
854  a = SetArgPointee<2>(world);
855  str = "";
856  a.Perform(make_tuple(true, &str, &ptr));
857  EXPECT_EQ("", str);
858  EXPECT_EQ(world, ptr);
859}
860
861TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
862  typedef void MyFunction(bool, const wchar_t**);
863  const wchar_t* const hi = L"hi";
864  Action<MyFunction> a = SetArgPointee<1>(hi);
865  const wchar_t* ptr = NULL;
866  a.Perform(make_tuple(true, &ptr));
867  EXPECT_EQ(hi, ptr);
868
869# if GTEST_HAS_STD_WSTRING
870
871  typedef void MyStringFunction(bool, std::wstring*);
872  wchar_t world_array[] = L"world";
873  wchar_t* const world = world_array;
874  Action<MyStringFunction> a2 = SetArgPointee<1>(world);
875  std::wstring str;
876  a2.Perform(make_tuple(true, &str));
877  EXPECT_EQ(world_array, str);
878# endif
879}
880
881#if GTEST_HAS_PROTOBUF_
882
883// Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
884// variable pointed to by the N-th (0-based) argument to proto_buffer.
885TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
886  TestMessage* const msg = new TestMessage;
887  msg->set_member("yes");
888  TestMessage orig_msg;
889  orig_msg.CopyFrom(*msg);
890
891  Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg);
892  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
893  // s.t. the action works even when the original proto_buffer has
894  // died.  We ensure this behavior by deleting msg before using the
895  // action.
896  delete msg;
897
898  TestMessage dest;
899  EXPECT_FALSE(orig_msg.Equals(dest));
900  a.Perform(make_tuple(true, &dest));
901  EXPECT_TRUE(orig_msg.Equals(dest));
902}
903
904// Tests that SetArgPointee<N>(proto_buffer) sets the
905// ::ProtocolMessage variable pointed to by the N-th (0-based)
906// argument to proto_buffer.
907TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
908  TestMessage* const msg = new TestMessage;
909  msg->set_member("yes");
910  TestMessage orig_msg;
911  orig_msg.CopyFrom(*msg);
912
913  Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg);
914  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
915  // s.t. the action works even when the original proto_buffer has
916  // died.  We ensure this behavior by deleting msg before using the
917  // action.
918  delete msg;
919
920  TestMessage dest;
921  ::ProtocolMessage* const dest_base = &dest;
922  EXPECT_FALSE(orig_msg.Equals(dest));
923  a.Perform(make_tuple(true, dest_base));
924  EXPECT_TRUE(orig_msg.Equals(dest));
925}
926
927// Tests that SetArgPointee<N>(proto2_buffer) sets the v2
928// protobuf variable pointed to by the N-th (0-based) argument to
929// proto2_buffer.
930TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
931  using testing::internal::FooMessage;
932  FooMessage* const msg = new FooMessage;
933  msg->set_int_field(2);
934  msg->set_string_field("hi");
935  FooMessage orig_msg;
936  orig_msg.CopyFrom(*msg);
937
938  Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg);
939  // SetArgPointee<N>(proto2_buffer) makes a copy of
940  // proto2_buffer s.t. the action works even when the original
941  // proto2_buffer has died.  We ensure this behavior by deleting msg
942  // before using the action.
943  delete msg;
944
945  FooMessage dest;
946  dest.set_int_field(0);
947  a.Perform(make_tuple(true, &dest));
948  EXPECT_EQ(2, dest.int_field());
949  EXPECT_EQ("hi", dest.string_field());
950}
951
952// Tests that SetArgPointee<N>(proto2_buffer) sets the
953// proto2::Message variable pointed to by the N-th (0-based) argument
954// to proto2_buffer.
955TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
956  using testing::internal::FooMessage;
957  FooMessage* const msg = new FooMessage;
958  msg->set_int_field(2);
959  msg->set_string_field("hi");
960  FooMessage orig_msg;
961  orig_msg.CopyFrom(*msg);
962
963  Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg);
964  // SetArgPointee<N>(proto2_buffer) makes a copy of
965  // proto2_buffer s.t. the action works even when the original
966  // proto2_buffer has died.  We ensure this behavior by deleting msg
967  // before using the action.
968  delete msg;
969
970  FooMessage dest;
971  dest.set_int_field(0);
972  ::proto2::Message* const dest_base = &dest;
973  a.Perform(make_tuple(true, dest_base));
974  EXPECT_EQ(2, dest.int_field());
975  EXPECT_EQ("hi", dest.string_field());
976}
977
978#endif  // GTEST_HAS_PROTOBUF_
979
980// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
981// the N-th (0-based) argument to v.
982TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
983  typedef void MyFunction(bool, int*, char*);
984  Action<MyFunction> a = SetArgumentPointee<1>(2);
985
986  int n = 0;
987  char ch = '\0';
988  a.Perform(make_tuple(true, &n, &ch));
989  EXPECT_EQ(2, n);
990  EXPECT_EQ('\0', ch);
991
992  a = SetArgumentPointee<2>('a');
993  n = 0;
994  ch = '\0';
995  a.Perform(make_tuple(true, &n, &ch));
996  EXPECT_EQ(0, n);
997  EXPECT_EQ('a', ch);
998}
999
1000#if GTEST_HAS_PROTOBUF_
1001
1002// Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
1003// variable pointed to by the N-th (0-based) argument to proto_buffer.
1004TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
1005  TestMessage* const msg = new TestMessage;
1006  msg->set_member("yes");
1007  TestMessage orig_msg;
1008  orig_msg.CopyFrom(*msg);
1009
1010  Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg);
1011  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
1012  // s.t. the action works even when the original proto_buffer has
1013  // died.  We ensure this behavior by deleting msg before using the
1014  // action.
1015  delete msg;
1016
1017  TestMessage dest;
1018  EXPECT_FALSE(orig_msg.Equals(dest));
1019  a.Perform(make_tuple(true, &dest));
1020  EXPECT_TRUE(orig_msg.Equals(dest));
1021}
1022
1023// Tests that SetArgumentPointee<N>(proto_buffer) sets the
1024// ::ProtocolMessage variable pointed to by the N-th (0-based)
1025// argument to proto_buffer.
1026TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
1027  TestMessage* const msg = new TestMessage;
1028  msg->set_member("yes");
1029  TestMessage orig_msg;
1030  orig_msg.CopyFrom(*msg);
1031
1032  Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg);
1033  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
1034  // s.t. the action works even when the original proto_buffer has
1035  // died.  We ensure this behavior by deleting msg before using the
1036  // action.
1037  delete msg;
1038
1039  TestMessage dest;
1040  ::ProtocolMessage* const dest_base = &dest;
1041  EXPECT_FALSE(orig_msg.Equals(dest));
1042  a.Perform(make_tuple(true, dest_base));
1043  EXPECT_TRUE(orig_msg.Equals(dest));
1044}
1045
1046// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
1047// protobuf variable pointed to by the N-th (0-based) argument to
1048// proto2_buffer.
1049TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
1050  using testing::internal::FooMessage;
1051  FooMessage* const msg = new FooMessage;
1052  msg->set_int_field(2);
1053  msg->set_string_field("hi");
1054  FooMessage orig_msg;
1055  orig_msg.CopyFrom(*msg);
1056
1057  Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg);
1058  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
1059  // proto2_buffer s.t. the action works even when the original
1060  // proto2_buffer has died.  We ensure this behavior by deleting msg
1061  // before using the action.
1062  delete msg;
1063
1064  FooMessage dest;
1065  dest.set_int_field(0);
1066  a.Perform(make_tuple(true, &dest));
1067  EXPECT_EQ(2, dest.int_field());
1068  EXPECT_EQ("hi", dest.string_field());
1069}
1070
1071// Tests that SetArgumentPointee<N>(proto2_buffer) sets the
1072// proto2::Message variable pointed to by the N-th (0-based) argument
1073// to proto2_buffer.
1074TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
1075  using testing::internal::FooMessage;
1076  FooMessage* const msg = new FooMessage;
1077  msg->set_int_field(2);
1078  msg->set_string_field("hi");
1079  FooMessage orig_msg;
1080  orig_msg.CopyFrom(*msg);
1081
1082  Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg);
1083  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
1084  // proto2_buffer s.t. the action works even when the original
1085  // proto2_buffer has died.  We ensure this behavior by deleting msg
1086  // before using the action.
1087  delete msg;
1088
1089  FooMessage dest;
1090  dest.set_int_field(0);
1091  ::proto2::Message* const dest_base = &dest;
1092  a.Perform(make_tuple(true, dest_base));
1093  EXPECT_EQ(2, dest.int_field());
1094  EXPECT_EQ("hi", dest.string_field());
1095}
1096
1097#endif  // GTEST_HAS_PROTOBUF_
1098
1099// Sample functions and functors for testing Invoke() and etc.
1100int Nullary() { return 1; }
1101
1102class NullaryFunctor {
1103 public:
1104  int operator()() { return 2; }
1105};
1106
1107bool g_done = false;
1108void VoidNullary() { g_done = true; }
1109
1110class VoidNullaryFunctor {
1111 public:
1112  void operator()() { g_done = true; }
1113};
1114
1115class Foo {
1116 public:
1117  Foo() : value_(123) {}
1118
1119  int Nullary() const { return value_; }
1120
1121 private:
1122  int value_;
1123};
1124
1125// Tests InvokeWithoutArgs(function).
1126TEST(InvokeWithoutArgsTest, Function) {
1127  // As an action that takes one argument.
1128  Action<int(int)> a = InvokeWithoutArgs(Nullary);  // NOLINT
1129  EXPECT_EQ(1, a.Perform(make_tuple(2)));
1130
1131  // As an action that takes two arguments.
1132  Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary);  // NOLINT
1133  EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5)));
1134
1135  // As an action that returns void.
1136  Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary);  // NOLINT
1137  g_done = false;
1138  a3.Perform(make_tuple(1));
1139  EXPECT_TRUE(g_done);
1140}
1141
1142// Tests InvokeWithoutArgs(functor).
1143TEST(InvokeWithoutArgsTest, Functor) {
1144  // As an action that takes no argument.
1145  Action<int()> a = InvokeWithoutArgs(NullaryFunctor());  // NOLINT
1146  EXPECT_EQ(2, a.Perform(make_tuple()));
1147
1148  // As an action that takes three arguments.
1149  Action<int(int, double, char)> a2 =  // NOLINT
1150      InvokeWithoutArgs(NullaryFunctor());
1151  EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a')));
1152
1153  // As an action that returns void.
1154  Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
1155  g_done = false;
1156  a3.Perform(make_tuple());
1157  EXPECT_TRUE(g_done);
1158}
1159
1160// Tests InvokeWithoutArgs(obj_ptr, method).
1161TEST(InvokeWithoutArgsTest, Method) {
1162  Foo foo;
1163  Action<int(bool, char)> a =  // NOLINT
1164      InvokeWithoutArgs(&foo, &Foo::Nullary);
1165  EXPECT_EQ(123, a.Perform(make_tuple(true, 'a')));
1166}
1167
1168// Tests using IgnoreResult() on a polymorphic action.
1169TEST(IgnoreResultTest, PolymorphicAction) {
1170  Action<void(int)> a = IgnoreResult(Return(5));  // NOLINT
1171  a.Perform(make_tuple(1));
1172}
1173
1174// Tests using IgnoreResult() on a monomorphic action.
1175
1176int ReturnOne() {
1177  g_done = true;
1178  return 1;
1179}
1180
1181TEST(IgnoreResultTest, MonomorphicAction) {
1182  g_done = false;
1183  Action<void()> a = IgnoreResult(Invoke(ReturnOne));
1184  a.Perform(make_tuple());
1185  EXPECT_TRUE(g_done);
1186}
1187
1188// Tests using IgnoreResult() on an action that returns a class type.
1189
1190MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1191  g_done = true;
1192  return MyNonDefaultConstructible(42);
1193}
1194
1195TEST(IgnoreResultTest, ActionReturningClass) {
1196  g_done = false;
1197  Action<void(int)> a =
1198      IgnoreResult(Invoke(ReturnMyNonDefaultConstructible));  // NOLINT
1199  a.Perform(make_tuple(2));
1200  EXPECT_TRUE(g_done);
1201}
1202
1203TEST(AssignTest, Int) {
1204  int x = 0;
1205  Action<void(int)> a = Assign(&x, 5);
1206  a.Perform(make_tuple(0));
1207  EXPECT_EQ(5, x);
1208}
1209
1210TEST(AssignTest, String) {
1211  ::std::string x;
1212  Action<void(void)> a = Assign(&x, "Hello, world");
1213  a.Perform(make_tuple());
1214  EXPECT_EQ("Hello, world", x);
1215}
1216
1217TEST(AssignTest, CompatibleTypes) {
1218  double x = 0;
1219  Action<void(int)> a = Assign(&x, 5);
1220  a.Perform(make_tuple(0));
1221  EXPECT_DOUBLE_EQ(5, x);
1222}
1223
1224#if !GTEST_OS_WINDOWS_MOBILE
1225
1226class SetErrnoAndReturnTest : public testing::Test {
1227 protected:
1228  virtual void SetUp() { errno = 0; }
1229  virtual void TearDown() { errno = 0; }
1230};
1231
1232TEST_F(SetErrnoAndReturnTest, Int) {
1233  Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1234  EXPECT_EQ(-5, a.Perform(make_tuple()));
1235  EXPECT_EQ(ENOTTY, errno);
1236}
1237
1238TEST_F(SetErrnoAndReturnTest, Ptr) {
1239  int x;
1240  Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1241  EXPECT_EQ(&x, a.Perform(make_tuple()));
1242  EXPECT_EQ(ENOTTY, errno);
1243}
1244
1245TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1246  Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1247  EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple()));
1248  EXPECT_EQ(EINVAL, errno);
1249}
1250
1251#endif  // !GTEST_OS_WINDOWS_MOBILE
1252
1253// Tests ByRef().
1254
1255// Tests that ReferenceWrapper<T> is copyable.
1256TEST(ByRefTest, IsCopyable) {
1257  const std::string s1 = "Hi";
1258  const std::string s2 = "Hello";
1259
1260  ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper =
1261      ByRef(s1);
1262  const std::string& r1 = ref_wrapper;
1263  EXPECT_EQ(&s1, &r1);
1264
1265  // Assigns a new value to ref_wrapper.
1266  ref_wrapper = ByRef(s2);
1267  const std::string& r2 = ref_wrapper;
1268  EXPECT_EQ(&s2, &r2);
1269
1270  ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 =
1271      ByRef(s1);
1272  // Copies ref_wrapper1 to ref_wrapper.
1273  ref_wrapper = ref_wrapper1;
1274  const std::string& r3 = ref_wrapper;
1275  EXPECT_EQ(&s1, &r3);
1276}
1277
1278// Tests using ByRef() on a const value.
1279TEST(ByRefTest, ConstValue) {
1280  const int n = 0;
1281  // int& ref = ByRef(n);  // This shouldn't compile - we have a
1282                           // negative compilation test to catch it.
1283  const int& const_ref = ByRef(n);
1284  EXPECT_EQ(&n, &const_ref);
1285}
1286
1287// Tests using ByRef() on a non-const value.
1288TEST(ByRefTest, NonConstValue) {
1289  int n = 0;
1290
1291  // ByRef(n) can be used as either an int&,
1292  int& ref = ByRef(n);
1293  EXPECT_EQ(&n, &ref);
1294
1295  // or a const int&.
1296  const int& const_ref = ByRef(n);
1297  EXPECT_EQ(&n, &const_ref);
1298}
1299
1300// Tests explicitly specifying the type when using ByRef().
1301TEST(ByRefTest, ExplicitType) {
1302  int n = 0;
1303  const int& r1 = ByRef<const int>(n);
1304  EXPECT_EQ(&n, &r1);
1305
1306  // ByRef<char>(n);  // This shouldn't compile - we have a negative
1307                      // compilation test to catch it.
1308
1309  Derived d;
1310  Derived& r2 = ByRef<Derived>(d);
1311  EXPECT_EQ(&d, &r2);
1312
1313  const Derived& r3 = ByRef<const Derived>(d);
1314  EXPECT_EQ(&d, &r3);
1315
1316  Base& r4 = ByRef<Base>(d);
1317  EXPECT_EQ(&d, &r4);
1318
1319  const Base& r5 = ByRef<const Base>(d);
1320  EXPECT_EQ(&d, &r5);
1321
1322  // The following shouldn't compile - we have a negative compilation
1323  // test for it.
1324  //
1325  // Base b;
1326  // ByRef<Derived>(b);
1327}
1328
1329// Tests that Google Mock prints expression ByRef(x) as a reference to x.
1330TEST(ByRefTest, PrintsCorrectly) {
1331  int n = 42;
1332  ::std::stringstream expected, actual;
1333  testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1334  testing::internal::UniversalPrint(ByRef(n), &actual);
1335  EXPECT_EQ(expected.str(), actual.str());
1336}
1337
1338#if GTEST_HAS_STD_UNIQUE_PTR_
1339
1340std::unique_ptr<int> UniquePtrSource() {
1341  return std::unique_ptr<int>(new int(19));
1342}
1343
1344std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1345  std::vector<std::unique_ptr<int>> out;
1346  out.emplace_back(new int(7));
1347  return out;
1348}
1349
1350TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1351  MockClass mock;
1352  std::unique_ptr<int> i(new int(19));
1353  EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
1354  EXPECT_CALL(mock, MakeVectorUnique())
1355      .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1356  Derived* d = new Derived;
1357  EXPECT_CALL(mock, MakeUniqueBase())
1358      .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
1359
1360  std::unique_ptr<int> result1 = mock.MakeUnique();
1361  EXPECT_EQ(19, *result1);
1362
1363  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1364  EXPECT_EQ(1u, vresult.size());
1365  EXPECT_NE(nullptr, vresult[0]);
1366  EXPECT_EQ(7, *vresult[0]);
1367
1368  std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1369  EXPECT_EQ(d, result2.get());
1370}
1371
1372TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1373  testing::MockFunction<void()> mock_function;
1374  MockClass mock;
1375  std::unique_ptr<int> i(new int(19));
1376  EXPECT_CALL(mock_function, Call());
1377  EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
1378      InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
1379      Return(ByMove(std::move(i)))));
1380
1381  std::unique_ptr<int> result1 = mock.MakeUnique();
1382  EXPECT_EQ(19, *result1);
1383}
1384
1385TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1386  MockClass mock;
1387
1388  // Check default value
1389  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
1390    return std::unique_ptr<int>(new int(42));
1391  });
1392  EXPECT_EQ(42, *mock.MakeUnique());
1393
1394  EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1395  EXPECT_CALL(mock, MakeVectorUnique())
1396      .WillRepeatedly(Invoke(VectorUniquePtrSource));
1397  std::unique_ptr<int> result1 = mock.MakeUnique();
1398  EXPECT_EQ(19, *result1);
1399  std::unique_ptr<int> result2 = mock.MakeUnique();
1400  EXPECT_EQ(19, *result2);
1401  EXPECT_NE(result1, result2);
1402
1403  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1404  EXPECT_EQ(1u, vresult.size());
1405  EXPECT_NE(nullptr, vresult[0]);
1406  EXPECT_EQ(7, *vresult[0]);
1407}
1408
1409#endif  // GTEST_HAS_STD_UNIQUE_PTR_
1410
1411}  // Unnamed namespace
trunk/3rdparty/googletest/googlemock/test/gmock-cardinalities_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the built-in cardinalities.
35
36#include "gmock/gmock.h"
37#include "gtest/gtest.h"
38#include "gtest/gtest-spi.h"
39
40namespace {
41
42using std::stringstream;
43using testing::AnyNumber;
44using testing::AtLeast;
45using testing::AtMost;
46using testing::Between;
47using testing::Cardinality;
48using testing::CardinalityInterface;
49using testing::Exactly;
50using testing::IsSubstring;
51using testing::MakeCardinality;
52
53class MockFoo {
54 public:
55  MockFoo() {}
56  MOCK_METHOD0(Bar, int());  // NOLINT
57
58 private:
59  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
60};
61
62// Tests that Cardinality objects can be default constructed.
63TEST(CardinalityTest, IsDefaultConstructable) {
64  Cardinality c;
65}
66
67// Tests that Cardinality objects are copyable.
68TEST(CardinalityTest, IsCopyable) {
69  // Tests the copy constructor.
70  Cardinality c = Exactly(1);
71  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));
72  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
73  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
74
75  // Tests the assignment operator.
76  c = Exactly(2);
77  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
78  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
79  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
80}
81
82TEST(CardinalityTest, IsOverSaturatedByCallCountWorks) {
83  const Cardinality c = AtMost(5);
84  EXPECT_FALSE(c.IsOverSaturatedByCallCount(4));
85  EXPECT_FALSE(c.IsOverSaturatedByCallCount(5));
86  EXPECT_TRUE(c.IsOverSaturatedByCallCount(6));
87}
88
89// Tests that Cardinality::DescribeActualCallCountTo() creates the
90// correct description.
91TEST(CardinalityTest, CanDescribeActualCallCount) {
92  stringstream ss0;
93  Cardinality::DescribeActualCallCountTo(0, &ss0);
94  EXPECT_EQ("never called", ss0.str());
95
96  stringstream ss1;
97  Cardinality::DescribeActualCallCountTo(1, &ss1);
98  EXPECT_EQ("called once", ss1.str());
99
100  stringstream ss2;
101  Cardinality::DescribeActualCallCountTo(2, &ss2);
102  EXPECT_EQ("called twice", ss2.str());
103
104  stringstream ss3;
105  Cardinality::DescribeActualCallCountTo(3, &ss3);
106  EXPECT_EQ("called 3 times", ss3.str());
107}
108
109// Tests AnyNumber()
110TEST(AnyNumber, Works) {
111  const Cardinality c = AnyNumber();
112  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
113  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
114
115  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
116  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
117
118  EXPECT_TRUE(c.IsSatisfiedByCallCount(9));
119  EXPECT_FALSE(c.IsSaturatedByCallCount(9));
120
121  stringstream ss;
122  c.DescribeTo(&ss);
123  EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times",
124                      ss.str());
125}
126
127TEST(AnyNumberTest, HasCorrectBounds) {
128  const Cardinality c = AnyNumber();
129  EXPECT_EQ(0, c.ConservativeLowerBound());
130  EXPECT_EQ(INT_MAX, c.ConservativeUpperBound());
131}
132
133// Tests AtLeast(n).
134
135TEST(AtLeastTest, OnNegativeNumber) {
136  EXPECT_NONFATAL_FAILURE({  // NOLINT
137    AtLeast(-1);
138  }, "The invocation lower bound must be >= 0");
139}
140
141TEST(AtLeastTest, OnZero) {
142  const Cardinality c = AtLeast(0);
143  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
144  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
145
146  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
147  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
148
149  stringstream ss;
150  c.DescribeTo(&ss);
151  EXPECT_PRED_FORMAT2(IsSubstring, "any number of times",
152                      ss.str());
153}
154
155TEST(AtLeastTest, OnPositiveNumber) {
156  const Cardinality c = AtLeast(2);
157  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));
158  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
159
160  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
161  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
162
163  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
164  EXPECT_FALSE(c.IsSaturatedByCallCount(2));
165
166  stringstream ss1;
167  AtLeast(1).DescribeTo(&ss1);
168  EXPECT_PRED_FORMAT2(IsSubstring, "at least once",
169                      ss1.str());
170
171  stringstream ss2;
172  c.DescribeTo(&ss2);
173  EXPECT_PRED_FORMAT2(IsSubstring, "at least twice",
174                      ss2.str());
175
176  stringstream ss3;
177  AtLeast(3).DescribeTo(&ss3);
178  EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times",
179                      ss3.str());
180}
181
182TEST(AtLeastTest, HasCorrectBounds) {
183  const Cardinality c = AtLeast(2);
184  EXPECT_EQ(2, c.ConservativeLowerBound());
185  EXPECT_EQ(INT_MAX, c.ConservativeUpperBound());
186}
187
188// Tests AtMost(n).
189
190TEST(AtMostTest, OnNegativeNumber) {
191  EXPECT_NONFATAL_FAILURE({  // NOLINT
192    AtMost(-1);
193  }, "The invocation upper bound must be >= 0");
194}
195
196TEST(AtMostTest, OnZero) {
197  const Cardinality c = AtMost(0);
198  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
199  EXPECT_TRUE(c.IsSaturatedByCallCount(0));
200
201  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
202  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
203
204  stringstream ss;
205  c.DescribeTo(&ss);
206  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
207                      ss.str());
208}
209
210TEST(AtMostTest, OnPositiveNumber) {
211  const Cardinality c = AtMost(2);
212  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
213  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
214
215  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
216  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
217
218  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
219  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
220
221  stringstream ss1;
222  AtMost(1).DescribeTo(&ss1);
223  EXPECT_PRED_FORMAT2(IsSubstring, "called at most once",
224                      ss1.str());
225
226  stringstream ss2;
227  c.DescribeTo(&ss2);
228  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice",
229                      ss2.str());
230
231  stringstream ss3;
232  AtMost(3).DescribeTo(&ss3);
233  EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times",
234                      ss3.str());
235}
236
237TEST(AtMostTest, HasCorrectBounds) {
238  const Cardinality c = AtMost(2);
239  EXPECT_EQ(0, c.ConservativeLowerBound());
240  EXPECT_EQ(2, c.ConservativeUpperBound());
241}
242
243// Tests Between(m, n).
244
245TEST(BetweenTest, OnNegativeStart) {
246  EXPECT_NONFATAL_FAILURE({  // NOLINT
247    Between(-1, 2);
248  }, "The invocation lower bound must be >= 0, but is actually -1");
249}
250
251TEST(BetweenTest, OnNegativeEnd) {
252  EXPECT_NONFATAL_FAILURE({  // NOLINT
253    Between(1, -2);
254  }, "The invocation upper bound must be >= 0, but is actually -2");
255}
256
257TEST(BetweenTest, OnStartBiggerThanEnd) {
258  EXPECT_NONFATAL_FAILURE({  // NOLINT
259    Between(2, 1);
260  }, "The invocation upper bound (1) must be >= "
261     "the invocation lower bound (2)");
262}
263
264TEST(BetweenTest, OnZeroStartAndZeroEnd) {
265  const Cardinality c = Between(0, 0);
266
267  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
268  EXPECT_TRUE(c.IsSaturatedByCallCount(0));
269
270  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
271  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
272
273  stringstream ss;
274  c.DescribeTo(&ss);
275  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
276                      ss.str());
277}
278
279TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
280  const Cardinality c = Between(0, 2);
281
282  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
283  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
284
285  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
286  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
287
288  EXPECT_FALSE(c.IsSatisfiedByCallCount(4));
289  EXPECT_TRUE(c.IsSaturatedByCallCount(4));
290
291  stringstream ss;
292  c.DescribeTo(&ss);
293  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice",
294                      ss.str());
295}
296
297TEST(BetweenTest, OnSameStartAndEnd) {
298  const Cardinality c = Between(3, 3);
299
300  EXPECT_FALSE(c.IsSatisfiedByCallCount(2));
301  EXPECT_FALSE(c.IsSaturatedByCallCount(2));
302
303  EXPECT_TRUE(c.IsSatisfiedByCallCount(3));
304  EXPECT_TRUE(c.IsSaturatedByCallCount(3));
305
306  EXPECT_FALSE(c.IsSatisfiedByCallCount(4));
307  EXPECT_TRUE(c.IsSaturatedByCallCount(4));
308
309  stringstream ss;
310  c.DescribeTo(&ss);
311  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times",
312                      ss.str());
313}
314
315TEST(BetweenTest, OnDifferentStartAndEnd) {
316  const Cardinality c = Between(3, 5);
317
318  EXPECT_FALSE(c.IsSatisfiedByCallCount(2));
319  EXPECT_FALSE(c.IsSaturatedByCallCount(2));
320
321  EXPECT_TRUE(c.IsSatisfiedByCallCount(3));
322  EXPECT_FALSE(c.IsSaturatedByCallCount(3));
323
324  EXPECT_TRUE(c.IsSatisfiedByCallCount(5));
325  EXPECT_TRUE(c.IsSaturatedByCallCount(5));
326
327  EXPECT_FALSE(c.IsSatisfiedByCallCount(6));
328  EXPECT_TRUE(c.IsSaturatedByCallCount(6));
329
330  stringstream ss;
331  c.DescribeTo(&ss);
332  EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times",
333                      ss.str());
334}
335
336TEST(BetweenTest, HasCorrectBounds) {
337  const Cardinality c = Between(3, 5);
338  EXPECT_EQ(3, c.ConservativeLowerBound());
339  EXPECT_EQ(5, c.ConservativeUpperBound());
340}
341
342// Tests Exactly(n).
343
344TEST(ExactlyTest, OnNegativeNumber) {
345  EXPECT_NONFATAL_FAILURE({  // NOLINT
346    Exactly(-1);
347  }, "The invocation lower bound must be >= 0");
348}
349
350TEST(ExactlyTest, OnZero) {
351  const Cardinality c = Exactly(0);
352  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
353  EXPECT_TRUE(c.IsSaturatedByCallCount(0));
354
355  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
356  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
357
358  stringstream ss;
359  c.DescribeTo(&ss);
360  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
361                      ss.str());
362}
363
364TEST(ExactlyTest, OnPositiveNumber) {
365  const Cardinality c = Exactly(2);
366  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));
367  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
368
369  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
370  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
371
372  stringstream ss1;
373  Exactly(1).DescribeTo(&ss1);
374  EXPECT_PRED_FORMAT2(IsSubstring, "called once",
375                      ss1.str());
376
377  stringstream ss2;
378  c.DescribeTo(&ss2);
379  EXPECT_PRED_FORMAT2(IsSubstring, "called twice",
380                      ss2.str());
381
382  stringstream ss3;
383  Exactly(3).DescribeTo(&ss3);
384  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times",
385                      ss3.str());
386}
387
388TEST(ExactlyTest, HasCorrectBounds) {
389  const Cardinality c = Exactly(3);
390  EXPECT_EQ(3, c.ConservativeLowerBound());
391  EXPECT_EQ(3, c.ConservativeUpperBound());
392}
393
394// Tests that a user can make his own cardinality by implementing
395// CardinalityInterface and calling MakeCardinality().
396
397class EvenCardinality : public CardinalityInterface {
398 public:
399  // Returns true iff call_count calls will satisfy this cardinality.
400  virtual bool IsSatisfiedByCallCount(int call_count) const {
401    return (call_count % 2 == 0);
402  }
403
404  // Returns true iff call_count calls will saturate this cardinality.
405  virtual bool IsSaturatedByCallCount(int /* call_count */) const {
406    return false;
407  }
408
409  // Describes self to an ostream.
410  virtual void DescribeTo(::std::ostream* ss) const {
411    *ss << "called even number of times";
412  }
413};
414
415TEST(MakeCardinalityTest, ConstructsCardinalityFromInterface) {
416  const Cardinality c = MakeCardinality(new EvenCardinality);
417
418  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
419  EXPECT_FALSE(c.IsSatisfiedByCallCount(3));
420
421  EXPECT_FALSE(c.IsSaturatedByCallCount(10000));
422
423  stringstream ss;
424  c.DescribeTo(&ss);
425  EXPECT_EQ("called even number of times", ss.str());
426}
427
428}  // Unnamed namespace
trunk/3rdparty/googletest/googlemock/test/gmock-generated-actions_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the built-in actions generated by a script.
35
36#include "gmock/gmock-generated-actions.h"
37
38#include <functional>
39#include <sstream>
40#include <string>
41#include "gmock/gmock.h"
42#include "gtest/gtest.h"
43
44namespace testing {
45namespace gmock_generated_actions_test {
46
47using ::std::plus;
48using ::std::string;
49using testing::get;
50using testing::make_tuple;
51using testing::tuple;
52using testing::tuple_element;
53using testing::_;
54using testing::Action;
55using testing::ActionInterface;
56using testing::ByRef;
57using testing::DoAll;
58using testing::Invoke;
59using testing::Return;
60using testing::ReturnNew;
61using testing::SetArgPointee;
62using testing::StaticAssertTypeEq;
63using testing::Unused;
64using testing::WithArgs;
65
66// For suppressing compiler warnings on conversion possibly losing precision.
67inline short Short(short n) { return n; }  // NOLINT
68inline char Char(char ch) { return ch; }
69
70// Sample functions and functors for testing various actions.
71int Nullary() { return 1; }
72
73class NullaryFunctor {
74 public:
75  int operator()() { return 2; }
76};
77
78bool g_done = false;
79
80bool Unary(int x) { return x < 0; }
81
82const char* Plus1(const char* s) { return s + 1; }
83
84bool ByConstRef(const string& s) { return s == "Hi"; }
85
86const double g_double = 0;
87bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
88
89string ByNonConstRef(string& s) { return s += "+"; }  // NOLINT
90
91struct UnaryFunctor {
92  int operator()(bool x) { return x ? 1 : -1; }
93};
94
95const char* Binary(const char* input, short n) { return input + n; }  // NOLINT
96
97void VoidBinary(int, char) { g_done = true; }
98
99int Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT
100
101void VoidTernary(int, char, bool) { g_done = true; }
102
103int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
104
105string Concat4(const char* s1, const char* s2, const char* s3,
106               const char* s4) {
107  return string(s1) + s2 + s3 + s4;
108}
109
110int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
111
112struct SumOf5Functor {
113  int operator()(int a, int b, int c, int d, int e) {
114    return a + b + c + d + e;
115  }
116};
117
118string Concat5(const char* s1, const char* s2, const char* s3,
119               const char* s4, const char* s5) {
120  return string(s1) + s2 + s3 + s4 + s5;
121}
122
123int SumOf6(int a, int b, int c, int d, int e, int f) {
124  return a + b + c + d + e + f;
125}
126
127struct SumOf6Functor {
128  int operator()(int a, int b, int c, int d, int e, int f) {
129    return a + b + c + d + e + f;
130  }
131};
132
133string Concat6(const char* s1, const char* s2, const char* s3,
134               const char* s4, const char* s5, const char* s6) {
135  return string(s1) + s2 + s3 + s4 + s5 + s6;
136}
137
138string Concat7(const char* s1, const char* s2, const char* s3,
139               const char* s4, const char* s5, const char* s6,
140               const char* s7) {
141  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
142}
143
144string Concat8(const char* s1, const char* s2, const char* s3,
145               const char* s4, const char* s5, const char* s6,
146               const char* s7, const char* s8) {
147  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
148}
149
150string Concat9(const char* s1, const char* s2, const char* s3,
151               const char* s4, const char* s5, const char* s6,
152               const char* s7, const char* s8, const char* s9) {
153  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
154}
155
156string Concat10(const char* s1, const char* s2, const char* s3,
157                const char* s4, const char* s5, const char* s6,
158                const char* s7, const char* s8, const char* s9,
159                const char* s10) {
160  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
161}
162
163// A helper that turns the type of a C-string literal from const
164// char[N] to const char*.
165inline const char* CharPtr(const char* s) { return s; }
166
167// Tests InvokeArgument<N>(...).
168
169// Tests using InvokeArgument with a nullary function.
170TEST(InvokeArgumentTest, Function0) {
171  Action<int(int, int(*)())> a = InvokeArgument<1>();  // NOLINT
172  EXPECT_EQ(1, a.Perform(make_tuple(2, &Nullary)));
173}
174
175// Tests using InvokeArgument with a unary function.
176TEST(InvokeArgumentTest, Functor1) {
177  Action<int(UnaryFunctor)> a = InvokeArgument<0>(true);  // NOLINT
178  EXPECT_EQ(1, a.Perform(make_tuple(UnaryFunctor())));
179}
180
181// Tests using InvokeArgument with a 5-ary function.
182TEST(InvokeArgumentTest, Function5) {
183  Action<int(int(*)(int, int, int, int, int))> a =  // NOLINT
184      InvokeArgument<0>(10000, 2000, 300, 40, 5);
185  EXPECT_EQ(12345, a.Perform(make_tuple(&SumOf5)));
186}
187
188// Tests using InvokeArgument with a 5-ary functor.
189TEST(InvokeArgumentTest, Functor5) {
190  Action<int(SumOf5Functor)> a =  // NOLINT
191      InvokeArgument<0>(10000, 2000, 300, 40, 5);
192  EXPECT_EQ(12345, a.Perform(make_tuple(SumOf5Functor())));
193}
194
195// Tests using InvokeArgument with a 6-ary function.
196TEST(InvokeArgumentTest, Function6) {
197  Action<int(int(*)(int, int, int, int, int, int))> a =  // NOLINT
198      InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
199  EXPECT_EQ(123456, a.Perform(make_tuple(&SumOf6)));
200}
201
202// Tests using InvokeArgument with a 6-ary functor.
203TEST(InvokeArgumentTest, Functor6) {
204  Action<int(SumOf6Functor)> a =  // NOLINT
205      InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
206  EXPECT_EQ(123456, a.Perform(make_tuple(SumOf6Functor())));
207}
208
209// Tests using InvokeArgument with a 7-ary function.
210TEST(InvokeArgumentTest, Function7) {
211  Action<string(string(*)(const char*, const char*, const char*,
212                          const char*, const char*, const char*,
213                          const char*))> a =
214      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
215  EXPECT_EQ("1234567", a.Perform(make_tuple(&Concat7)));
216}
217
218// Tests using InvokeArgument with a 8-ary function.
219TEST(InvokeArgumentTest, Function8) {
220  Action<string(string(*)(const char*, const char*, const char*,
221                          const char*, const char*, const char*,
222                          const char*, const char*))> a =
223      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
224  EXPECT_EQ("12345678", a.Perform(make_tuple(&Concat8)));
225}
226
227// Tests using InvokeArgument with a 9-ary function.
228TEST(InvokeArgumentTest, Function9) {
229  Action<string(string(*)(const char*, const char*, const char*,
230                          const char*, const char*, const char*,
231                          const char*, const char*, const char*))> a =
232      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
233  EXPECT_EQ("123456789", a.Perform(make_tuple(&Concat9)));
234}
235
236// Tests using InvokeArgument with a 10-ary function.
237TEST(InvokeArgumentTest, Function10) {
238  Action<string(string(*)(const char*, const char*, const char*,
239                          const char*, const char*, const char*,
240                          const char*, const char*, const char*,
241                          const char*))> a =
242      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
243  EXPECT_EQ("1234567890", a.Perform(make_tuple(&Concat10)));
244}
245
246// Tests using InvokeArgument with a function that takes a pointer argument.
247TEST(InvokeArgumentTest, ByPointerFunction) {
248  Action<const char*(const char*(*)(const char* input, short n))> a =  // NOLINT
249      InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
250  EXPECT_STREQ("i", a.Perform(make_tuple(&Binary)));
251}
252
253// Tests using InvokeArgument with a function that takes a const char*
254// by passing it a C-string literal.
255TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
256  Action<const char*(const char*(*)(const char* input, short n))> a =  // NOLINT
257      InvokeArgument<0>("Hi", Short(1));
258  EXPECT_STREQ("i", a.Perform(make_tuple(&Binary)));
259}
260
261// Tests using InvokeArgument with a function that takes a const reference.
262TEST(InvokeArgumentTest, ByConstReferenceFunction) {
263  Action<bool(bool(*function)(const string& s))> a =  // NOLINT
264      InvokeArgument<0>(string("Hi"));
265  // When action 'a' is constructed, it makes a copy of the temporary
266  // string object passed to it, so it's OK to use 'a' later, when the
267  // temporary object has already died.
268  EXPECT_TRUE(a.Perform(make_tuple(&ByConstRef)));
269}
270
271// Tests using InvokeArgument with ByRef() and a function that takes a
272// const reference.
273TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
274  Action<bool(bool(*)(const double& x))> a =  // NOLINT
275      InvokeArgument<0>(ByRef(g_double));
276  // The above line calls ByRef() on a const value.
277  EXPECT_TRUE(a.Perform(make_tuple(&ReferencesGlobalDouble)));
278
279  double x = 0;
280  a = InvokeArgument<0>(ByRef(x));  // This calls ByRef() on a non-const.
281  EXPECT_FALSE(a.Perform(make_tuple(&ReferencesGlobalDouble)));
282}
283
284// Tests using WithArgs and with an action that takes 1 argument.
285TEST(WithArgsTest, OneArg) {
286  Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary));  // NOLINT
287  EXPECT_TRUE(a.Perform(make_tuple(1.5, -1)));
288  EXPECT_FALSE(a.Perform(make_tuple(1.5, 1)));
289}
290
291// Tests using WithArgs with an action that takes 2 arguments.
292TEST(WithArgsTest, TwoArgs) {
293  Action<const char*(const char* s, double x, short n)> a =
294      WithArgs<0, 2>(Invoke(Binary));
295  const char s[] = "Hello";
296  EXPECT_EQ(s + 2, a.Perform(make_tuple(CharPtr(s), 0.5, Short(2))));
297}
298
299// Tests using WithArgs with an action that takes 3 arguments.
300TEST(WithArgsTest, ThreeArgs) {
301  Action<int(int, double, char, short)> a =  // NOLINT
302      WithArgs<0, 2, 3>(Invoke(Ternary));
303  EXPECT_EQ(123, a.Perform(make_tuple(100, 6.5, Char(20), Short(3))));
304}
305
306// Tests using WithArgs with an action that takes 4 arguments.
307TEST(WithArgsTest, FourArgs) {
308  Action<string(const char*, const char*, double, const char*, const char*)> a =
309      WithArgs<4, 3, 1, 0>(Invoke(Concat4));
310  EXPECT_EQ("4310", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), 2.5,
311                                         CharPtr("3"), CharPtr("4"))));
312}
313
314// Tests using WithArgs with an action that takes 5 arguments.
315TEST(WithArgsTest, FiveArgs) {
316  Action<string(const char*, const char*, const char*,
317                const char*, const char*)> a =
318      WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5));
319  EXPECT_EQ("43210",
320            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
321                                 CharPtr("3"), CharPtr("4"))));
322}
323
324// Tests using WithArgs with an action that takes 6 arguments.
325TEST(WithArgsTest, SixArgs) {
326  Action<string(const char*, const char*, const char*)> a =
327      WithArgs<0, 1, 2, 2, 1, 0>(Invoke(Concat6));
328  EXPECT_EQ("012210",
329            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"))));
330}
331
332// Tests using WithArgs with an action that takes 7 arguments.
333TEST(WithArgsTest, SevenArgs) {
334  Action<string(const char*, const char*, const char*, const char*)> a =
335      WithArgs<0, 1, 2, 3, 2, 1, 0>(Invoke(Concat7));
336  EXPECT_EQ("0123210",
337            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
338                                 CharPtr("3"))));
339}
340
341// Tests using WithArgs with an action that takes 8 arguments.
342TEST(WithArgsTest, EightArgs) {
343  Action<string(const char*, const char*, const char*, const char*)> a =
344      WithArgs<0, 1, 2, 3, 0, 1, 2, 3>(Invoke(Concat8));
345  EXPECT_EQ("01230123",
346            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
347                                 CharPtr("3"))));
348}
349
350// Tests using WithArgs with an action that takes 9 arguments.
351TEST(WithArgsTest, NineArgs) {
352  Action<string(const char*, const char*, const char*, const char*)> a =
353      WithArgs<0, 1, 2, 3, 1, 2, 3, 2, 3>(Invoke(Concat9));
354  EXPECT_EQ("012312323",
355            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
356                                 CharPtr("3"))));
357}
358
359// Tests using WithArgs with an action that takes 10 arguments.
360TEST(WithArgsTest, TenArgs) {
361  Action<string(const char*, const char*, const char*, const char*)> a =
362      WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(Concat10));
363  EXPECT_EQ("0123210123",
364            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
365                                 CharPtr("3"))));
366}
367
368// Tests using WithArgs with an action that is not Invoke().
369class SubstractAction : public ActionInterface<int(int, int)> {  // NOLINT
370 public:
371  virtual int Perform(const tuple<int, int>& args) {
372    return get<0>(args) - get<1>(args);
373  }
374};
375
376TEST(WithArgsTest, NonInvokeAction) {
377  Action<int(const string&, int, int)> a =  // NOLINT
378      WithArgs<2, 1>(MakeAction(new SubstractAction));
379  EXPECT_EQ(8, a.Perform(make_tuple(string("hi"), 2, 10)));
380}
381
382// Tests using WithArgs to pass all original arguments in the original order.
383TEST(WithArgsTest, Identity) {
384  Action<int(int x, char y, short z)> a =  // NOLINT
385      WithArgs<0, 1, 2>(Invoke(Ternary));
386  EXPECT_EQ(123, a.Perform(make_tuple(100, Char(20), Short(3))));
387}
388
389// Tests using WithArgs with repeated arguments.
390TEST(WithArgsTest, RepeatedArguments) {
391  Action<int(bool, int m, int n)> a =  // NOLINT
392      WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
393  EXPECT_EQ(4, a.Perform(make_tuple(false, 1, 10)));
394}
395
396// Tests using WithArgs with reversed argument order.
397TEST(WithArgsTest, ReversedArgumentOrder) {
398  Action<const char*(short n, const char* input)> a =  // NOLINT
399      WithArgs<1, 0>(Invoke(Binary));
400  const char s[] = "Hello";
401  EXPECT_EQ(s + 2, a.Perform(make_tuple(Short(2), CharPtr(s))));
402}
403
404// Tests using WithArgs with compatible, but not identical, argument types.
405TEST(WithArgsTest, ArgsOfCompatibleTypes) {
406  Action<long(short x, char y, double z, char c)> a =  // NOLINT
407      WithArgs<0, 1, 3>(Invoke(Ternary));
408  EXPECT_EQ(123, a.Perform(make_tuple(Short(100), Char(20), 5.6, Char(3))));
409}
410
411// Tests using WithArgs with an action that returns void.
412TEST(WithArgsTest, VoidAction) {
413  Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
414  g_done = false;
415  a.Perform(make_tuple(1.5, 'a', 3));
416  EXPECT_TRUE(g_done);
417}
418
419// Tests DoAll(a1, a2).
420TEST(DoAllTest, TwoActions) {
421  int n = 0;
422  Action<int(int*)> a = DoAll(SetArgPointee<0>(1),  // NOLINT
423                              Return(2));
424  EXPECT_EQ(2, a.Perform(make_tuple(&n)));
425  EXPECT_EQ(1, n);
426}
427
428// Tests DoAll(a1, a2, a3).
429TEST(DoAllTest, ThreeActions) {
430  int m = 0, n = 0;
431  Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1),  // NOLINT
432                                    SetArgPointee<1>(2),
433                                    Return(3));
434  EXPECT_EQ(3, a.Perform(make_tuple(&m, &n)));
435  EXPECT_EQ(1, m);
436  EXPECT_EQ(2, n);
437}
438
439// Tests DoAll(a1, a2, a3, a4).
440TEST(DoAllTest, FourActions) {
441  int m = 0, n = 0;
442  char ch = '\0';
443  Action<int(int*, int*, char*)> a =  // NOLINT
444      DoAll(SetArgPointee<0>(1),
445            SetArgPointee<1>(2),
446            SetArgPointee<2>('a'),
447            Return(3));
448  EXPECT_EQ(3, a.Perform(make_tuple(&m, &n, &ch)));
449  EXPECT_EQ(1, m);
450  EXPECT_EQ(2, n);
451  EXPECT_EQ('a', ch);
452}
453
454// Tests DoAll(a1, a2, a3, a4, a5).
455TEST(DoAllTest, FiveActions) {
456  int m = 0, n = 0;
457  char a = '\0', b = '\0';
458  Action<int(int*, int*, char*, char*)> action =  // NOLINT
459      DoAll(SetArgPointee<0>(1),
460            SetArgPointee<1>(2),
461            SetArgPointee<2>('a'),
462            SetArgPointee<3>('b'),
463            Return(3));
464  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b)));
465  EXPECT_EQ(1, m);
466  EXPECT_EQ(2, n);
467  EXPECT_EQ('a', a);
468  EXPECT_EQ('b', b);
469}
470
471// Tests DoAll(a1, a2, ..., a6).
472TEST(DoAllTest, SixActions) {
473  int m = 0, n = 0;
474  char a = '\0', b = '\0', c = '\0';
475  Action<int(int*, int*, char*, char*, char*)> action =  // NOLINT
476      DoAll(SetArgPointee<0>(1),
477            SetArgPointee<1>(2),
478            SetArgPointee<2>('a'),
479            SetArgPointee<3>('b'),
480            SetArgPointee<4>('c'),
481            Return(3));
482  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c)));
483  EXPECT_EQ(1, m);
484  EXPECT_EQ(2, n);
485  EXPECT_EQ('a', a);
486  EXPECT_EQ('b', b);
487  EXPECT_EQ('c', c);
488}
489
490// Tests DoAll(a1, a2, ..., a7).
491TEST(DoAllTest, SevenActions) {
492  int m = 0, n = 0;
493  char a = '\0', b = '\0', c = '\0', d = '\0';
494  Action<int(int*, int*, char*, char*, char*, char*)> action =  // NOLINT
495      DoAll(SetArgPointee<0>(1),
496            SetArgPointee<1>(2),
497            SetArgPointee<2>('a'),
498            SetArgPointee<3>('b'),
499            SetArgPointee<4>('c'),
500            SetArgPointee<5>('d'),
501            Return(3));
502  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d)));
503  EXPECT_EQ(1, m);
504  EXPECT_EQ(2, n);
505  EXPECT_EQ('a', a);
506  EXPECT_EQ('b', b);
507  EXPECT_EQ('c', c);
508  EXPECT_EQ('d', d);
509}
510
511// Tests DoAll(a1, a2, ..., a8).
512TEST(DoAllTest, EightActions) {
513  int m = 0, n = 0;
514  char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0';
515  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT
516             char*)> action =
517      DoAll(SetArgPointee<0>(1),
518            SetArgPointee<1>(2),
519            SetArgPointee<2>('a'),
520            SetArgPointee<3>('b'),
521            SetArgPointee<4>('c'),
522            SetArgPointee<5>('d'),
523            SetArgPointee<6>('e'),
524            Return(3));
525  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e)));
526  EXPECT_EQ(1, m);
527  EXPECT_EQ(2, n);
528  EXPECT_EQ('a', a);
529  EXPECT_EQ('b', b);
530  EXPECT_EQ('c', c);
531  EXPECT_EQ('d', d);
532  EXPECT_EQ('e', e);
533}
534
535// Tests DoAll(a1, a2, ..., a9).
536TEST(DoAllTest, NineActions) {
537  int m = 0, n = 0;
538  char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0';
539  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT
540             char*, char*)> action =
541      DoAll(SetArgPointee<0>(1),
542            SetArgPointee<1>(2),
543            SetArgPointee<2>('a'),
544            SetArgPointee<3>('b'),
545            SetArgPointee<4>('c'),
546            SetArgPointee<5>('d'),
547            SetArgPointee<6>('e'),
548            SetArgPointee<7>('f'),
549            Return(3));
550  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));
551  EXPECT_EQ(1, m);
552  EXPECT_EQ(2, n);
553  EXPECT_EQ('a', a);
554  EXPECT_EQ('b', b);
555  EXPECT_EQ('c', c);
556  EXPECT_EQ('d', d);
557  EXPECT_EQ('e', e);
558  EXPECT_EQ('f', f);
559}
560
561// Tests DoAll(a1, a2, ..., a10).
562TEST(DoAllTest, TenActions) {
563  int m = 0, n = 0;
564  char a = '\0', b = '\0', c = '\0', d = '\0';
565  char e = '\0', f = '\0', g = '\0';
566  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT
567             char*, char*, char*)> action =
568      DoAll(SetArgPointee<0>(1),
569            SetArgPointee<1>(2),
570            SetArgPointee<2>('a'),
571            SetArgPointee<3>('b'),
572            SetArgPointee<4>('c'),
573            SetArgPointee<5>('d'),
574            SetArgPointee<6>('e'),
575            SetArgPointee<7>('f'),
576            SetArgPointee<8>('g'),
577            Return(3));
578  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));
579  EXPECT_EQ(1, m);
580  EXPECT_EQ(2, n);
581  EXPECT_EQ('a', a);
582  EXPECT_EQ('b', b);
583  EXPECT_EQ('c', c);
584  EXPECT_EQ('d', d);
585  EXPECT_EQ('e', e);
586  EXPECT_EQ('f', f);
587  EXPECT_EQ('g', g);
588}
589
590// The ACTION*() macros trigger warning C4100 (unreferenced formal
591// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
592// the macro definition, as the warnings are generated when the macro
593// is expanded and macro expansion cannot contain #pragma.  Therefore
594// we suppress them here.
595#ifdef _MSC_VER
596# pragma warning(push)
597# pragma warning(disable:4100)
598#endif
599
600// Tests the ACTION*() macro family.
601
602// Tests that ACTION() can define an action that doesn't reference the
603// mock function arguments.
604ACTION(Return5) { return 5; }
605
606TEST(ActionMacroTest, WorksWhenNotReferencingArguments) {
607  Action<double()> a1 = Return5();
608  EXPECT_DOUBLE_EQ(5, a1.Perform(make_tuple()));
609
610  Action<int(double, bool)> a2 = Return5();
611  EXPECT_EQ(5, a2.Perform(make_tuple(1, true)));
612}
613
614// Tests that ACTION() can define an action that returns void.
615ACTION(IncrementArg1) { (*arg1)++; }
616
617TEST(ActionMacroTest, WorksWhenReturningVoid) {
618  Action<void(int, int*)> a1 = IncrementArg1();
619  int n = 0;
620  a1.Perform(make_tuple(5, &n));
621  EXPECT_EQ(1, n);
622}
623
624// Tests that the body of ACTION() can reference the type of the
625// argument.
626ACTION(IncrementArg2) {
627  StaticAssertTypeEq<int*, arg2_type>();
628  arg2_type temp = arg2;
629  (*temp)++;
630}
631
632TEST(ActionMacroTest, CanReferenceArgumentType) {
633  Action<void(int, bool, int*)> a1 = IncrementArg2();
634  int n = 0;
635  a1.Perform(make_tuple(5, false, &n));
636  EXPECT_EQ(1, n);
637}
638
639// Tests that the body of ACTION() can reference the argument tuple
640// via args_type and args.
641ACTION(Sum2) {
642  StaticAssertTypeEq<tuple<int, char, int*>, args_type>();
643  args_type args_copy = args;
644  return get<0>(args_copy) + get<1>(args_copy);
645}
646
647TEST(ActionMacroTest, CanReferenceArgumentTuple) {
648  Action<int(int, char, int*)> a1 = Sum2();
649  int dummy = 0;
650  EXPECT_EQ(11, a1.Perform(make_tuple(5, Char(6), &dummy)));
651}
652
653// Tests that the body of ACTION() can reference the mock function
654// type.
655int Dummy(bool flag) { return flag? 1 : 0; }
656
657ACTION(InvokeDummy) {
658  StaticAssertTypeEq<int(bool), function_type>();
659  function_type* fp = &Dummy;
660  return (*fp)(true);
661}
662
663TEST(ActionMacroTest, CanReferenceMockFunctionType) {
664  Action<int(bool)> a1 = InvokeDummy();
665  EXPECT_EQ(1, a1.Perform(make_tuple(true)));
666  EXPECT_EQ(1, a1.Perform(make_tuple(false)));
667}
668
669// Tests that the body of ACTION() can reference the mock function's
670// return type.
671ACTION(InvokeDummy2) {
672  StaticAssertTypeEq<int, return_type>();
673  return_type result = Dummy(true);
674  return result;
675}
676
677TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) {
678  Action<int(bool)> a1 = InvokeDummy2();
679  EXPECT_EQ(1, a1.Perform(make_tuple(true)));
680  EXPECT_EQ(1, a1.Perform(make_tuple(false)));
681}
682
683// Tests that ACTION() works for arguments passed by const reference.
684ACTION(ReturnAddrOfConstBoolReferenceArg) {
685  StaticAssertTypeEq<const bool&, arg1_type>();
686  return &arg1;
687}
688
689TEST(ActionMacroTest, WorksForConstReferenceArg) {
690  Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg();
691  const bool b = false;
692  EXPECT_EQ(&b, a.Perform(tuple<int, const bool&>(0, b)));
693}
694
695// Tests that ACTION() works for arguments passed by non-const reference.
696ACTION(ReturnAddrOfIntReferenceArg) {
697  StaticAssertTypeEq<int&, arg0_type>();
698  return &arg0;
699}
700
701TEST(ActionMacroTest, WorksForNonConstReferenceArg) {
702  Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg();
703  int n = 0;
704  EXPECT_EQ(&n, a.Perform(tuple<int&, bool, int>(n, true, 1)));
705}
706
707// Tests that ACTION() can be used in a namespace.
708namespace action_test {
709ACTION(Sum) { return arg0 + arg1; }
710}  // namespace action_test
711
712TEST(ActionMacroTest, WorksInNamespace) {
713  Action<int(int, int)> a1 = action_test::Sum();
714  EXPECT_EQ(3, a1.Perform(make_tuple(1, 2)));
715}
716
717// Tests that the same ACTION definition works for mock functions with
718// different argument numbers.
719ACTION(PlusTwo) { return arg0 + 2; }
720
721TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) {
722  Action<int(int)> a1 = PlusTwo();
723  EXPECT_EQ(4, a1.Perform(make_tuple(2)));
724
725  Action<double(float, void*)> a2 = PlusTwo();
726  int dummy;
727  EXPECT_DOUBLE_EQ(6, a2.Perform(make_tuple(4.0f, &dummy)));
728}
729
730// Tests that ACTION_P can define a parameterized action.
731ACTION_P(Plus, n) { return arg0 + n; }
732
733TEST(ActionPMacroTest, DefinesParameterizedAction) {
734  Action<int(int m, bool t)> a1 = Plus(9);
735  EXPECT_EQ(10, a1.Perform(make_tuple(1, true)));
736}
737
738// Tests that the body of ACTION_P can reference the argument types
739// and the parameter type.
740ACTION_P(TypedPlus, n) {
741  arg0_type t1 = arg0;
742  n_type t2 = n;
743  return t1 + t2;
744}
745
746TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
747  Action<int(char m, bool t)> a1 = TypedPlus(9);
748  EXPECT_EQ(10, a1.Perform(make_tuple(Char(1), true)));
749}
750
751// Tests that a parameterized action can be used in any mock function
752// whose type is compatible.
753TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
754  Action<std::string(const std::string& s)> a1 = Plus("tail");
755  const std::string re = "re";
756  EXPECT_EQ("retail", a1.Perform(make_tuple(re)));
757}
758
759// Tests that we can use ACTION*() to define actions overloaded on the
760// number of parameters.
761
762ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; }
763
764ACTION_P(OverloadedAction, default_value) {
765  return arg0 ? arg1 : default_value;
766}
767
768ACTION_P2(OverloadedAction, true_value, false_value) {
769  return arg0 ? true_value : false_value;
770}
771
772TEST(ActionMacroTest, CanDefineOverloadedActions) {
773  typedef Action<const char*(bool, const char*)> MyAction;
774
775  const MyAction a1 = OverloadedAction();
776  EXPECT_STREQ("hello", a1.Perform(make_tuple(false, CharPtr("world"))));
777  EXPECT_STREQ("world", a1.Perform(make_tuple(true, CharPtr("world"))));
778
779  const MyAction a2 = OverloadedAction("hi");
780  EXPECT_STREQ("hi", a2.Perform(make_tuple(false, CharPtr("world"))));
781  EXPECT_STREQ("world", a2.Perform(make_tuple(true, CharPtr("world"))));
782
783  const MyAction a3 = OverloadedAction("hi", "you");
784  EXPECT_STREQ("hi", a3.Perform(make_tuple(true, CharPtr("world"))));
785  EXPECT_STREQ("you", a3.Perform(make_tuple(false, CharPtr("world"))));
786}
787
788// Tests ACTION_Pn where n >= 3.
789
790ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; }
791
792TEST(ActionPnMacroTest, WorksFor3Parameters) {
793  Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4);
794  EXPECT_DOUBLE_EQ(3123.4, a1.Perform(make_tuple(3000, true)));
795
796  Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
797  const std::string re = "re";
798  EXPECT_EQ("retail->", a2.Perform(make_tuple(re)));
799}
800
801ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
802
803TEST(ActionPnMacroTest, WorksFor4Parameters) {
804  Action<int(int)> a1 = Plus(1, 2, 3, 4);
805  EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(make_tuple(10)));
806}
807
808ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; }
809
810TEST(ActionPnMacroTest, WorksFor5Parameters) {
811  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5);
812  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(make_tuple(10)));
813}
814
815ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) {
816  return arg0 + p0 + p1 + p2 + p3 + p4 + p5;
817}
818
819TEST(ActionPnMacroTest, WorksFor6Parameters) {
820  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6);
821  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(make_tuple(10)));
822}
823
824ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) {
825  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6;
826}
827
828TEST(ActionPnMacroTest, WorksFor7Parameters) {
829  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7);
830  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(make_tuple(10)));
831}
832
833ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) {
834  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7;
835}
836
837TEST(ActionPnMacroTest, WorksFor8Parameters) {
838  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8);
839  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, a1.Perform(make_tuple(10)));
840}
841
842ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) {
843  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;
844}
845
846TEST(ActionPnMacroTest, WorksFor9Parameters) {
847  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9);
848  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, a1.Perform(make_tuple(10)));
849}
850
851ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) {
852  arg0_type t0 = arg0;
853  last_param_type t9 = last_param;
854  return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9;
855}
856
857TEST(ActionPnMacroTest, WorksFor10Parameters) {
858  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
859  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
860            a1.Perform(make_tuple(10)));
861}
862
863// Tests that the action body can promote the parameter types.
864
865ACTION_P2(PadArgument, prefix, suffix) {
866  // The following lines promote the two parameters to desired types.
867  std::string prefix_str(prefix);
868  char suffix_char = static_cast<char>(suffix);
869  return prefix_str + arg0 + suffix_char;
870}
871
872TEST(ActionPnMacroTest, SimpleTypePromotion) {
873  Action<std::string(const char*)> no_promo =
874      PadArgument(std::string("foo"), 'r');
875  Action<std::string(const char*)> promo =
876      PadArgument("foo", static_cast<int>('r'));
877  EXPECT_EQ("foobar", no_promo.Perform(make_tuple(CharPtr("ba"))));
878  EXPECT_EQ("foobar", promo.Perform(make_tuple(CharPtr("ba"))));
879}
880
881// Tests that we can partially restrict parameter types using a
882// straight-forward pattern.
883
884// Defines a generic action that doesn't restrict the types of its
885// parameters.
886ACTION_P3(ConcatImpl, a, b, c) {
887  std::stringstream ss;
888  ss << a << b << c;
889  return ss.str();
890}
891
892// Next, we try to restrict that either the first parameter is a
893// string, or the second parameter is an int.
894
895// Defines a partially specialized wrapper that restricts the first
896// parameter to std::string.
897template <typename T1, typename T2>
898// ConcatImplActionP3 is the class template ACTION_P3 uses to
899// implement ConcatImpl.  We shouldn't change the name as this
900// pattern requires the user to use it directly.
901ConcatImplActionP3<std::string, T1, T2>
902Concat(const std::string& a, T1 b, T2 c) {
903  GTEST_INTENTIONAL_CONST_COND_PUSH_()
904  if (true) {
905  GTEST_INTENTIONAL_CONST_COND_POP_()
906    // This branch verifies that ConcatImpl() can be invoked without
907    // explicit template arguments.
908    return ConcatImpl(a, b, c);
909  } else {
910    // This branch verifies that ConcatImpl() can also be invoked with
911    // explicit template arguments.  It doesn't really need to be
912    // executed as this is a compile-time verification.
913    return ConcatImpl<std::string, T1, T2>(a, b, c);
914  }
915}
916
917// Defines another partially specialized wrapper that restricts the
918// second parameter to int.
919template <typename T1, typename T2>
920ConcatImplActionP3<T1, int, T2>
921Concat(T1 a, int b, T2 c) {
922  return ConcatImpl(a, b, c);
923}
924
925TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) {
926  Action<const std::string()> a1 = Concat("Hello", "1", 2);
927  EXPECT_EQ("Hello12", a1.Perform(make_tuple()));
928
929  a1 = Concat(1, 2, 3);
930  EXPECT_EQ("123", a1.Perform(make_tuple()));
931}
932
933// Verifies the type of an ACTION*.
934
935ACTION(DoFoo) {}
936ACTION_P(DoFoo, p) {}
937ACTION_P2(DoFoo, p0, p1) {}
938
939TEST(ActionPnMacroTest, TypesAreCorrect) {
940  // DoFoo() must be assignable to a DoFooAction variable.
941  DoFooAction a0 = DoFoo();
942
943  // DoFoo(1) must be assignable to a DoFooActionP variable.
944  DoFooActionP<int> a1 = DoFoo(1);
945
946  // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk
947  // variable, and so on.
948  DoFooActionP2<int, char> a2 = DoFoo(1, '2');
949  PlusActionP3<int, int, char> a3 = Plus(1, 2, '3');
950  PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4');
951  PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5');
952  PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6');
953  PlusActionP7<int, int, int, int, int, int, char> a7 =
954      Plus(1, 2, 3, 4, 5, 6, '7');
955  PlusActionP8<int, int, int, int, int, int, int, char> a8 =
956      Plus(1, 2, 3, 4, 5, 6, 7, '8');
957  PlusActionP9<int, int, int, int, int, int, int, int, char> a9 =
958      Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');
959  PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =
960      Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
961
962  // Avoid "unused variable" warnings.
963  (void)a0;
964  (void)a1;
965  (void)a2;
966  (void)a3;
967  (void)a4;
968  (void)a5;
969  (void)a6;
970  (void)a7;
971  (void)a8;
972  (void)a9;
973  (void)a10;
974}
975
976// Tests that an ACTION_P*() action can be explicitly instantiated
977// with reference-typed parameters.
978
979ACTION_P(Plus1, x) { return x; }
980ACTION_P2(Plus2, x, y) { return x + y; }
981ACTION_P3(Plus3, x, y, z) { return x + y + z; }
982ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
983  return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9;
984}
985
986TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {
987  int x = 1, y = 2, z = 3;
988  const tuple<> empty = make_tuple();
989
990  Action<int()> a = Plus1<int&>(x);
991  EXPECT_EQ(1, a.Perform(empty));
992
993  a = Plus2<const int&, int&>(x, y);
994  EXPECT_EQ(3, a.Perform(empty));
995
996  a = Plus3<int&, const int&, int&>(x, y, z);
997  EXPECT_EQ(6, a.Perform(empty));
998
999  int n[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
1000  a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,
1001      int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7],
1002                              n[8], n[9]);
1003  EXPECT_EQ(55, a.Perform(empty));
1004}
1005
1006class NullaryConstructorClass {
1007 public:
1008  NullaryConstructorClass() : value_(123) {}
1009  int value_;
1010};
1011
1012// Tests using ReturnNew() with a nullary constructor.
1013TEST(ReturnNewTest, NoArgs) {
1014  Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>();
1015  NullaryConstructorClass* c = a.Perform(make_tuple());
1016  EXPECT_EQ(123, c->value_);
1017  delete c;
1018}
1019
1020class UnaryConstructorClass {
1021 public:
1022  explicit UnaryConstructorClass(int value) : value_(value) {}
1023  int value_;
1024};
1025
1026// Tests using ReturnNew() with a unary constructor.
1027TEST(ReturnNewTest, Unary) {
1028  Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
1029  UnaryConstructorClass* c = a.Perform(make_tuple());
1030  EXPECT_EQ(4000, c->value_);
1031  delete c;
1032}
1033
1034TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
1035  Action<UnaryConstructorClass*(bool, int)> a =
1036      ReturnNew<UnaryConstructorClass>(4000);
1037  UnaryConstructorClass* c = a.Perform(make_tuple(false, 5));
1038  EXPECT_EQ(4000, c->value_);
1039  delete c;
1040}
1041
1042TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
1043  Action<const UnaryConstructorClass*()> a =
1044      ReturnNew<UnaryConstructorClass>(4000);
1045  const UnaryConstructorClass* c = a.Perform(make_tuple());
1046  EXPECT_EQ(4000, c->value_);
1047  delete c;
1048}
1049
1050class TenArgConstructorClass {
1051 public:
1052  TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5,
1053                         int a6, int a7, int a8, int a9, int a10)
1054    : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {
1055  }
1056  int value_;
1057};
1058
1059// Tests using ReturnNew() with a 10-argument constructor.
1060TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
1061  Action<TenArgConstructorClass*()> a =
1062      ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000,
1063                                        4000000, 500000, 60000,
1064                                        7000, 800, 90, 0);
1065  TenArgConstructorClass* c = a.Perform(make_tuple());
1066  EXPECT_EQ(1234567890, c->value_);
1067  delete c;
1068}
1069
1070// Tests that ACTION_TEMPLATE works when there is no value parameter.
1071ACTION_TEMPLATE(CreateNew,
1072                HAS_1_TEMPLATE_PARAMS(typename, T),
1073                AND_0_VALUE_PARAMS()) {
1074  return new T;
1075}
1076
1077TEST(ActionTemplateTest, WorksWithoutValueParam) {
1078  const Action<int*()> a = CreateNew<int>();
1079  int* p = a.Perform(make_tuple());
1080  delete p;
1081}
1082
1083// Tests that ACTION_TEMPLATE works when there are value parameters.
1084ACTION_TEMPLATE(CreateNew,
1085                HAS_1_TEMPLATE_PARAMS(typename, T),
1086                AND_1_VALUE_PARAMS(a0)) {
1087  return new T(a0);
1088}
1089
1090TEST(ActionTemplateTest, WorksWithValueParams) {
1091  const Action<int*()> a = CreateNew<int>(42);
1092  int* p = a.Perform(make_tuple());
1093  EXPECT_EQ(42, *p);
1094  delete p;
1095}
1096
1097// Tests that ACTION_TEMPLATE works for integral template parameters.
1098ACTION_TEMPLATE(MyDeleteArg,
1099                HAS_1_TEMPLATE_PARAMS(int, k),
1100                AND_0_VALUE_PARAMS()) {
1101  delete get<k>(args);
1102}
1103
1104// Resets a bool variable in the destructor.
1105class BoolResetter {
1106 public:
1107  explicit BoolResetter(bool* value) : value_(value) {}
1108  ~BoolResetter() { *value_ = false; }
1109 private:
1110  bool* value_;
1111};
1112
1113TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
1114  const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();
1115  int n = 0;
1116  bool b = true;
1117  BoolResetter* resetter = new BoolResetter(&b);
1118  a.Perform(make_tuple(&n, resetter));
1119  EXPECT_FALSE(b);  // Verifies that resetter is deleted.
1120}
1121
1122// Tests that ACTION_TEMPLATES works for template template parameters.
1123ACTION_TEMPLATE(ReturnSmartPointer,
1124                HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,
1125                                      Pointer),
1126                AND_1_VALUE_PARAMS(pointee)) {
1127  return Pointer<pointee_type>(new pointee_type(pointee));
1128}
1129
1130TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {
1131  using ::testing::internal::linked_ptr;
1132  const Action<linked_ptr<int>()> a = ReturnSmartPointer<linked_ptr>(42);
1133  linked_ptr<int> p = a.Perform(make_tuple());
1134  EXPECT_EQ(42, *p);
1135}
1136
1137// Tests that ACTION_TEMPLATE works for 10 template parameters.
1138template <typename T1, typename T2, typename T3, int k4, bool k5,
1139          unsigned int k6, typename T7, typename T8, typename T9>
1140struct GiantTemplate {
1141 public:
1142  explicit GiantTemplate(int a_value) : value(a_value) {}
1143  int value;
1144};
1145
1146ACTION_TEMPLATE(ReturnGiant,
1147                HAS_10_TEMPLATE_PARAMS(
1148                    typename, T1,
1149                    typename, T2,
1150                    typename, T3,
1151                    int, k4,
1152                    bool, k5,
1153                    unsigned int, k6,
1154                    class, T7,
1155                    class, T8,
1156                    class, T9,
1157                    template <typename T> class, T10),
1158                AND_1_VALUE_PARAMS(value)) {
1159  return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);
1160}
1161
1162TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
1163  using ::testing::internal::linked_ptr;
1164  typedef GiantTemplate<linked_ptr<int>, bool, double, 5,
1165      true, 6, char, unsigned, int> Giant;
1166  const Action<Giant()> a = ReturnGiant<
1167      int, bool, double, 5, true, 6, char, unsigned, int, linked_ptr>(42);
1168  Giant giant = a.Perform(make_tuple());
1169  EXPECT_EQ(42, giant.value);
1170}
1171
1172// Tests that ACTION_TEMPLATE works for 10 value parameters.
1173ACTION_TEMPLATE(ReturnSum,
1174                HAS_1_TEMPLATE_PARAMS(typename, Number),
1175                AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {
1176  return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
1177}
1178
1179TEST(ActionTemplateTest, WorksFor10ValueParameters) {
1180  const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
1181  EXPECT_EQ(55, a.Perform(make_tuple()));
1182}
1183
1184// Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded
1185// on the number of value parameters.
1186
1187ACTION(ReturnSum) { return 0; }
1188
1189ACTION_P(ReturnSum, x) { return x; }
1190
1191ACTION_TEMPLATE(ReturnSum,
1192                HAS_1_TEMPLATE_PARAMS(typename, Number),
1193                AND_2_VALUE_PARAMS(v1, v2)) {
1194  return static_cast<Number>(v1) + v2;
1195}
1196
1197ACTION_TEMPLATE(ReturnSum,
1198                HAS_1_TEMPLATE_PARAMS(typename, Number),
1199                AND_3_VALUE_PARAMS(v1, v2, v3)) {
1200  return static_cast<Number>(v1) + v2 + v3;
1201}
1202
1203ACTION_TEMPLATE(ReturnSum,
1204                HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
1205                AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {
1206  return static_cast<Number>(v1) + v2 + v3 + v4 + k;
1207}
1208
1209TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
1210  const Action<int()> a0 = ReturnSum();
1211  const Action<int()> a1 = ReturnSum(1);
1212  const Action<int()> a2 = ReturnSum<int>(1, 2);
1213  const Action<int()> a3 = ReturnSum<int>(1, 2, 3);
1214  const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5);
1215  EXPECT_EQ(0, a0.Perform(make_tuple()));
1216  EXPECT_EQ(1, a1.Perform(make_tuple()));
1217  EXPECT_EQ(3, a2.Perform(make_tuple()));
1218  EXPECT_EQ(6, a3.Perform(make_tuple()));
1219  EXPECT_EQ(12345, a4.Perform(make_tuple()));
1220}
1221
1222#ifdef _MSC_VER
1223# pragma warning(pop)
1224#endif
1225
1226}  // namespace gmock_generated_actions_test
1227}  // namespace testing
trunk/3rdparty/googletest/googlemock/test/gmock-generated-function-mockers_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the function mocker classes.
35
36#include "gmock/gmock-generated-function-mockers.h"
37
38#if GTEST_OS_WINDOWS
39// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
40// we are getting compiler errors if we use basetyps.h, hence including
41// objbase.h for definition of STDMETHOD.
42# include <objbase.h>
43#endif  // GTEST_OS_WINDOWS
44
45#include <map>
46#include <string>
47#include "gmock/gmock.h"
48#include "gtest/gtest.h"
49
50// There is a bug in MSVC (fixed in VS 2008) that prevents creating a
51// mock for a function with const arguments, so we don't test such
52// cases for MSVC versions older than 2008.
53#if !GTEST_OS_WINDOWS || (_MSC_VER >= 1500)
54# define GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
55#endif  // !GTEST_OS_WINDOWS || (_MSC_VER >= 1500)
56
57namespace testing {
58namespace gmock_generated_function_mockers_test {
59
60using testing::internal::string;
61using testing::_;
62using testing::A;
63using testing::An;
64using testing::AnyNumber;
65using testing::Const;
66using testing::DoDefault;
67using testing::Eq;
68using testing::Lt;
69using testing::MockFunction;
70using testing::Ref;
71using testing::Return;
72using testing::ReturnRef;
73using testing::TypedEq;
74
75class FooInterface {
76 public:
77  virtual ~FooInterface() {}
78
79  virtual void VoidReturning(int x) = 0;
80
81  virtual int Nullary() = 0;
82  virtual bool Unary(int x) = 0;
83  virtual long Binary(short x, int y) = 0;  // NOLINT
84  virtual int Decimal(bool b, char c, short d, int e, long f,  // NOLINT
85                      float g, double h, unsigned i, char* j, const string& k)
86      = 0;
87
88  virtual bool TakesNonConstReference(int& n) = 0;  // NOLINT
89  virtual string TakesConstReference(const int& n) = 0;
90#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
91  virtual bool TakesConst(const int x) = 0;
92#endif  // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
93
94  virtual int OverloadedOnArgumentNumber() = 0;
95  virtual int OverloadedOnArgumentNumber(int n) = 0;
96
97  virtual int OverloadedOnArgumentType(int n) = 0;
98  virtual char OverloadedOnArgumentType(char c) = 0;
99
100  virtual int OverloadedOnConstness() = 0;
101  virtual char OverloadedOnConstness() const = 0;
102
103  virtual int TypeWithHole(int (*func)()) = 0;
104  virtual int TypeWithComma(const std::map<int, string>& a_map) = 0;
105
106#if GTEST_OS_WINDOWS
107  STDMETHOD_(int, CTNullary)() = 0;
108  STDMETHOD_(bool, CTUnary)(int x) = 0;
109  STDMETHOD_(int, CTDecimal)(bool b, char c, short d, int e, long f,  // NOLINT
110      float g, double h, unsigned i, char* j, const string& k) = 0;
111  STDMETHOD_(char, CTConst)(int x) const = 0;
112#endif  // GTEST_OS_WINDOWS
113};
114
115// Const qualifiers on arguments were once (incorrectly) considered
116// significant in determining whether two virtual functions had the same
117// signature. This was fixed in Visual Studio 2008. However, the compiler
118// still emits a warning that alerts about this change in behavior.
119#ifdef _MSC_VER
120# pragma warning(push)
121# pragma warning(disable : 4373)
122#endif
123class MockFoo : public FooInterface {
124 public:
125  MockFoo() {}
126
127  // Makes sure that a mock function parameter can be named.
128  MOCK_METHOD1(VoidReturning, void(int n));  // NOLINT
129
130  MOCK_METHOD0(Nullary, int());  // NOLINT
131
132  // Makes sure that a mock function parameter can be unnamed.
133  MOCK_METHOD1(Unary, bool(int));  // NOLINT
134  MOCK_METHOD2(Binary, long(short, int));  // NOLINT
135  MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float,  // NOLINT
136                             double, unsigned, char*, const string& str));
137
138  MOCK_METHOD1(TakesNonConstReference, bool(int&));  // NOLINT
139  MOCK_METHOD1(TakesConstReference, string(const int&));
140
141#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
142  MOCK_METHOD1(TakesConst, bool(const int));  // NOLINT
143#endif
144
145  // Tests that the function return type can contain unprotected comma.
146  MOCK_METHOD0(ReturnTypeWithComma, std::map<int, string>());
147  MOCK_CONST_METHOD1(ReturnTypeWithComma,
148                     std::map<int, string>(int));  // NOLINT
149
150  MOCK_METHOD0(OverloadedOnArgumentNumber, int());  // NOLINT
151  MOCK_METHOD1(OverloadedOnArgumentNumber, int(int));  // NOLINT
152
153  MOCK_METHOD1(OverloadedOnArgumentType, int(int));  // NOLINT
154  MOCK_METHOD1(OverloadedOnArgumentType, char(char));  // NOLINT
155
156  MOCK_METHOD0(OverloadedOnConstness, int());  // NOLINT
157  MOCK_CONST_METHOD0(OverloadedOnConstness, char());  // NOLINT
158
159  MOCK_METHOD1(TypeWithHole, int(int (*)()));  // NOLINT
160  MOCK_METHOD1(TypeWithComma, int(const std::map<int, string>&));  // NOLINT
161
162#if GTEST_OS_WINDOWS
163  MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
164  MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int));
165  MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, int(bool b, char c,
166      short d, int e, long f, float g, double h, unsigned i, char* j,
167      const string& k));
168  MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int));
169
170  // Tests that the function return type can contain unprotected comma.
171  MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
172                             std::map<int, string>());
173#endif  // GTEST_OS_WINDOWS
174
175 private:
176  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
177};
178#ifdef _MSC_VER
179# pragma warning(pop)
180#endif
181
182class FunctionMockerTest : public testing::Test {
183 protected:
184  FunctionMockerTest() : foo_(&mock_foo_) {}
185
186  FooInterface* const foo_;
187  MockFoo mock_foo_;
188};
189
190// Tests mocking a void-returning function.
191TEST_F(FunctionMockerTest, MocksVoidFunction) {
192  EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
193  foo_->VoidReturning(0);
194}
195
196// Tests mocking a nullary function.
197TEST_F(FunctionMockerTest, MocksNullaryFunction) {
198  EXPECT_CALL(mock_foo_, Nullary())
199      .WillOnce(DoDefault())
200      .WillOnce(Return(1));
201
202  EXPECT_EQ(0, foo_->Nullary());
203  EXPECT_EQ(1, foo_->Nullary());
204}
205
206// Tests mocking a unary function.
207TEST_F(FunctionMockerTest, MocksUnaryFunction) {
208  EXPECT_CALL(mock_foo_, Unary(Eq(2)))
209      .Times(2)
210      .WillOnce(Return(true));
211
212  EXPECT_TRUE(foo_->Unary(2));
213  EXPECT_FALSE(foo_->Unary(2));
214}
215
216// Tests mocking a binary function.
217TEST_F(FunctionMockerTest, MocksBinaryFunction) {
218  EXPECT_CALL(mock_foo_, Binary(2, _))
219      .WillOnce(Return(3));
220
221  EXPECT_EQ(3, foo_->Binary(2, 1));
222}
223
224// Tests mocking a decimal function.
225TEST_F(FunctionMockerTest, MocksDecimalFunction) {
226  EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(),
227                                 Lt(100), 5U, NULL, "hi"))
228      .WillOnce(Return(5));
229
230  EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
231}
232
233// Tests mocking a function that takes a non-const reference.
234TEST_F(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
235  int a = 0;
236  EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
237      .WillOnce(Return(true));
238
239  EXPECT_TRUE(foo_->TakesNonConstReference(a));
240}
241
242// Tests mocking a function that takes a const reference.
243TEST_F(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
244  int a = 0;
245  EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
246      .WillOnce(Return("Hello"));
247
248  EXPECT_EQ("Hello", foo_->TakesConstReference(a));
249}
250
251#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
252// Tests mocking a function that takes a const variable.
253TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) {
254  EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
255      .WillOnce(DoDefault());
256
257  EXPECT_FALSE(foo_->TakesConst(5));
258}
259#endif  // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
260
261// Tests mocking functions overloaded on the number of arguments.
262TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
263  EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
264      .WillOnce(Return(1));
265  EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
266      .WillOnce(Return(2));
267
268  EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
269  EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
270}
271
272// Tests mocking functions overloaded on the types of argument.
273TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
274  EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
275      .WillOnce(Return(1));
276  EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
277      .WillOnce(Return('b'));
278
279  EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
280  EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
281}
282
283// Tests mocking functions overloaded on the const-ness of this object.
284TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
285  EXPECT_CALL(mock_foo_, OverloadedOnConstness());
286  EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
287      .WillOnce(Return('a'));
288
289  EXPECT_EQ(0, foo_->OverloadedOnConstness());
290  EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
291}
292
293TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) {
294  const std::map<int, string> a_map;
295  EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
296      .WillOnce(Return(a_map));
297  EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
298      .WillOnce(Return(a_map));
299
300  EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
301  EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
302}
303
304#if GTEST_OS_WINDOWS
305// Tests mocking a nullary function with calltype.
306TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
307  EXPECT_CALL(mock_foo_, CTNullary())
308      .WillOnce(Return(-1))
309      .WillOnce(Return(0));
310
311  EXPECT_EQ(-1, foo_->CTNullary());
312  EXPECT_EQ(0, foo_->CTNullary());
313}
314
315// Tests mocking a unary function with calltype.
316TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
317  EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
318      .Times(2)
319      .WillOnce(Return(true))
320      .WillOnce(Return(false));
321
322  EXPECT_TRUE(foo_->CTUnary(2));
323  EXPECT_FALSE(foo_->CTUnary(2));
324}
325
326// Tests mocking a decimal function with calltype.
327TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
328  EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
329                                   Lt(100), 5U, NULL, "hi"))
330      .WillOnce(Return(10));
331
332  EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
333}
334
335// Tests mocking functions overloaded on the const-ness of this object.
336TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
337  EXPECT_CALL(Const(mock_foo_), CTConst(_))
338      .WillOnce(Return('a'));
339
340  EXPECT_EQ('a', Const(*foo_).CTConst(0));
341}
342
343TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
344  const std::map<int, string> a_map;
345  EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
346      .WillOnce(Return(a_map));
347
348  EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
349}
350
351#endif  // GTEST_OS_WINDOWS
352
353class MockB {
354 public:
355  MockB() {}
356
357  MOCK_METHOD0(DoB, void());
358
359 private:
360  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
361};
362
363// Tests that functions with no EXPECT_CALL() ruls can be called any
364// number of times.
365TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
366  {
367    MockB b;
368  }
369
370  {
371    MockB b;
372    b.DoB();
373  }
374
375  {
376    MockB b;
377    b.DoB();
378    b.DoB();
379  }
380}
381
382// Tests mocking template interfaces.
383
384template <typename T>
385class StackInterface {
386 public:
387  virtual ~StackInterface() {}
388
389  // Template parameter appears in function parameter.
390  virtual void Push(const T& value) = 0;
391  virtual void Pop() = 0;
392  virtual int GetSize() const = 0;
393  // Template parameter appears in function return type.
394  virtual const T& GetTop() const = 0;
395};
396
397template <typename T>
398class MockStack : public StackInterface<T> {
399 public:
400  MockStack() {}
401
402  MOCK_METHOD1_T(Push, void(const T& elem));
403  MOCK_METHOD0_T(Pop, void());
404  MOCK_CONST_METHOD0_T(GetSize, int());  // NOLINT
405  MOCK_CONST_METHOD0_T(GetTop, const T&());
406
407  // Tests that the function return type can contain unprotected comma.
408  MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
409  MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int));  // NOLINT
410
411 private:
412  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
413};
414
415// Tests that template mock works.
416TEST(TemplateMockTest, Works) {
417  MockStack<int> mock;
418
419  EXPECT_CALL(mock, GetSize())
420      .WillOnce(Return(0))
421      .WillOnce(Return(1))
422      .WillOnce(Return(0));
423  EXPECT_CALL(mock, Push(_));
424  int n = 5;
425  EXPECT_CALL(mock, GetTop())
426      .WillOnce(ReturnRef(n));
427  EXPECT_CALL(mock, Pop())
428      .Times(AnyNumber());
429
430  EXPECT_EQ(0, mock.GetSize());
431  mock.Push(5);
432  EXPECT_EQ(1, mock.GetSize());
433  EXPECT_EQ(5, mock.GetTop());
434  mock.Pop();
435  EXPECT_EQ(0, mock.GetSize());
436}
437
438TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
439  MockStack<int> mock;
440
441  const std::map<int, int> a_map;
442  EXPECT_CALL(mock, ReturnTypeWithComma())
443      .WillOnce(Return(a_map));
444  EXPECT_CALL(mock, ReturnTypeWithComma(1))
445      .WillOnce(Return(a_map));
446
447  EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
448  EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
449}
450
451#if GTEST_OS_WINDOWS
452// Tests mocking template interfaces with calltype.
453
454template <typename T>
455class StackInterfaceWithCallType {
456 public:
457  virtual ~StackInterfaceWithCallType() {}
458
459  // Template parameter appears in function parameter.
460  STDMETHOD_(void, Push)(const T& value) = 0;
461  STDMETHOD_(void, Pop)() = 0;
462  STDMETHOD_(int, GetSize)() const = 0;
463  // Template parameter appears in function return type.
464  STDMETHOD_(const T&, GetTop)() const = 0;
465};
466
467template <typename T>
468class MockStackWithCallType : public StackInterfaceWithCallType<T> {
469 public:
470  MockStackWithCallType() {}
471
472  MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
473  MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
474  MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
475  MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
476
477 private:
478  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
479};
480
481// Tests that template mock with calltype works.
482TEST(TemplateMockTestWithCallType, Works) {
483  MockStackWithCallType<int> mock;
484
485  EXPECT_CALL(mock, GetSize())
486      .WillOnce(Return(0))
487      .WillOnce(Return(1))
488      .WillOnce(Return(0));
489  EXPECT_CALL(mock, Push(_));
490  int n = 5;
491  EXPECT_CALL(mock, GetTop())
492      .WillOnce(ReturnRef(n));
493  EXPECT_CALL(mock, Pop())
494      .Times(AnyNumber());
495
496  EXPECT_EQ(0, mock.GetSize());
497  mock.Push(5);
498  EXPECT_EQ(1, mock.GetSize());
499  EXPECT_EQ(5, mock.GetTop());
500  mock.Pop();
501  EXPECT_EQ(0, mock.GetSize());
502}
503#endif  // GTEST_OS_WINDOWS
504
505#define MY_MOCK_METHODS1_ \
506    MOCK_METHOD0(Overloaded, void()); \
507    MOCK_CONST_METHOD1(Overloaded, int(int n)); \
508    MOCK_METHOD2(Overloaded, bool(bool f, int n))
509
510class MockOverloadedOnArgNumber {
511 public:
512  MockOverloadedOnArgNumber() {}
513
514  MY_MOCK_METHODS1_;
515
516 private:
517  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
518};
519
520TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
521  MockOverloadedOnArgNumber mock;
522  EXPECT_CALL(mock, Overloaded());
523  EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
524  EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
525
526  mock.Overloaded();
527  EXPECT_EQ(2, mock.Overloaded(1));
528  EXPECT_TRUE(mock.Overloaded(true, 1));
529}
530
531#define MY_MOCK_METHODS2_ \
532    MOCK_CONST_METHOD1(Overloaded, int(int n)); \
533    MOCK_METHOD1(Overloaded, int(int n));
534
535class MockOverloadedOnConstness {
536 public:
537  MockOverloadedOnConstness() {}
538
539  MY_MOCK_METHODS2_;
540
541 private:
542  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
543};
544
545TEST(OverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
546  MockOverloadedOnConstness mock;
547  const MockOverloadedOnConstness* const_mock = &mock;
548  EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
549  EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3));
550
551  EXPECT_EQ(2, mock.Overloaded(1));
552  EXPECT_EQ(3, const_mock->Overloaded(1));
553}
554
555TEST(MockFunctionTest, WorksForVoidNullary) {
556  MockFunction<void()> foo;
557  EXPECT_CALL(foo, Call());
558  foo.Call();
559}
560
561TEST(MockFunctionTest, WorksForNonVoidNullary) {
562  MockFunction<int()> foo;
563  EXPECT_CALL(foo, Call())
564      .WillOnce(Return(1))
565      .WillOnce(Return(2));
566  EXPECT_EQ(1, foo.Call());
567  EXPECT_EQ(2, foo.Call());
568}
569
570TEST(MockFunctionTest, WorksForVoidUnary) {
571  MockFunction<void(int)> foo;
572  EXPECT_CALL(foo, Call(1));
573  foo.Call(1);
574}
575
576TEST(MockFunctionTest, WorksForNonVoidBinary) {
577  MockFunction<int(bool, int)> foo;
578  EXPECT_CALL(foo, Call(false, 42))
579      .WillOnce(Return(1))
580      .WillOnce(Return(2));
581  EXPECT_CALL(foo, Call(true, Ge(100)))
582      .WillOnce(Return(3));
583  EXPECT_EQ(1, foo.Call(false, 42));
584  EXPECT_EQ(2, foo.Call(false, 42));
585  EXPECT_EQ(3, foo.Call(true, 120));
586}
587
588TEST(MockFunctionTest, WorksFor10Arguments) {
589  MockFunction<int(bool a0, char a1, int a2, int a3, int a4,
590                   int a5, int a6, char a7, int a8, bool a9)> foo;
591  EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
592      .WillOnce(Return(1))
593      .WillOnce(Return(2));
594  EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true));
595  EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
596}
597
598#if GTEST_HAS_STD_FUNCTION_
599TEST(MockFunctionTest, AsStdFunction) {
600  MockFunction<int(int)> foo;
601  auto call = [](const std::function<int(int)> &f, int i) {
602    return f(i);
603  };
604  EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
605  EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
606  EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
607  EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));
608}
609
610TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
611  MockFunction<int&()> foo;
612  int value = 1;
613  EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));
614  int& ref = foo.AsStdFunction()();
615  EXPECT_EQ(1, ref);
616  value = 2;
617  EXPECT_EQ(2, ref);
618}
619#endif  // GTEST_HAS_STD_FUNCTION_
620
621}  // namespace gmock_generated_function_mockers_test
622}  // namespace testing
trunk/3rdparty/googletest/googlemock/test/gmock-generated-internal-utils_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the internal utilities.
35
36#include "gmock/internal/gmock-generated-internal-utils.h"
37#include "gmock/internal/gmock-internal-utils.h"
38#include "gtest/gtest.h"
39
40namespace {
41
42using ::testing::tuple;
43using ::testing::Matcher;
44using ::testing::internal::CompileAssertTypesEqual;
45using ::testing::internal::MatcherTuple;
46using ::testing::internal::Function;
47using ::testing::internal::IgnoredValue;
48
49// Tests the MatcherTuple template struct.
50
51TEST(MatcherTupleTest, ForSize0) {
52  CompileAssertTypesEqual<tuple<>, MatcherTuple<tuple<> >::type>();
53}
54
55TEST(MatcherTupleTest, ForSize1) {
56  CompileAssertTypesEqual<tuple<Matcher<int> >,
57                          MatcherTuple<tuple<int> >::type>();
58}
59
60TEST(MatcherTupleTest, ForSize2) {
61  CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char> >,
62                          MatcherTuple<tuple<int, char> >::type>();
63}
64
65TEST(MatcherTupleTest, ForSize5) {
66  CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
67                                Matcher<double>, Matcher<char*> >,
68                          MatcherTuple<tuple<int, char, bool, double, char*>
69                                      >::type>();
70}
71
72// Tests the Function template struct.
73
74TEST(FunctionTest, Nullary) {
75  typedef Function<int()> F;  // NOLINT
76  CompileAssertTypesEqual<int, F::Result>();
77  CompileAssertTypesEqual<tuple<>, F::ArgumentTuple>();
78  CompileAssertTypesEqual<tuple<>, F::ArgumentMatcherTuple>();
79  CompileAssertTypesEqual<void(), F::MakeResultVoid>();
80  CompileAssertTypesEqual<IgnoredValue(), F::MakeResultIgnoredValue>();
81}
82
83TEST(FunctionTest, Unary) {
84  typedef Function<int(bool)> F;  // NOLINT
85  CompileAssertTypesEqual<int, F::Result>();
86  CompileAssertTypesEqual<bool, F::Argument1>();
87  CompileAssertTypesEqual<tuple<bool>, F::ArgumentTuple>();
88  CompileAssertTypesEqual<tuple<Matcher<bool> >, F::ArgumentMatcherTuple>();
89  CompileAssertTypesEqual<void(bool), F::MakeResultVoid>();  // NOLINT
90  CompileAssertTypesEqual<IgnoredValue(bool),  // NOLINT
91      F::MakeResultIgnoredValue>();
92}
93
94TEST(FunctionTest, Binary) {
95  typedef Function<int(bool, const long&)> F;  // NOLINT
96  CompileAssertTypesEqual<int, F::Result>();
97  CompileAssertTypesEqual<bool, F::Argument1>();
98  CompileAssertTypesEqual<const long&, F::Argument2>();  // NOLINT
99  CompileAssertTypesEqual<tuple<bool, const long&>, F::ArgumentTuple>();  // NOLINT
100  CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<const long&> >,  // NOLINT
101                          F::ArgumentMatcherTuple>();
102  CompileAssertTypesEqual<void(bool, const long&), F::MakeResultVoid>();  // NOLINT
103  CompileAssertTypesEqual<IgnoredValue(bool, const long&),  // NOLINT
104      F::MakeResultIgnoredValue>();
105}
106
107TEST(FunctionTest, LongArgumentList) {
108  typedef Function<char(bool, int, char*, int&, const long&)> F;  // NOLINT
109  CompileAssertTypesEqual<char, F::Result>();
110  CompileAssertTypesEqual<bool, F::Argument1>();
111  CompileAssertTypesEqual<int, F::Argument2>();
112  CompileAssertTypesEqual<char*, F::Argument3>();
113  CompileAssertTypesEqual<int&, F::Argument4>();
114  CompileAssertTypesEqual<const long&, F::Argument5>();  // NOLINT
115  CompileAssertTypesEqual<tuple<bool, int, char*, int&, const long&>,  // NOLINT
116                          F::ArgumentTuple>();
117  CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<int>, Matcher<char*>,
118                                Matcher<int&>, Matcher<const long&> >,  // NOLINT
119                          F::ArgumentMatcherTuple>();
120  CompileAssertTypesEqual<void(bool, int, char*, int&, const long&),  // NOLINT
121                          F::MakeResultVoid>();
122  CompileAssertTypesEqual<
123      IgnoredValue(bool, int, char*, int&, const long&),  // NOLINT
124      F::MakeResultIgnoredValue>();
125}
126
127}  // Unnamed namespace
trunk/3rdparty/googletest/googlemock/test/gmock-generated-matchers_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// Google Mock - a framework for writing C++ mock classes.
31//
32// This file tests the built-in matchers generated by a script.
33
34#include "gmock/gmock-generated-matchers.h"
35
36#include <list>
37#include <map>
38#include <set>
39#include <sstream>
40#include <string>
41#include <utility>
42#include <vector>
43
44#include "gmock/gmock.h"
45#include "gtest/gtest.h"
46#include "gtest/gtest-spi.h"
47
48namespace {
49
50using std::list;
51using std::map;
52using std::pair;
53using std::set;
54using std::stringstream;
55using std::vector;
56using testing::get;
57using testing::make_tuple;
58using testing::tuple;
59using testing::_;
60using testing::Args;
61using testing::Contains;
62using testing::ElementsAre;
63using testing::ElementsAreArray;
64using testing::Eq;
65using testing::Ge;
66using testing::Gt;
67using testing::Le;
68using testing::Lt;
69using testing::MakeMatcher;
70using testing::Matcher;
71using testing::MatcherInterface;
72using testing::MatchResultListener;
73using testing::Ne;
74using testing::Not;
75using testing::Pointee;
76using testing::PrintToString;
77using testing::Ref;
78using testing::StaticAssertTypeEq;
79using testing::StrEq;
80using testing::Value;
81using testing::internal::ElementsAreArrayMatcher;
82using testing::internal::string;
83
84// Returns the description of the given matcher.
85template <typename T>
86string Describe(const Matcher<T>& m) {
87  stringstream ss;
88  m.DescribeTo(&ss);
89  return ss.str();
90}
91
92// Returns the description of the negation of the given matcher.
93template <typename T>
94string DescribeNegation(const Matcher<T>& m) {
95  stringstream ss;
96  m.DescribeNegationTo(&ss);
97  return ss.str();
98}
99
100// Returns the reason why x matches, or doesn't match, m.
101template <typename MatcherType, typename Value>
102string Explain(const MatcherType& m, const Value& x) {
103  stringstream ss;
104  m.ExplainMatchResultTo(x, &ss);
105  return ss.str();
106}
107
108// Tests Args<k0, ..., kn>(m).
109
110TEST(ArgsTest, AcceptsZeroTemplateArg) {
111  const tuple<int, bool> t(5, true);
112  EXPECT_THAT(t, Args<>(Eq(tuple<>())));
113  EXPECT_THAT(t, Not(Args<>(Ne(tuple<>()))));
114}
115
116TEST(ArgsTest, AcceptsOneTemplateArg) {
117  const tuple<int, bool> t(5, true);
118  EXPECT_THAT(t, Args<0>(Eq(make_tuple(5))));
119  EXPECT_THAT(t, Args<1>(Eq(make_tuple(true))));
120  EXPECT_THAT(t, Not(Args<1>(Eq(make_tuple(false)))));
121}
122
123TEST(ArgsTest, AcceptsTwoTemplateArgs) {
124  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
125
126  EXPECT_THAT(t, (Args<0, 1>(Lt())));
127  EXPECT_THAT(t, (Args<1, 2>(Lt())));
128  EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
129}
130
131TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
132  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
133  EXPECT_THAT(t, (Args<0, 0>(Eq())));
134  EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
135}
136
137TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
138  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
139  EXPECT_THAT(t, (Args<2, 0>(Gt())));
140  EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
141}
142
143// The MATCHER*() macros trigger warning C4100 (unreferenced formal
144// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
145// the macro definition, as the warnings are generated when the macro
146// is expanded and macro expansion cannot contain #pragma.  Therefore
147// we suppress them here.
148#ifdef _MSC_VER
149# pragma warning(push)
150# pragma warning(disable:4100)
151#endif
152
153MATCHER(SumIsZero, "") {
154  return get<0>(arg) + get<1>(arg) + get<2>(arg) == 0;
155}
156
157TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
158  EXPECT_THAT(make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
159  EXPECT_THAT(make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
160}
161
162TEST(ArgsTest, CanBeNested) {
163  const tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT
164  EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
165  EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
166}
167
168TEST(ArgsTest, CanMatchTupleByValue) {
169  typedef tuple<char, int, int> Tuple3;
170  const Matcher<Tuple3> m = Args<1, 2>(Lt());
171  EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
172  EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
173}
174
175TEST(ArgsTest, CanMatchTupleByReference) {
176  typedef tuple<char, char, int> Tuple3;
177  const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
178  EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
179  EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
180}
181
182// Validates that arg is printed as str.
183MATCHER_P(PrintsAs, str, "") {
184  return testing::PrintToString(arg) == str;
185}
186
187TEST(ArgsTest, AcceptsTenTemplateArgs) {
188  EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
189              (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
190                  PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
191  EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
192              Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
193                      PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
194}
195
196TEST(ArgsTest, DescirbesSelfCorrectly) {
197  const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt());
198  EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
199            "the first < the second",
200            Describe(m));
201}
202
203TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
204  const Matcher<const tuple<int, bool, char, int>&> m =
205      Args<0, 2, 3>(Args<2, 0>(Lt()));
206  EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
207            "whose fields (#2, #0) are a pair where the first < the second",
208            Describe(m));
209}
210
211TEST(ArgsTest, DescribesNegationCorrectly) {
212  const Matcher<tuple<int, char> > m = Args<1, 0>(Gt());
213  EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
214            "where the first > the second",
215            DescribeNegation(m));
216}
217
218TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
219  const Matcher<tuple<bool, int, int> > m = Args<1, 2>(Eq());
220  EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
221            Explain(m, make_tuple(false, 42, 42)));
222  EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
223            Explain(m, make_tuple(false, 42, 43)));
224}
225
226// For testing Args<>'s explanation.
227class LessThanMatcher : public MatcherInterface<tuple<char, int> > {
228 public:
229  virtual void DescribeTo(::std::ostream* os) const {}
230
231  virtual bool MatchAndExplain(tuple<char, int> value,
232                               MatchResultListener* listener) const {
233    const int diff = get<0>(value) - get<1>(value);
234    if (diff > 0) {
235      *listener << "where the first value is " << diff
236                << " more than the second";
237    }
238    return diff < 0;
239  }
240};
241
242Matcher<tuple<char, int> > LessThan() {
243  return MakeMatcher(new LessThanMatcher);
244}
245
246TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
247  const Matcher<tuple<char, int, int> > m = Args<0, 2>(LessThan());
248  EXPECT_EQ("whose fields (#0, #2) are ('a' (97, 0x61), 42), "
249            "where the first value is 55 more than the second",
250            Explain(m, make_tuple('a', 42, 42)));
251  EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
252            Explain(m, make_tuple('\0', 42, 43)));
253}
254
255// For testing ExplainMatchResultTo().
256class GreaterThanMatcher : public MatcherInterface<int> {
257 public:
258  explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
259
260  virtual void DescribeTo(::std::ostream* os) const {
261    *os << "is greater than " << rhs_;
262  }
263
264  virtual bool MatchAndExplain(int lhs,
265                               MatchResultListener* listener) const {
266    const int diff = lhs - rhs_;
267    if (diff > 0) {
268      *listener << "which is " << diff << " more than " << rhs_;
269    } else if (diff == 0) {
270      *listener << "which is the same as " << rhs_;
271    } else {
272      *listener << "which is " << -diff << " less than " << rhs_;
273    }
274
275    return lhs > rhs_;
276  }
277
278 private:
279  int rhs_;
280};
281
282Matcher<int> GreaterThan(int n) {
283  return MakeMatcher(new GreaterThanMatcher(n));
284}
285
286// Tests for ElementsAre().
287
288TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
289  Matcher<const vector<int>&> m = ElementsAre();
290  EXPECT_EQ("is empty", Describe(m));
291}
292
293TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
294  Matcher<vector<int> > m = ElementsAre(Gt(5));
295  EXPECT_EQ("has 1 element that is > 5", Describe(m));
296}
297
298TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
299  Matcher<list<string> > m = ElementsAre(StrEq("one"), "two");
300  EXPECT_EQ("has 2 elements where\n"
301            "element #0 is equal to \"one\",\n"
302            "element #1 is equal to \"two\"", Describe(m));
303}
304
305TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
306  Matcher<vector<int> > m = ElementsAre();
307  EXPECT_EQ("isn't empty", DescribeNegation(m));
308}
309
310TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
311  Matcher<const list<int>& > m = ElementsAre(Gt(5));
312  EXPECT_EQ("doesn't have 1 element, or\n"
313            "element #0 isn't > 5", DescribeNegation(m));
314}
315
316TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
317  Matcher<const list<string>& > m = ElementsAre("one", "two");
318  EXPECT_EQ("doesn't have 2 elements, or\n"
319            "element #0 isn't equal to \"one\", or\n"
320            "element #1 isn't equal to \"two\"", DescribeNegation(m));
321}
322
323TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
324  Matcher<const list<int>& > m = ElementsAre(1, Ne(2));
325
326  list<int> test_list;
327  test_list.push_back(1);
328  test_list.push_back(3);
329  EXPECT_EQ("", Explain(m, test_list));  // No need to explain anything.
330}
331
332TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
333  Matcher<const vector<int>& > m =
334      ElementsAre(GreaterThan(1), 0, GreaterThan(2));
335
336  const int a[] = { 10, 0, 100 };
337  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
338  EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n"
339            "and whose element #2 matches, which is 98 more than 2",
340            Explain(m, test_vector));
341}
342
343TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
344  Matcher<const list<int>& > m = ElementsAre(1, 3);
345
346  list<int> test_list;
347  // No need to explain when the container is empty.
348  EXPECT_EQ("", Explain(m, test_list));
349
350  test_list.push_back(1);
351  EXPECT_EQ("which has 1 element", Explain(m, test_list));
352}
353
354TEST(ElementsAreTest, CanExplainMismatchRightSize) {
355  Matcher<const vector<int>& > m = ElementsAre(1, GreaterThan(5));
356
357  vector<int> v;
358  v.push_back(2);
359  v.push_back(1);
360  EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
361
362  v[0] = 1;
363  EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
364            Explain(m, v));
365}
366
367TEST(ElementsAreTest, MatchesOneElementVector) {
368  vector<string> test_vector;
369  test_vector.push_back("test string");
370
371  EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
372}
373
374TEST(ElementsAreTest, MatchesOneElementList) {
375  list<string> test_list;
376  test_list.push_back("test string");
377
378  EXPECT_THAT(test_list, ElementsAre("test string"));
379}
380
381TEST(ElementsAreTest, MatchesThreeElementVector) {
382  vector<string> test_vector;
383  test_vector.push_back("one");
384  test_vector.push_back("two");
385  test_vector.push_back("three");
386
387  EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
388}
389
390TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
391  vector<int> test_vector;
392  test_vector.push_back(4);
393
394  EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
395}
396
397TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
398  vector<int> test_vector;
399  test_vector.push_back(4);
400
401  EXPECT_THAT(test_vector, ElementsAre(_));
402}
403
404TEST(ElementsAreTest, MatchesOneElementValue) {
405  vector<int> test_vector;
406  test_vector.push_back(4);
407
408  EXPECT_THAT(test_vector, ElementsAre(4));
409}
410
411TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
412  vector<int> test_vector;
413  test_vector.push_back(1);
414  test_vector.push_back(2);
415  test_vector.push_back(3);
416
417  EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
418}
419
420TEST(ElementsAreTest, MatchesTenElementVector) {
421  const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
422  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
423
424  EXPECT_THAT(test_vector,
425              // The element list can contain values and/or matchers
426              // of different types.
427              ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
428}
429
430TEST(ElementsAreTest, DoesNotMatchWrongSize) {
431  vector<string> test_vector;
432  test_vector.push_back("test string");
433  test_vector.push_back("test string");
434
435  Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
436  EXPECT_FALSE(m.Matches(test_vector));
437}
438
439TEST(ElementsAreTest, DoesNotMatchWrongValue) {
440  vector<string> test_vector;
441  test_vector.push_back("other string");
442
443  Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
444  EXPECT_FALSE(m.Matches(test_vector));
445}
446
447TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
448  vector<string> test_vector;
449  test_vector.push_back("one");
450  test_vector.push_back("three");
451  test_vector.push_back("two");
452
453  Matcher<vector<string> > m = ElementsAre(
454    StrEq("one"), StrEq("two"), StrEq("three"));
455  EXPECT_FALSE(m.Matches(test_vector));
456}
457
458TEST(ElementsAreTest, WorksForNestedContainer) {
459  const char* strings[] = {
460    "Hi",
461    "world"
462  };
463
464  vector<list<char> > nested;
465  for (size_t i = 0; i < GTEST_ARRAY_SIZE_(strings); i++) {
466    nested.push_back(list<char>(strings[i], strings[i] + strlen(strings[i])));
467  }
468
469  EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
470                                  ElementsAre('w', 'o', _, _, 'd')));
471  EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
472                                      ElementsAre('w', 'o', _, _, 'd'))));
473}
474
475TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
476  int a[] = { 0, 1, 2 };
477  vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
478
479  EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
480  EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
481}
482
483TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
484  int a[] = { 0, 1, 2 };
485  vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
486
487  EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
488  EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
489}
490
491TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
492  int array[] = { 0, 1, 2 };
493  EXPECT_THAT(array, ElementsAre(0, 1, _));
494  EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
495  EXPECT_THAT(array, Not(ElementsAre(0, _)));
496}
497
498class NativeArrayPassedAsPointerAndSize {
499 public:
500  NativeArrayPassedAsPointerAndSize() {}
501
502  MOCK_METHOD2(Helper, void(int* array, int size));
503
504 private:
505  GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
506};
507
508TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
509  int array[] = { 0, 1 };
510  ::testing::tuple<int*, size_t> array_as_tuple(array, 2);
511  EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
512  EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
513
514  NativeArrayPassedAsPointerAndSize helper;
515  EXPECT_CALL(helper, Helper(_, _))
516      .With(ElementsAre(0, 1));
517  helper.Helper(array, 2);
518}
519
520TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
521  const char a2[][3] = { "hi", "lo" };
522  EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
523                              ElementsAre('l', 'o', '\0')));
524  EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
525  EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
526                              ElementsAre('l', 'o', '\0')));
527}
528
529TEST(ElementsAreTest, AcceptsStringLiteral) {
530  string array[] = { "hi", "one", "two" };
531  EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
532  EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
533}
534
535#ifndef _MSC_VER
536
537// The following test passes a value of type const char[] to a
538// function template that expects const T&.  Some versions of MSVC
539// generates a compiler error C2665 for that.  We believe it's a bug
540// in MSVC.  Therefore this test is #if-ed out for MSVC.
541
542// Declared here with the size unknown.  Defined AFTER the following test.
543extern const char kHi[];
544
545TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
546  // The size of kHi is not known in this test, but ElementsAre() should
547  // still accept it.
548
549  string array1[] = { "hi" };
550  EXPECT_THAT(array1, ElementsAre(kHi));
551
552  string array2[] = { "ho" };
553  EXPECT_THAT(array2, Not(ElementsAre(kHi)));
554}
555
556const char kHi[] = "hi";
557
558#endif  // _MSC_VER
559
560TEST(ElementsAreTest, MakesCopyOfArguments) {
561  int x = 1;
562  int y = 2;
563  // This should make a copy of x and y.
564  ::testing::internal::ElementsAreMatcher<testing::tuple<int, int> >
565          polymorphic_matcher = ElementsAre(x, y);
566  // Changing x and y now shouldn't affect the meaning of the above matcher.
567  x = y = 0;
568  const int array1[] = { 1, 2 };
569  EXPECT_THAT(array1, polymorphic_matcher);
570  const int array2[] = { 0, 0 };
571  EXPECT_THAT(array2, Not(polymorphic_matcher));
572}
573
574
575// Tests for ElementsAreArray().  Since ElementsAreArray() shares most
576// of the implementation with ElementsAre(), we don't test it as
577// thoroughly here.
578
579TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
580  const int a[] = { 1, 2, 3 };
581
582  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
583  EXPECT_THAT(test_vector, ElementsAreArray(a));
584
585  test_vector[2] = 0;
586  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
587}
588
589TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
590  const char* a[] = { "one", "two", "three" };
591
592  vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
593  EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a)));
594
595  const char** p = a;
596  test_vector[0] = "1";
597  EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GTEST_ARRAY_SIZE_(a))));
598}
599
600TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
601  const char* a[] = { "one", "two", "three" };
602
603  vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
604  EXPECT_THAT(test_vector, ElementsAreArray(a));
605
606  test_vector[0] = "1";
607  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
608}
609
610TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
611  const Matcher<string> kMatcherArray[] =
612    { StrEq("one"), StrEq("two"), StrEq("three") };
613
614  vector<string> test_vector;
615  test_vector.push_back("one");
616  test_vector.push_back("two");
617  test_vector.push_back("three");
618  EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
619
620  test_vector.push_back("three");
621  EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
622}
623
624TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
625  const int a[] = { 1, 2, 3 };
626  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
627  const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
628  EXPECT_THAT(test_vector, ElementsAreArray(expected));
629  test_vector.push_back(4);
630  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
631}
632
633#if GTEST_HAS_STD_INITIALIZER_LIST_
634
635TEST(ElementsAreArrayTest, TakesInitializerList) {
636  const int a[5] = { 1, 2, 3, 4, 5 };
637  EXPECT_THAT(a, ElementsAreArray({ 1, 2, 3, 4, 5 }));
638  EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 5, 4 })));
639  EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 4, 6 })));
640}
641
642TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
643  const string a[5] = { "a", "b", "c", "d", "e" };
644  EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" }));
645  EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" })));
646  EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" })));
647}
648
649TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
650  const int a[5] = { 1, 2, 3, 4, 5 };
651  EXPECT_THAT(a, ElementsAreArray(
652      { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
653  EXPECT_THAT(a, Not(ElementsAreArray(
654      { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
655}
656
657TEST(ElementsAreArrayTest,
658     TakesInitializerListOfDifferentTypedMatchers) {
659  const int a[5] = { 1, 2, 3, 4, 5 };
660  // The compiler cannot infer the type of the initializer list if its
661  // elements have different types.  We must explicitly specify the
662  // unified element type in this case.
663  EXPECT_THAT(a, ElementsAreArray<Matcher<int> >(
664      { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
665  EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int> >(
666      { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
667}
668
669#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
670
671TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
672  const int a[] = { 1, 2, 3 };
673  const Matcher<int> kMatchers[] = { Eq(1), Eq(2), Eq(3) };
674  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
675  const vector<Matcher<int> > expected(
676      kMatchers, kMatchers + GTEST_ARRAY_SIZE_(kMatchers));
677  EXPECT_THAT(test_vector, ElementsAreArray(expected));
678  test_vector.push_back(4);
679  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
680}
681
682TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
683  const int a[] = { 1, 2, 3 };
684  const vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
685  const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
686  EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
687  // Pointers are iterators, too.
688  EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a)));
689  // The empty range of NULL pointers should also be okay.
690  int* const null_int = NULL;
691  EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
692  EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
693}
694
695// Since ElementsAre() and ElementsAreArray() share much of the
696// implementation, we only do a sanity test for native arrays here.
697TEST(ElementsAreArrayTest, WorksWithNativeArray) {
698  ::std::string a[] = { "hi", "ho" };
699  ::std::string b[] = { "hi", "ho" };
700
701  EXPECT_THAT(a, ElementsAreArray(b));
702  EXPECT_THAT(a, ElementsAreArray(b, 2));
703  EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
704}
705
706TEST(ElementsAreArrayTest, SourceLifeSpan) {
707  const int a[] = { 1, 2, 3 };
708  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
709  vector<int> expect(a, a + GTEST_ARRAY_SIZE_(a));
710  ElementsAreArrayMatcher<int> matcher_maker =
711      ElementsAreArray(expect.begin(), expect.end());
712  EXPECT_THAT(test_vector, matcher_maker);
713  // Changing in place the values that initialized matcher_maker should not
714  // affect matcher_maker anymore. It should have made its own copy of them.
715  typedef vector<int>::iterator Iter;
716  for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 10; }
717  EXPECT_THAT(test_vector, matcher_maker);
718  test_vector.push_back(3);
719  EXPECT_THAT(test_vector, Not(matcher_maker));
720}
721
722// Tests for the MATCHER*() macro family.
723
724// Tests that a simple MATCHER() definition works.
725
726MATCHER(IsEven, "") { return (arg % 2) == 0; }
727
728TEST(MatcherMacroTest, Works) {
729  const Matcher<int> m = IsEven();
730  EXPECT_TRUE(m.Matches(6));
731  EXPECT_FALSE(m.Matches(7));
732
733  EXPECT_EQ("is even", Describe(m));
734  EXPECT_EQ("not (is even)", DescribeNegation(m));
735  EXPECT_EQ("", Explain(m, 6));
736  EXPECT_EQ("", Explain(m, 7));
737}
738
739// This also tests that the description string can reference 'negation'.
740MATCHER(IsEven2, negation ? "is odd" : "is even") {
741  if ((arg % 2) == 0) {
742    // Verifies that we can stream to result_listener, a listener
743    // supplied by the MATCHER macro implicitly.
744    *result_listener << "OK";
745    return true;
746  } else {
747    *result_listener << "% 2 == " << (arg % 2);
748    return false;
749  }
750}
751
752// This also tests that the description string can reference matcher
753// parameters.
754MATCHER_P2(EqSumOf, x, y,
755           string(negation ? "doesn't equal" : "equals") + " the sum of " +
756           PrintToString(x) + " and " + PrintToString(y)) {
757  if (arg == (x + y)) {
758    *result_listener << "OK";
759    return true;
760  } else {
761    // Verifies that we can stream to the underlying stream of
762    // result_listener.
763    if (result_listener->stream() != NULL) {
764      *result_listener->stream() << "diff == " << (x + y - arg);
765    }
766    return false;
767  }
768}
769
770// Tests that the matcher description can reference 'negation' and the
771// matcher parameters.
772TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
773  const Matcher<int> m1 = IsEven2();
774  EXPECT_EQ("is even", Describe(m1));
775  EXPECT_EQ("is odd", DescribeNegation(m1));
776
777  const Matcher<int> m2 = EqSumOf(5, 9);
778  EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
779  EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
780}
781
782// Tests explaining match result in a MATCHER* macro.
783TEST(MatcherMacroTest, CanExplainMatchResult) {
784  const Matcher<int> m1 = IsEven2();
785  EXPECT_EQ("OK", Explain(m1, 4));
786  EXPECT_EQ("% 2 == 1", Explain(m1, 5));
787
788  const Matcher<int> m2 = EqSumOf(1, 2);
789  EXPECT_EQ("OK", Explain(m2, 3));
790  EXPECT_EQ("diff == -1", Explain(m2, 4));
791}
792
793// Tests that the body of MATCHER() can reference the type of the
794// value being matched.
795
796MATCHER(IsEmptyString, "") {
797  StaticAssertTypeEq< ::std::string, arg_type>();
798  return arg == "";
799}
800
801MATCHER(IsEmptyStringByRef, "") {
802  StaticAssertTypeEq<const ::std::string&, arg_type>();
803  return arg == "";
804}
805
806TEST(MatcherMacroTest, CanReferenceArgType) {
807  const Matcher< ::std::string> m1 = IsEmptyString();
808  EXPECT_TRUE(m1.Matches(""));
809
810  const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
811  EXPECT_TRUE(m2.Matches(""));
812}
813
814// Tests that MATCHER() can be used in a namespace.
815
816namespace matcher_test {
817MATCHER(IsOdd, "") { return (arg % 2) != 0; }
818}  // namespace matcher_test
819
820TEST(MatcherMacroTest, WorksInNamespace) {
821  Matcher<int> m = matcher_test::IsOdd();
822  EXPECT_FALSE(m.Matches(4));
823  EXPECT_TRUE(m.Matches(5));
824}
825
826// Tests that Value() can be used to compose matchers.
827MATCHER(IsPositiveOdd, "") {
828  return Value(arg, matcher_test::IsOdd()) && arg > 0;
829}
830
831TEST(MatcherMacroTest, CanBeComposedUsingValue) {
832  EXPECT_THAT(3, IsPositiveOdd());
833  EXPECT_THAT(4, Not(IsPositiveOdd()));
834  EXPECT_THAT(-1, Not(IsPositiveOdd()));
835}
836
837// Tests that a simple MATCHER_P() definition works.
838
839MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
840
841TEST(MatcherPMacroTest, Works) {
842  const Matcher<int> m = IsGreaterThan32And(5);
843  EXPECT_TRUE(m.Matches(36));
844  EXPECT_FALSE(m.Matches(5));
845
846  EXPECT_EQ("is greater than 32 and 5", Describe(m));
847  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
848  EXPECT_EQ("", Explain(m, 36));
849  EXPECT_EQ("", Explain(m, 5));
850}
851
852// Tests that the description is calculated correctly from the matcher name.
853MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
854
855TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
856  const Matcher<int> m = _is_Greater_Than32and_(5);
857
858  EXPECT_EQ("is greater than 32 and 5", Describe(m));
859  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
860  EXPECT_EQ("", Explain(m, 36));
861  EXPECT_EQ("", Explain(m, 5));
862}
863
864// Tests that a MATCHER_P matcher can be explicitly instantiated with
865// a reference parameter type.
866
867class UncopyableFoo {
868 public:
869  explicit UncopyableFoo(char value) : value_(value) {}
870 private:
871  UncopyableFoo(const UncopyableFoo&);
872  void operator=(const UncopyableFoo&);
873
874  char value_;
875};
876
877MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
878
879TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
880  UncopyableFoo foo1('1'), foo2('2');
881  const Matcher<const UncopyableFoo&> m =
882      ReferencesUncopyable<const UncopyableFoo&>(foo1);
883
884  EXPECT_TRUE(m.Matches(foo1));
885  EXPECT_FALSE(m.Matches(foo2));
886
887  // We don't want the address of the parameter printed, as most
888  // likely it will just annoy the user.  If the address is
889  // interesting, the user should consider passing the parameter by
890  // pointer instead.
891  EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
892}
893
894
895// Tests that the body of MATCHER_Pn() can reference the parameter
896// types.
897
898MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
899  StaticAssertTypeEq<int, foo_type>();
900  StaticAssertTypeEq<long, bar_type>();  // NOLINT
901  StaticAssertTypeEq<char, baz_type>();
902  return arg == 0;
903}
904
905TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
906  EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
907}
908
909// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
910// reference parameter types.
911
912MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
913  return &arg == &variable1 || &arg == &variable2;
914}
915
916TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
917  UncopyableFoo foo1('1'), foo2('2'), foo3('3');
918  const Matcher<const UncopyableFoo&> m =
919      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
920
921  EXPECT_TRUE(m.Matches(foo1));
922  EXPECT_TRUE(m.Matches(foo2));
923  EXPECT_FALSE(m.Matches(foo3));
924}
925
926TEST(MatcherPnMacroTest,
927     GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
928  UncopyableFoo foo1('1'), foo2('2');
929  const Matcher<const UncopyableFoo&> m =
930      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
931
932  // We don't want the addresses of the parameters printed, as most
933  // likely they will just annoy the user.  If the addresses are
934  // interesting, the user should consider passing the parameters by
935  // pointers instead.
936  EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
937            Describe(m));
938}
939
940// Tests that a simple MATCHER_P2() definition works.
941
942MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
943
944TEST(MatcherPnMacroTest, Works) {
945  const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT
946  EXPECT_TRUE(m.Matches(36L));
947  EXPECT_FALSE(m.Matches(15L));
948
949  EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
950  EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
951  EXPECT_EQ("", Explain(m, 36L));
952  EXPECT_EQ("", Explain(m, 15L));
953}
954
955// Tests that MATCHER*() definitions can be overloaded on the number
956// of parameters; also tests MATCHER_Pn() where n >= 3.
957
958MATCHER(EqualsSumOf, "") { return arg == 0; }
959MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
960MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
961MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
962MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
963MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
964MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
965  return arg == a + b + c + d + e + f;
966}
967MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
968  return arg == a + b + c + d + e + f + g;
969}
970MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
971  return arg == a + b + c + d + e + f + g + h;
972}
973MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
974  return arg == a + b + c + d + e + f + g + h + i;
975}
976MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
977  return arg == a + b + c + d + e + f + g + h + i + j;
978}
979
980TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
981  EXPECT_THAT(0, EqualsSumOf());
982  EXPECT_THAT(1, EqualsSumOf(1));
983  EXPECT_THAT(12, EqualsSumOf(10, 2));
984  EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
985  EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
986  EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
987  EXPECT_THAT("abcdef",
988              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
989  EXPECT_THAT("abcdefg",
990              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
991  EXPECT_THAT("abcdefgh",
992              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
993                          "h"));
994  EXPECT_THAT("abcdefghi",
995              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
996                          "h", 'i'));
997  EXPECT_THAT("abcdefghij",
998              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
999                          "h", 'i', ::std::string("j")));
1000
1001  EXPECT_THAT(1, Not(EqualsSumOf()));
1002  EXPECT_THAT(-1, Not(EqualsSumOf(1)));
1003  EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
1004  EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
1005  EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
1006  EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
1007  EXPECT_THAT("abcdef ",
1008              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
1009  EXPECT_THAT("abcdefg ",
1010              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f',
1011                              'g')));
1012  EXPECT_THAT("abcdefgh ",
1013              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
1014                              "h")));
1015  EXPECT_THAT("abcdefghi ",
1016              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
1017                              "h", 'i')));
1018  EXPECT_THAT("abcdefghij ",
1019              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
1020                              "h", 'i', ::std::string("j"))));
1021}
1022
1023// Tests that a MATCHER_Pn() definition can be instantiated with any
1024// compatible parameter types.
1025TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
1026  EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
1027  EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
1028
1029  EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
1030  EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
1031}
1032
1033// Tests that the matcher body can promote the parameter types.
1034
1035MATCHER_P2(EqConcat, prefix, suffix, "") {
1036  // The following lines promote the two parameters to desired types.
1037  std::string prefix_str(prefix);
1038  char suffix_char = static_cast<char>(suffix);
1039  return arg == prefix_str + suffix_char;
1040}
1041
1042TEST(MatcherPnMacroTest, SimpleTypePromotion) {
1043  Matcher<std::string> no_promo =
1044      EqConcat(std::string("foo"), 't');
1045  Matcher<const std::string&> promo =
1046      EqConcat("foo", static_cast<int>('t'));
1047  EXPECT_FALSE(no_promo.Matches("fool"));
1048  EXPECT_FALSE(promo.Matches("fool"));
1049  EXPECT_TRUE(no_promo.Matches("foot"));
1050  EXPECT_TRUE(promo.Matches("foot"));
1051}
1052
1053// Verifies the type of a MATCHER*.
1054
1055TEST(MatcherPnMacroTest, TypesAreCorrect) {
1056  // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
1057  EqualsSumOfMatcher a0 = EqualsSumOf();
1058
1059  // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
1060  EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
1061
1062  // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
1063  // variable, and so on.
1064  EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
1065  EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
1066  EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
1067  EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
1068      EqualsSumOf(1, 2, 3, 4, '5');
1069  EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
1070      EqualsSumOf(1, 2, 3, 4, 5, '6');
1071  EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
1072      EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
1073  EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
1074      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
1075  EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
1076      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
1077  EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
1078      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
1079
1080  // Avoid "unused variable" warnings.
1081  (void)a0;
1082  (void)a1;
1083  (void)a2;
1084  (void)a3;
1085  (void)a4;
1086  (void)a5;
1087  (void)a6;
1088  (void)a7;
1089  (void)a8;
1090  (void)a9;
1091  (void)a10;
1092}
1093
1094// Tests that matcher-typed parameters can be used in Value() inside a
1095// MATCHER_Pn definition.
1096
1097// Succeeds if arg matches exactly 2 of the 3 matchers.
1098MATCHER_P3(TwoOf, m1, m2, m3, "") {
1099  const int count = static_cast<int>(Value(arg, m1))
1100      + static_cast<int>(Value(arg, m2)) + static_cast<int>(Value(arg, m3));
1101  return count == 2;
1102}
1103
1104TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
1105  EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
1106  EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
1107}
1108
1109// Tests Contains().
1110
1111TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
1112  list<int> some_list;
1113  some_list.push_back(3);
1114  some_list.push_back(1);
1115  some_list.push_back(2);
1116  EXPECT_THAT(some_list, Contains(1));
1117  EXPECT_THAT(some_list, Contains(Gt(2.5)));
1118  EXPECT_THAT(some_list, Contains(Eq(2.0f)));
1119
1120  list<string> another_list;
1121  another_list.push_back("fee");
1122  another_list.push_back("fie");
1123  another_list.push_back("foe");
1124  another_list.push_back("fum");
1125  EXPECT_THAT(another_list, Contains(string("fee")));
1126}
1127
1128TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
1129  list<int> some_list;
1130  some_list.push_back(3);
1131  some_list.push_back(1);
1132  EXPECT_THAT(some_list, Not(Contains(4)));
1133}
1134
1135TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
1136  set<int> some_set;
1137  some_set.insert(3);
1138  some_set.insert(1);
1139  some_set.insert(2);
1140  EXPECT_THAT(some_set, Contains(Eq(1.0)));
1141  EXPECT_THAT(some_set, Contains(Eq(3.0f)));
1142  EXPECT_THAT(some_set, Contains(2));
1143
1144  set<const char*> another_set;
1145  another_set.insert("fee");
1146  another_set.insert("fie");
1147  another_set.insert("foe");
1148  another_set.insert("fum");
1149  EXPECT_THAT(another_set, Contains(Eq(string("fum"))));
1150}
1151
1152TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
1153  set<int> some_set;
1154  some_set.insert(3);
1155  some_set.insert(1);
1156  EXPECT_THAT(some_set, Not(Contains(4)));
1157
1158  set<const char*> c_string_set;
1159  c_string_set.insert("hello");
1160  EXPECT_THAT(c_string_set, Not(Contains(string("hello").c_str())));
1161}
1162
1163TEST(ContainsTest, ExplainsMatchResultCorrectly) {
1164  const int a[2] = { 1, 2 };
1165  Matcher<const int (&)[2]> m = Contains(2);
1166  EXPECT_EQ("whose element #1 matches", Explain(m, a));
1167
1168  m = Contains(3);
1169  EXPECT_EQ("", Explain(m, a));
1170
1171  m = Contains(GreaterThan(0));
1172  EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
1173
1174  m = Contains(GreaterThan(10));
1175  EXPECT_EQ("", Explain(m, a));
1176}
1177
1178TEST(ContainsTest, DescribesItselfCorrectly) {
1179  Matcher<vector<int> > m = Contains(1);
1180  EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
1181
1182  Matcher<vector<int> > m2 = Not(m);
1183  EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
1184}
1185
1186TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
1187  map<const char*, int> my_map;
1188  const char* bar = "a string";
1189  my_map[bar] = 2;
1190  EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
1191
1192  map<string, int> another_map;
1193  another_map["fee"] = 1;
1194  another_map["fie"] = 2;
1195  another_map["foe"] = 3;
1196  another_map["fum"] = 4;
1197  EXPECT_THAT(another_map, Contains(pair<const string, int>(string("fee"), 1)));
1198  EXPECT_THAT(another_map, Contains(pair<const string, int>("fie", 2)));
1199}
1200
1201TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
1202  map<int, int> some_map;
1203  some_map[1] = 11;
1204  some_map[2] = 22;
1205  EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
1206}
1207
1208TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
1209  const char* string_array[] = { "fee", "fie", "foe", "fum" };
1210  EXPECT_THAT(string_array, Contains(Eq(string("fum"))));
1211}
1212
1213TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
1214  int int_array[] = { 1, 2, 3, 4 };
1215  EXPECT_THAT(int_array, Not(Contains(5)));
1216}
1217
1218TEST(ContainsTest, AcceptsMatcher) {
1219  const int a[] = { 1, 2, 3 };
1220  EXPECT_THAT(a, Contains(Gt(2)));
1221  EXPECT_THAT(a, Not(Contains(Gt(4))));
1222}
1223
1224TEST(ContainsTest, WorksForNativeArrayAsTuple) {
1225  const int a[] = { 1, 2 };
1226  const int* const pointer = a;
1227  EXPECT_THAT(make_tuple(pointer, 2), Contains(1));
1228  EXPECT_THAT(make_tuple(pointer, 2), Not(Contains(Gt(3))));
1229}
1230
1231TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
1232  int a[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
1233  EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
1234  EXPECT_THAT(a, Contains(Contains(5)));
1235  EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
1236  EXPECT_THAT(a, Contains(Not(Contains(5))));
1237}
1238
1239TEST(AllOfTest, HugeMatcher) {
1240  // Verify that using AllOf with many arguments doesn't cause
1241  // the compiler to exceed template instantiation depth limit.
1242  EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
1243                                testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
1244}
1245
1246TEST(AnyOfTest, HugeMatcher) {
1247  // Verify that using AnyOf with many arguments doesn't cause
1248  // the compiler to exceed template instantiation depth limit.
1249  EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
1250                                testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
1251}
1252
1253namespace adl_test {
1254
1255// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
1256// don't issue unqualified recursive calls.  If they do, the argument dependent
1257// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
1258// as a candidate and the compilation will break due to an ambiguous overload.
1259
1260// The matcher must be in the same namespace as AllOf/AnyOf to make argument
1261// dependent lookup find those.
1262MATCHER(M, "") { return true; }
1263
1264template <typename T1, typename T2>
1265bool AllOf(const T1& t1, const T2& t2) { return true; }
1266
1267TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
1268  EXPECT_THAT(42, testing::AllOf(
1269      M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
1270}
1271
1272template <typename T1, typename T2> bool
1273AnyOf(const T1& t1, const T2& t2) { return true; }
1274
1275TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
1276  EXPECT_THAT(42, testing::AnyOf(
1277      M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
1278}
1279
1280}  // namespace adl_test
1281
1282#ifdef _MSC_VER
1283# pragma warning(pop)
1284#endif
1285
1286}  // namespace
trunk/3rdparty/googletest/googlemock/test/gmock-internal-utils_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the internal utilities.
35
36#include "gmock/internal/gmock-internal-utils.h"
37#include <stdlib.h>
38#include <map>
39#include <string>
40#include <sstream>
41#include <vector>
42#include "gmock/gmock.h"
43#include "gmock/internal/gmock-port.h"
44#include "gtest/gtest.h"
45#include "gtest/gtest-spi.h"
46
47// Indicates that this translation unit is part of Google Test's
48// implementation.  It must come before gtest-internal-inl.h is
49// included, or there will be a compiler error.  This trick is to
50// prevent a user from accidentally including gtest-internal-inl.h in
51// his code.
52#define GTEST_IMPLEMENTATION_ 1
53#include "src/gtest-internal-inl.h"
54#undef GTEST_IMPLEMENTATION_
55
56#if GTEST_OS_CYGWIN
57# include <sys/types.h>  // For ssize_t. NOLINT
58#endif
59
60class ProtocolMessage;
61
62namespace proto2 {
63class Message;
64}  // namespace proto2
65
66namespace testing {
67namespace internal {
68
69namespace {
70
71TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
72  EXPECT_EQ("", ConvertIdentifierNameToWords(""));
73  EXPECT_EQ("", ConvertIdentifierNameToWords("_"));
74  EXPECT_EQ("", ConvertIdentifierNameToWords("__"));
75}
76
77TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) {
78  EXPECT_EQ("1", ConvertIdentifierNameToWords("_1"));
79  EXPECT_EQ("2", ConvertIdentifierNameToWords("2_"));
80  EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_"));
81  EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56"));
82}
83
84TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) {
85  EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord"));
86  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar"));
87  EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_"));
88  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_"));
89  EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar"));
90}
91
92TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) {
93  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar"));
94  EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_"));
95  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_"));
96  EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar"));
97}
98
99TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
100  EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123"));
101  EXPECT_EQ("chapter 11 section 1",
102            ConvertIdentifierNameToWords("_Chapter11Section_1_"));
103}
104
105TEST(PointeeOfTest, WorksForSmartPointers) {
106  CompileAssertTypesEqual<const char,
107      PointeeOf<internal::linked_ptr<const char> >::type>();
108#if GTEST_HAS_STD_UNIQUE_PTR_
109  CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>();
110#endif  // GTEST_HAS_STD_UNIQUE_PTR_
111#if GTEST_HAS_STD_SHARED_PTR_
112  CompileAssertTypesEqual<std::string,
113                          PointeeOf<std::shared_ptr<std::string> >::type>();
114#endif  // GTEST_HAS_STD_SHARED_PTR_
115}
116
117TEST(PointeeOfTest, WorksForRawPointers) {
118  CompileAssertTypesEqual<int, PointeeOf<int*>::type>();
119  CompileAssertTypesEqual<const char, PointeeOf<const char*>::type>();
120  CompileAssertTypesEqual<void, PointeeOf<void*>::type>();
121}
122
123TEST(GetRawPointerTest, WorksForSmartPointers) {
124#if GTEST_HAS_STD_UNIQUE_PTR_
125  const char* const raw_p1 = new const char('a');  // NOLINT
126  const std::unique_ptr<const char> p1(raw_p1);
127  EXPECT_EQ(raw_p1, GetRawPointer(p1));
128#endif  // GTEST_HAS_STD_UNIQUE_PTR_
129#if GTEST_HAS_STD_SHARED_PTR_
130  double* const raw_p2 = new double(2.5);  // NOLINT
131  const std::shared_ptr<double> p2(raw_p2);
132  EXPECT_EQ(raw_p2, GetRawPointer(p2));
133#endif  // GTEST_HAS_STD_SHARED_PTR_
134
135  const char* const raw_p4 = new const char('a');  // NOLINT
136  const internal::linked_ptr<const char> p4(raw_p4);
137  EXPECT_EQ(raw_p4, GetRawPointer(p4));
138}
139
140TEST(GetRawPointerTest, WorksForRawPointers) {
141  int* p = NULL;
142  // Don't use EXPECT_EQ as no NULL-testing magic on Symbian.
143  EXPECT_TRUE(NULL == GetRawPointer(p));
144  int n = 1;
145  EXPECT_EQ(&n, GetRawPointer(&n));
146}
147
148// Tests KindOf<T>.
149
150class Base {};
151class Derived : public Base {};
152
153TEST(KindOfTest, Bool) {
154  EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool));  // NOLINT
155}
156
157TEST(KindOfTest, Integer) {
158  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));  // NOLINT
159  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));  // NOLINT
160  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));  // NOLINT
161  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));  // NOLINT
162  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));  // NOLINT
163  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));  // NOLINT
164  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));  // NOLINT
165  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));  // NOLINT
166  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));  // NOLINT
167  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));  // NOLINT
168  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(Int64));  // NOLINT
169  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64));  // NOLINT
170  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));  // NOLINT
171#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
172  // ssize_t is not defined on Windows and possibly some other OSes.
173  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t));  // NOLINT
174#endif
175}
176
177TEST(KindOfTest, FloatingPoint) {
178  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));  // NOLINT
179  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));  // NOLINT
180  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double));  // NOLINT
181}
182
183TEST(KindOfTest, Other) {
184  EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));  // NOLINT
185  EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**));  // NOLINT
186  EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));  // NOLINT
187}
188
189// Tests LosslessArithmeticConvertible<T, U>.
190
191TEST(LosslessArithmeticConvertibleTest, BoolToBool) {
192  EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value));
193}
194
195TEST(LosslessArithmeticConvertibleTest, BoolToInteger) {
196  EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value));
197  EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value));
198  EXPECT_TRUE(
199      (LosslessArithmeticConvertible<bool, unsigned long>::value));  // NOLINT
200}
201
202TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) {
203  EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value));
204  EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value));
205}
206
207TEST(LosslessArithmeticConvertibleTest, IntegerToBool) {
208  EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value));
209  EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value));
210}
211
212TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
213  // Unsigned => larger signed is fine.
214  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
215
216  // Unsigned => larger unsigned is fine.
217  EXPECT_TRUE(
218      (LosslessArithmeticConvertible<unsigned short, UInt64>::value)); // NOLINT
219
220  // Signed => unsigned is not fine.
221  EXPECT_FALSE((LosslessArithmeticConvertible<short, UInt64>::value)); // NOLINT
222  EXPECT_FALSE((LosslessArithmeticConvertible<
223      signed char, unsigned int>::value));  // NOLINT
224
225  // Same size and same signedness: fine too.
226  EXPECT_TRUE((LosslessArithmeticConvertible<
227               unsigned char, unsigned char>::value));
228  EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
229  EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
230  EXPECT_TRUE((LosslessArithmeticConvertible<
231               unsigned long, unsigned long>::value));  // NOLINT
232
233  // Same size, different signedness: not fine.
234  EXPECT_FALSE((LosslessArithmeticConvertible<
235                unsigned char, signed char>::value));
236  EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
237  EXPECT_FALSE((LosslessArithmeticConvertible<UInt64, Int64>::value));
238
239  // Larger size => smaller size is not fine.
240  EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value));  // NOLINT
241  EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
242  EXPECT_FALSE((LosslessArithmeticConvertible<Int64, unsigned int>::value));
243}
244
245TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
246  // Integers cannot be losslessly converted to floating-points, as
247  // the format of the latter is implementation-defined.
248  EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
249  EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
250  EXPECT_FALSE((LosslessArithmeticConvertible<
251                short, long double>::value));  // NOLINT
252}
253
254TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
255  EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value));
256  EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value));
257}
258
259TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
260  EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value));  // NOLINT
261  EXPECT_FALSE((LosslessArithmeticConvertible<double, Int64>::value));
262  EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
263}
264
265TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
266  // Smaller size => larger size is fine.
267  EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value));
268  EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value));
269  EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value));
270
271  // Same size: fine.
272  EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value));
273  EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value));
274
275  // Larger size => smaller size is not fine.
276  EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
277  GTEST_INTENTIONAL_CONST_COND_PUSH_()
278  if (sizeof(double) == sizeof(long double)) {  // NOLINT
279  GTEST_INTENTIONAL_CONST_COND_POP_()
280    // In some implementations (e.g. MSVC), double and long double
281    // have the same size.
282    EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
283  } else {
284    EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value));
285  }
286}
287
288// Tests the TupleMatches() template function.
289
290TEST(TupleMatchesTest, WorksForSize0) {
291  tuple<> matchers;
292  tuple<> values;
293
294  EXPECT_TRUE(TupleMatches(matchers, values));
295}
296
297TEST(TupleMatchesTest, WorksForSize1) {
298  tuple<Matcher<int> > matchers(Eq(1));
299  tuple<int> values1(1),
300      values2(2);
301
302  EXPECT_TRUE(TupleMatches(matchers, values1));
303  EXPECT_FALSE(TupleMatches(matchers, values2));
304}
305
306TEST(TupleMatchesTest, WorksForSize2) {
307  tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a'));
308  tuple<int, char> values1(1, 'a'),
309      values2(1, 'b'),
310      values3(2, 'a'),
311      values4(2, 'b');
312
313  EXPECT_TRUE(TupleMatches(matchers, values1));
314  EXPECT_FALSE(TupleMatches(matchers, values2));
315  EXPECT_FALSE(TupleMatches(matchers, values3));
316  EXPECT_FALSE(TupleMatches(matchers, values4));
317}
318
319TEST(TupleMatchesTest, WorksForSize5) {
320  tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>,  // NOLINT
321      Matcher<string> >
322      matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
323  tuple<int, char, bool, long, string>  // NOLINT
324      values1(1, 'a', true, 2L, "hi"),
325      values2(1, 'a', true, 2L, "hello"),
326      values3(2, 'a', true, 2L, "hi");
327
328  EXPECT_TRUE(TupleMatches(matchers, values1));
329  EXPECT_FALSE(TupleMatches(matchers, values2));
330  EXPECT_FALSE(TupleMatches(matchers, values3));
331}
332
333// Tests that Assert(true, ...) succeeds.
334TEST(AssertTest, SucceedsOnTrue) {
335  Assert(true, __FILE__, __LINE__, "This should succeed.");
336  Assert(true, __FILE__, __LINE__);  // This should succeed too.
337}
338
339// Tests that Assert(false, ...) generates a fatal failure.
340TEST(AssertTest, FailsFatallyOnFalse) {
341  EXPECT_DEATH_IF_SUPPORTED({
342    Assert(false, __FILE__, __LINE__, "This should fail.");
343  }, "");
344
345  EXPECT_DEATH_IF_SUPPORTED({
346    Assert(false, __FILE__, __LINE__);
347  }, "");
348}
349
350// Tests that Expect(true, ...) succeeds.
351TEST(ExpectTest, SucceedsOnTrue) {
352  Expect(true, __FILE__, __LINE__, "This should succeed.");
353  Expect(true, __FILE__, __LINE__);  // This should succeed too.
354}
355
356// Tests that Expect(false, ...) generates a non-fatal failure.
357TEST(ExpectTest, FailsNonfatallyOnFalse) {
358  EXPECT_NONFATAL_FAILURE({  // NOLINT
359    Expect(false, __FILE__, __LINE__, "This should fail.");
360  }, "This should fail");
361
362  EXPECT_NONFATAL_FAILURE({  // NOLINT
363    Expect(false, __FILE__, __LINE__);
364  }, "Expectation failed");
365}
366
367// Tests LogIsVisible().
368
369class LogIsVisibleTest : public ::testing::Test {
370 protected:
371  virtual void SetUp() {
372    original_verbose_ = GMOCK_FLAG(verbose);
373  }
374
375  virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; }
376
377  string original_verbose_;
378};
379
380TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
381  GMOCK_FLAG(verbose) = kInfoVerbosity;
382  EXPECT_TRUE(LogIsVisible(kInfo));
383  EXPECT_TRUE(LogIsVisible(kWarning));
384}
385
386TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
387  GMOCK_FLAG(verbose) = kErrorVerbosity;
388  EXPECT_FALSE(LogIsVisible(kInfo));
389  EXPECT_FALSE(LogIsVisible(kWarning));
390}
391
392TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
393  GMOCK_FLAG(verbose) = kWarningVerbosity;
394  EXPECT_FALSE(LogIsVisible(kInfo));
395  EXPECT_TRUE(LogIsVisible(kWarning));
396}
397
398#if GTEST_HAS_STREAM_REDIRECTION
399
400// Tests the Log() function.
401
402// Verifies that Log() behaves correctly for the given verbosity level
403// and log severity.
404void TestLogWithSeverity(const string& verbosity, LogSeverity severity,
405                         bool should_print) {
406  const string old_flag = GMOCK_FLAG(verbose);
407  GMOCK_FLAG(verbose) = verbosity;
408  CaptureStdout();
409  Log(severity, "Test log.\n", 0);
410  if (should_print) {
411    EXPECT_THAT(GetCapturedStdout().c_str(),
412                ContainsRegex(
413                    severity == kWarning ?
414                    "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" :
415                    "^\nTest log\\.\nStack trace:\n"));
416  } else {
417    EXPECT_STREQ("", GetCapturedStdout().c_str());
418  }
419  GMOCK_FLAG(verbose) = old_flag;
420}
421
422// Tests that when the stack_frames_to_skip parameter is negative,
423// Log() doesn't include the stack trace in the output.
424TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
425  const string saved_flag = GMOCK_FLAG(verbose);
426  GMOCK_FLAG(verbose) = kInfoVerbosity;
427  CaptureStdout();
428  Log(kInfo, "Test log.\n", -1);
429  EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
430  GMOCK_FLAG(verbose) = saved_flag;
431}
432
433struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
434  virtual string CurrentStackTrace(int max_depth, int skip_count) {
435    return (testing::Message() << max_depth << "::" << skip_count << "\n")
436        .GetString();
437  }
438  virtual void UponLeavingGTest() {}
439};
440
441// Tests that in opt mode, a positive stack_frames_to_skip argument is
442// treated as 0.
443TEST(LogTest, NoSkippingStackFrameInOptMode) {
444  MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;
445  GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);
446
447  CaptureStdout();
448  Log(kWarning, "Test log.\n", 100);
449  const string log = GetCapturedStdout();
450
451  string expected_trace =
452      (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString();
453  string expected_message =
454      "\nGMOCK WARNING:\n"
455      "Test log.\n"
456      "Stack trace:\n" +
457      expected_trace;
458  EXPECT_THAT(log, HasSubstr(expected_message));
459  int skip_count = atoi(log.substr(expected_message.size()).c_str());
460
461# if defined(NDEBUG)
462  // In opt mode, no stack frame should be skipped.
463  const int expected_skip_count = 0;
464# else
465  // In dbg mode, the stack frames should be skipped.
466  const int expected_skip_count = 100;
467# endif
468
469  // Note that each inner implementation layer will +1 the number to remove
470  // itself from the trace. This means that the value is a little higher than
471  // expected, but close enough.
472  EXPECT_THAT(skip_count,
473              AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));
474
475  // Restores the default OS stack trace getter.
476  GetUnitTestImpl()->set_os_stack_trace_getter(NULL);
477}
478
479// Tests that all logs are printed when the value of the
480// --gmock_verbose flag is "info".
481TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
482  TestLogWithSeverity(kInfoVerbosity, kInfo, true);
483  TestLogWithSeverity(kInfoVerbosity, kWarning, true);
484}
485
486// Tests that only warnings are printed when the value of the
487// --gmock_verbose flag is "warning".
488TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
489  TestLogWithSeverity(kWarningVerbosity, kInfo, false);
490  TestLogWithSeverity(kWarningVerbosity, kWarning, true);
491}
492
493// Tests that no logs are printed when the value of the
494// --gmock_verbose flag is "error".
495TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
496  TestLogWithSeverity(kErrorVerbosity, kInfo, false);
497  TestLogWithSeverity(kErrorVerbosity, kWarning, false);
498}
499
500// Tests that only warnings are printed when the value of the
501// --gmock_verbose flag is invalid.
502TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
503  TestLogWithSeverity("invalid", kInfo, false);
504  TestLogWithSeverity("invalid", kWarning, true);
505}
506
507#endif  // GTEST_HAS_STREAM_REDIRECTION
508
509TEST(TypeTraitsTest, true_type) {
510  EXPECT_TRUE(true_type::value);
511}
512
513TEST(TypeTraitsTest, false_type) {
514  EXPECT_FALSE(false_type::value);
515}
516
517TEST(TypeTraitsTest, is_reference) {
518  EXPECT_FALSE(is_reference<int>::value);
519  EXPECT_FALSE(is_reference<char*>::value);
520  EXPECT_TRUE(is_reference<const int&>::value);
521}
522
523TEST(TypeTraitsTest, is_pointer) {
524  EXPECT_FALSE(is_pointer<int>::value);
525  EXPECT_FALSE(is_pointer<char&>::value);
526  EXPECT_TRUE(is_pointer<const int*>::value);
527}
528
529TEST(TypeTraitsTest, type_equals) {
530  EXPECT_FALSE((type_equals<int, const int>::value));
531  EXPECT_FALSE((type_equals<int, int&>::value));
532  EXPECT_FALSE((type_equals<int, double>::value));
533  EXPECT_TRUE((type_equals<char, char>::value));
534}
535
536TEST(TypeTraitsTest, remove_reference) {
537  EXPECT_TRUE((type_equals<char, remove_reference<char&>::type>::value));
538  EXPECT_TRUE((type_equals<const int,
539               remove_reference<const int&>::type>::value));
540  EXPECT_TRUE((type_equals<int, remove_reference<int>::type>::value));
541  EXPECT_TRUE((type_equals<double*, remove_reference<double*>::type>::value));
542}
543
544#if GTEST_HAS_STREAM_REDIRECTION
545
546// Verifies that Log() behaves correctly for the given verbosity level
547// and log severity.
548std::string GrabOutput(void(*logger)(), const char* verbosity) {
549  const string saved_flag = GMOCK_FLAG(verbose);
550  GMOCK_FLAG(verbose) = verbosity;
551  CaptureStdout();
552  logger();
553  GMOCK_FLAG(verbose) = saved_flag;
554  return GetCapturedStdout();
555}
556
557class DummyMock {
558 public:
559  MOCK_METHOD0(TestMethod, void());
560  MOCK_METHOD1(TestMethodArg, void(int dummy));
561};
562
563void ExpectCallLogger() {
564  DummyMock mock;
565  EXPECT_CALL(mock, TestMethod());
566  mock.TestMethod();
567};
568
569// Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
570TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
571  EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),
572              HasSubstr("EXPECT_CALL(mock, TestMethod())"));
573}
574
575// Verifies that EXPECT_CALL doesn't log
576// if the --gmock_verbose flag is set to "warning".
577TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
578  EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str());
579}
580
581// Verifies that EXPECT_CALL doesn't log
582// if the --gmock_verbose flag is set to "error".
583TEST(ExpectCallTest,  DoesNotLogWhenVerbosityIsError) {
584  EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
585}
586
587void OnCallLogger() {
588  DummyMock mock;
589  ON_CALL(mock, TestMethod());
590};
591
592// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
593TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
594  EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),
595              HasSubstr("ON_CALL(mock, TestMethod())"));
596}
597
598// Verifies that ON_CALL doesn't log
599// if the --gmock_verbose flag is set to "warning".
600TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {
601  EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str());
602}
603
604// Verifies that ON_CALL doesn't log if
605// the --gmock_verbose flag is set to "error".
606TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
607  EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str());
608}
609
610void OnCallAnyArgumentLogger() {
611  DummyMock mock;
612  ON_CALL(mock, TestMethodArg(_));
613}
614
615// Verifies that ON_CALL prints provided _ argument.
616TEST(OnCallTest, LogsAnythingArgument) {
617  EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),
618              HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
619}
620
621#endif  // GTEST_HAS_STREAM_REDIRECTION
622
623// Tests StlContainerView.
624
625TEST(StlContainerViewTest, WorksForStlContainer) {
626  StaticAssertTypeEq<std::vector<int>,
627      StlContainerView<std::vector<int> >::type>();
628  StaticAssertTypeEq<const std::vector<double>&,
629      StlContainerView<std::vector<double> >::const_reference>();
630
631  typedef std::vector<char> Chars;
632  Chars v1;
633  const Chars& v2(StlContainerView<Chars>::ConstReference(v1));
634  EXPECT_EQ(&v1, &v2);
635
636  v1.push_back('a');
637  Chars v3 = StlContainerView<Chars>::Copy(v1);
638  EXPECT_THAT(v3, Eq(v3));
639}
640
641TEST(StlContainerViewTest, WorksForStaticNativeArray) {
642  StaticAssertTypeEq<NativeArray<int>,
643      StlContainerView<int[3]>::type>();
644  StaticAssertTypeEq<NativeArray<double>,
645      StlContainerView<const double[4]>::type>();
646  StaticAssertTypeEq<NativeArray<char[3]>,
647      StlContainerView<const char[2][3]>::type>();
648
649  StaticAssertTypeEq<const NativeArray<int>,
650      StlContainerView<int[2]>::const_reference>();
651
652  int a1[3] = { 0, 1, 2 };
653  NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
654  EXPECT_EQ(3U, a2.size());
655  EXPECT_EQ(a1, a2.begin());
656
657  const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1);
658  ASSERT_EQ(3U, a3.size());
659  EXPECT_EQ(0, a3.begin()[0]);
660  EXPECT_EQ(1, a3.begin()[1]);
661  EXPECT_EQ(2, a3.begin()[2]);
662
663  // Makes sure a1 and a3 aren't aliases.
664  a1[0] = 3;
665  EXPECT_EQ(0, a3.begin()[0]);
666}
667
668TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
669  StaticAssertTypeEq<NativeArray<int>,
670      StlContainerView<tuple<const int*, size_t> >::type>();
671  StaticAssertTypeEq<NativeArray<double>,
672      StlContainerView<tuple<linked_ptr<double>, int> >::type>();
673
674  StaticAssertTypeEq<const NativeArray<int>,
675      StlContainerView<tuple<const int*, int> >::const_reference>();
676
677  int a1[3] = { 0, 1, 2 };
678  const int* const p1 = a1;
679  NativeArray<int> a2 = StlContainerView<tuple<const int*, int> >::
680      ConstReference(make_tuple(p1, 3));
681  EXPECT_EQ(3U, a2.size());
682  EXPECT_EQ(a1, a2.begin());
683
684  const NativeArray<int> a3 = StlContainerView<tuple<int*, size_t> >::
685      Copy(make_tuple(static_cast<int*>(a1), 3));
686  ASSERT_EQ(3U, a3.size());
687  EXPECT_EQ(0, a3.begin()[0]);
688  EXPECT_EQ(1, a3.begin()[1]);
689  EXPECT_EQ(2, a3.begin()[2]);
690
691  // Makes sure a1 and a3 aren't aliases.
692  a1[0] = 3;
693  EXPECT_EQ(0, a3.begin()[0]);
694}
695
696}  // namespace
697}  // namespace internal
698}  // namespace testing
trunk/3rdparty/googletest/googlemock/test/gmock-matchers_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests some commonly used argument matchers.
35
36#include "gmock/gmock-matchers.h"
37#include "gmock/gmock-more-matchers.h"
38
39#include <string.h>
40#include <time.h>
41#include <deque>
42#include <functional>
43#include <iostream>
44#include <iterator>
45#include <limits>
46#include <list>
47#include <map>
48#include <set>
49#include <sstream>
50#include <string>
51#include <utility>
52#include <vector>
53#include "gmock/gmock.h"
54#include "gtest/gtest.h"
55#include "gtest/gtest-spi.h"
56
57#if GTEST_HAS_STD_FORWARD_LIST_
58# include <forward_list>  // NOLINT
59#endif
60
61namespace testing {
62
63namespace internal {
64GTEST_API_ string JoinAsTuple(const Strings& fields);
65}  // namespace internal
66
67namespace gmock_matchers_test {
68
69using std::greater;
70using std::less;
71using std::list;
72using std::make_pair;
73using std::map;
74using std::multimap;
75using std::multiset;
76using std::ostream;
77using std::pair;
78using std::set;
79using std::stringstream;
80using std::vector;
81using testing::A;
82using testing::AllArgs;
83using testing::AllOf;
84using testing::An;
85using testing::AnyOf;
86using testing::ByRef;
87using testing::ContainsRegex;
88using testing::DoubleEq;
89using testing::DoubleNear;
90using testing::EndsWith;
91using testing::Eq;
92using testing::ExplainMatchResult;
93using testing::Field;
94using testing::FloatEq;
95using testing::FloatNear;
96using testing::Ge;
97using testing::Gt;
98using testing::HasSubstr;
99using testing::IsEmpty;
100using testing::IsNull;
101using testing::Key;
102using testing::Le;
103using testing::Lt;
104using testing::MakeMatcher;
105using testing::MakePolymorphicMatcher;
106using testing::MatchResultListener;
107using testing::Matcher;
108using testing::MatcherCast;
109using testing::MatcherInterface;
110using testing::Matches;
111using testing::MatchesRegex;
112using testing::NanSensitiveDoubleEq;
113using testing::NanSensitiveDoubleNear;
114using testing::NanSensitiveFloatEq;
115using testing::NanSensitiveFloatNear;
116using testing::Ne;
117using testing::Not;
118using testing::NotNull;
119using testing::Pair;
120using testing::Pointee;
121using testing::Pointwise;
122using testing::PolymorphicMatcher;
123using testing::Property;
124using testing::Ref;
125using testing::ResultOf;
126using testing::SizeIs;
127using testing::StartsWith;
128using testing::StrCaseEq;
129using testing::StrCaseNe;
130using testing::StrEq;
131using testing::StrNe;
132using testing::StringMatchResultListener;
133using testing::Truly;
134using testing::TypedEq;
135using testing::UnorderedPointwise;
136using testing::Value;
137using testing::WhenSorted;
138using testing::WhenSortedBy;
139using testing::_;
140using testing::get;
141using testing::internal::DummyMatchResultListener;
142using testing::internal::ElementMatcherPair;
143using testing::internal::ElementMatcherPairs;
144using testing::internal::ExplainMatchFailureTupleTo;
145using testing::internal::FloatingEqMatcher;
146using testing::internal::FormatMatcherDescription;
147using testing::internal::IsReadableTypeName;
148using testing::internal::JoinAsTuple;
149using testing::internal::linked_ptr;
150using testing::internal::MatchMatrix;
151using testing::internal::RE;
152using testing::internal::scoped_ptr;
153using testing::internal::StreamMatchResultListener;
154using testing::internal::Strings;
155using testing::internal::linked_ptr;
156using testing::internal::scoped_ptr;
157using testing::internal::string;
158using testing::make_tuple;
159using testing::tuple;
160
161// For testing ExplainMatchResultTo().
162class GreaterThanMatcher : public MatcherInterface<int> {
163 public:
164  explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
165
166  virtual void DescribeTo(ostream* os) const {
167    *os << "is > " << rhs_;
168  }
169
170  virtual bool MatchAndExplain(int lhs,
171                               MatchResultListener* listener) const {
172    const int diff = lhs - rhs_;
173    if (diff > 0) {
174      *listener << "which is " << diff << " more than " << rhs_;
175    } else if (diff == 0) {
176      *listener << "which is the same as " << rhs_;
177    } else {
178      *listener << "which is " << -diff << " less than " << rhs_;
179    }
180
181    return lhs > rhs_;
182  }
183
184 private:
185  int rhs_;
186};
187
188Matcher<int> GreaterThan(int n) {
189  return MakeMatcher(new GreaterThanMatcher(n));
190}
191
192string OfType(const string& type_name) {
193#if GTEST_HAS_RTTI
194  return " (of type " + type_name + ")";
195#else
196  return "";
197#endif
198}
199
200// Returns the description of the given matcher.
201template <typename T>
202string Describe(const Matcher<T>& m) {
203  stringstream ss;
204  m.DescribeTo(&ss);
205  return ss.str();
206}
207
208// Returns the description of the negation of the given matcher.
209template <typename T>
210string DescribeNegation(const Matcher<T>& m) {
211  stringstream ss;
212  m.DescribeNegationTo(&ss);
213  return ss.str();
214}
215
216// Returns the reason why x matches, or doesn't match, m.
217template <typename MatcherType, typename Value>
218string Explain(const MatcherType& m, const Value& x) {
219  StringMatchResultListener listener;
220  ExplainMatchResult(m, x, &listener);
221  return listener.str();
222}
223
224TEST(MatchResultListenerTest, StreamingWorks) {
225  StringMatchResultListener listener;
226  listener << "hi" << 5;
227  EXPECT_EQ("hi5", listener.str());
228
229  listener.Clear();
230  EXPECT_EQ("", listener.str());
231
232  listener << 42;
233  EXPECT_EQ("42", listener.str());
234
235  // Streaming shouldn't crash when the underlying ostream is NULL.
236  DummyMatchResultListener dummy;
237  dummy << "hi" << 5;
238}
239
240TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
241  EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
242  EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
243
244  EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
245}
246
247TEST(MatchResultListenerTest, IsInterestedWorks) {
248  EXPECT_TRUE(StringMatchResultListener().IsInterested());
249  EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
250
251  EXPECT_FALSE(DummyMatchResultListener().IsInterested());
252  EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
253}
254
255// Makes sure that the MatcherInterface<T> interface doesn't
256// change.
257class EvenMatcherImpl : public MatcherInterface<int> {
258 public:
259  virtual bool MatchAndExplain(int x,
260                               MatchResultListener* /* listener */) const {
261    return x % 2 == 0;
262  }
263
264  virtual void DescribeTo(ostream* os) const {
265    *os << "is an even number";
266  }
267
268  // We deliberately don't define DescribeNegationTo() and
269  // ExplainMatchResultTo() here, to make sure the definition of these
270  // two methods is optional.
271};
272
273// Makes sure that the MatcherInterface API doesn't change.
274TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
275  EvenMatcherImpl m;
276}
277
278// Tests implementing a monomorphic matcher using MatchAndExplain().
279
280class NewEvenMatcherImpl : public MatcherInterface<int> {
281 public:
282  virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
283    const bool match = x % 2 == 0;
284    // Verifies that we can stream to a listener directly.
285    *listener << "value % " << 2;
286    if (listener->stream() != NULL) {
287      // Verifies that we can stream to a listener's underlying stream
288      // too.
289      *listener->stream() << " == " << (x % 2);
290    }
291    return match;
292  }
293
294  virtual void DescribeTo(ostream* os) const {
295    *os << "is an even number";
296  }
297};
298
299TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
300  Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
301  EXPECT_TRUE(m.Matches(2));
302  EXPECT_FALSE(m.Matches(3));
303  EXPECT_EQ("value % 2 == 0", Explain(m, 2));
304  EXPECT_EQ("value % 2 == 1", Explain(m, 3));
305}
306
307// Tests default-constructing a matcher.
308TEST(MatcherTest, CanBeDefaultConstructed) {
309  Matcher<double> m;
310}
311
312// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
313TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
314  const MatcherInterface<int>* impl = new EvenMatcherImpl;
315  Matcher<int> m(impl);
316  EXPECT_TRUE(m.Matches(4));
317  EXPECT_FALSE(m.Matches(5));
318}
319
320// Tests that value can be used in place of Eq(value).
321TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
322  Matcher<int> m1 = 5;
323  EXPECT_TRUE(m1.Matches(5));
324  EXPECT_FALSE(m1.Matches(6));
325}
326
327// Tests that NULL can be used in place of Eq(NULL).
328TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
329  Matcher<int*> m1 = NULL;
330  EXPECT_TRUE(m1.Matches(NULL));
331  int n = 0;
332  EXPECT_FALSE(m1.Matches(&n));
333}
334
335// Tests that matchers are copyable.
336TEST(MatcherTest, IsCopyable) {
337  // Tests the copy constructor.
338  Matcher<bool> m1 = Eq(false);
339  EXPECT_TRUE(m1.Matches(false));
340  EXPECT_FALSE(m1.Matches(true));
341
342  // Tests the assignment operator.
343  m1 = Eq(true);
344  EXPECT_TRUE(m1.Matches(true));
345  EXPECT_FALSE(m1.Matches(false));
346}
347
348// Tests that Matcher<T>::DescribeTo() calls
349// MatcherInterface<T>::DescribeTo().
350TEST(MatcherTest, CanDescribeItself) {
351  EXPECT_EQ("is an even number",
352            Describe(Matcher<int>(new EvenMatcherImpl)));
353}
354
355// Tests Matcher<T>::MatchAndExplain().
356TEST(MatcherTest, MatchAndExplain) {
357  Matcher<int> m = GreaterThan(0);
358  StringMatchResultListener listener1;
359  EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
360  EXPECT_EQ("which is 42 more than 0", listener1.str());
361
362  StringMatchResultListener listener2;
363  EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
364  EXPECT_EQ("which is 9 less than 0", listener2.str());
365}
366
367// Tests that a C-string literal can be implicitly converted to a
368// Matcher<string> or Matcher<const string&>.
369TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
370  Matcher<string> m1 = "hi";
371  EXPECT_TRUE(m1.Matches("hi"));
372  EXPECT_FALSE(m1.Matches("hello"));
373
374  Matcher<const string&> m2 = "hi";
375  EXPECT_TRUE(m2.Matches("hi"));
376  EXPECT_FALSE(m2.Matches("hello"));
377}
378
379// Tests that a string object can be implicitly converted to a
380// Matcher<string> or Matcher<const string&>.
381TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
382  Matcher<string> m1 = string("hi");
383  EXPECT_TRUE(m1.Matches("hi"));
384  EXPECT_FALSE(m1.Matches("hello"));
385
386  Matcher<const string&> m2 = string("hi");
387  EXPECT_TRUE(m2.Matches("hi"));
388  EXPECT_FALSE(m2.Matches("hello"));
389}
390
391#if GTEST_HAS_STRING_PIECE_
392// Tests that a C-string literal can be implicitly converted to a
393// Matcher<StringPiece> or Matcher<const StringPiece&>.
394TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
395  Matcher<StringPiece> m1 = "cats";
396  EXPECT_TRUE(m1.Matches("cats"));
397  EXPECT_FALSE(m1.Matches("dogs"));
398
399  Matcher<const StringPiece&> m2 = "cats";
400  EXPECT_TRUE(m2.Matches("cats"));
401  EXPECT_FALSE(m2.Matches("dogs"));
402}
403
404// Tests that a string object can be implicitly converted to a
405// Matcher<StringPiece> or Matcher<const StringPiece&>.
406TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
407  Matcher<StringPiece> m1 = string("cats");
408  EXPECT_TRUE(m1.Matches("cats"));
409  EXPECT_FALSE(m1.Matches("dogs"));
410
411  Matcher<const StringPiece&> m2 = string("cats");
412  EXPECT_TRUE(m2.Matches("cats"));
413  EXPECT_FALSE(m2.Matches("dogs"));
414}
415
416// Tests that a StringPiece object can be implicitly converted to a
417// Matcher<StringPiece> or Matcher<const StringPiece&>.
418TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
419  Matcher<StringPiece> m1 = StringPiece("cats");
420  EXPECT_TRUE(m1.Matches("cats"));
421  EXPECT_FALSE(m1.Matches("dogs"));
422
423  Matcher<const StringPiece&> m2 = StringPiece("cats");
424  EXPECT_TRUE(m2.Matches("cats"));
425  EXPECT_FALSE(m2.Matches("dogs"));
426}
427#endif  // GTEST_HAS_STRING_PIECE_
428
429// Tests that MakeMatcher() constructs a Matcher<T> from a
430// MatcherInterface* without requiring the user to explicitly
431// write the type.
432TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
433  const MatcherInterface<int>* dummy_impl = NULL;
434  Matcher<int> m = MakeMatcher(dummy_impl);
435}
436
437// Tests that MakePolymorphicMatcher() can construct a polymorphic
438// matcher from its implementation using the old API.
439const int g_bar = 1;
440class ReferencesBarOrIsZeroImpl {
441 public:
442  template <typename T>
443  bool MatchAndExplain(const T& x,
444                       MatchResultListener* /* listener */) const {
445    const void* p = &x;
446    return p == &g_bar || x == 0;
447  }
448
449  void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
450
451  void DescribeNegationTo(ostream* os) const {
452    *os << "doesn't reference g_bar and is not zero";
453  }
454};
455
456// This function verifies that MakePolymorphicMatcher() returns a
457// PolymorphicMatcher<T> where T is the argument's type.
458PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
459  return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
460}
461
462TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
463  // Using a polymorphic matcher to match a reference type.
464  Matcher<const int&> m1 = ReferencesBarOrIsZero();
465  EXPECT_TRUE(m1.Matches(0));
466  // Verifies that the identity of a by-reference argument is preserved.
467  EXPECT_TRUE(m1.Matches(g_bar));
468  EXPECT_FALSE(m1.Matches(1));
469  EXPECT_EQ("g_bar or zero", Describe(m1));
470
471  // Using a polymorphic matcher to match a value type.
472  Matcher<double> m2 = ReferencesBarOrIsZero();
473  EXPECT_TRUE(m2.Matches(0.0));
474  EXPECT_FALSE(m2.Matches(0.1));
475  EXPECT_EQ("g_bar or zero", Describe(m2));
476}
477
478// Tests implementing a polymorphic matcher using MatchAndExplain().
479
480class PolymorphicIsEvenImpl {
481 public:
482  void DescribeTo(ostream* os) const { *os << "is even"; }
483
484  void DescribeNegationTo(ostream* os) const {
485    *os << "is odd";
486  }
487
488  template <typename T>
489  bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
490    // Verifies that we can stream to the listener directly.
491    *listener << "% " << 2;
492    if (listener->stream() != NULL) {
493      // Verifies that we can stream to the listener's underlying stream
494      // too.
495      *listener->stream() << " == " << (x % 2);
496    }
497    return (x % 2) == 0;
498  }
499};
500
501PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
502  return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
503}
504
505TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
506  // Using PolymorphicIsEven() as a Matcher<int>.
507  const Matcher<int> m1 = PolymorphicIsEven();
508  EXPECT_TRUE(m1.Matches(42));
509  EXPECT_FALSE(m1.Matches(43));
510  EXPECT_EQ("is even", Describe(m1));
511
512  const Matcher<int> not_m1 = Not(m1);
513  EXPECT_EQ("is odd", Describe(not_m1));
514
515  EXPECT_EQ("% 2 == 0", Explain(m1, 42));
516
517  // Using PolymorphicIsEven() as a Matcher<char>.
518  const Matcher<char> m2 = PolymorphicIsEven();
519  EXPECT_TRUE(m2.Matches('\x42'));
520  EXPECT_FALSE(m2.Matches('\x43'));
521  EXPECT_EQ("is even", Describe(m2));
522
523  const Matcher<char> not_m2 = Not(m2);
524  EXPECT_EQ("is odd", Describe(not_m2));
525
526  EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
527}
528
529// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
530TEST(MatcherCastTest, FromPolymorphicMatcher) {
531  Matcher<int> m = MatcherCast<int>(Eq(5));
532  EXPECT_TRUE(m.Matches(5));
533  EXPECT_FALSE(m.Matches(6));
534}
535
536// For testing casting matchers between compatible types.
537class IntValue {
538 public:
539  // An int can be statically (although not implicitly) cast to a
540  // IntValue.
541  explicit IntValue(int a_value) : value_(a_value) {}
542
543  int value() const { return value_; }
544 private:
545  int value_;
546};
547
548// For testing casting matchers between compatible types.
549bool IsPositiveIntValue(const IntValue& foo) {
550  return foo.value() > 0;
551}
552
553// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
554// can be statically converted to U.
555TEST(MatcherCastTest, FromCompatibleType) {
556  Matcher<double> m1 = Eq(2.0);
557  Matcher<int> m2 = MatcherCast<int>(m1);
558  EXPECT_TRUE(m2.Matches(2));
559  EXPECT_FALSE(m2.Matches(3));
560
561  Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
562  Matcher<int> m4 = MatcherCast<int>(m3);
563  // In the following, the arguments 1 and 0 are statically converted
564  // to IntValue objects, and then tested by the IsPositiveIntValue()
565  // predicate.
566  EXPECT_TRUE(m4.Matches(1));
567  EXPECT_FALSE(m4.Matches(0));
568}
569
570// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
571TEST(MatcherCastTest, FromConstReferenceToNonReference) {
572  Matcher<const int&> m1 = Eq(0);
573  Matcher<int> m2 = MatcherCast<int>(m1);
574  EXPECT_TRUE(m2.Matches(0));
575  EXPECT_FALSE(m2.Matches(1));
576}
577
578// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
579TEST(MatcherCastTest, FromReferenceToNonReference) {
580  Matcher<int&> m1 = Eq(0);
581  Matcher<int> m2 = MatcherCast<int>(m1);
582  EXPECT_TRUE(m2.Matches(0));
583  EXPECT_FALSE(m2.Matches(1));
584}
585
586// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
587TEST(MatcherCastTest, FromNonReferenceToConstReference) {
588  Matcher<int> m1 = Eq(0);
589  Matcher<const int&> m2 = MatcherCast<const int&>(m1);
590  EXPECT_TRUE(m2.Matches(0));
591  EXPECT_FALSE(m2.Matches(1));
592}
593
594// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
595TEST(MatcherCastTest, FromNonReferenceToReference) {
596  Matcher<int> m1 = Eq(0);
597  Matcher<int&> m2 = MatcherCast<int&>(m1);
598  int n = 0;
599  EXPECT_TRUE(m2.Matches(n));
600  n = 1;
601  EXPECT_FALSE(m2.Matches(n));
602}
603
604// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
605TEST(MatcherCastTest, FromSameType) {
606  Matcher<int> m1 = Eq(0);
607  Matcher<int> m2 = MatcherCast<int>(m1);
608  EXPECT_TRUE(m2.Matches(0));
609  EXPECT_FALSE(m2.Matches(1));
610}
611
612// Implicitly convertible from any type.
613struct ConvertibleFromAny {
614  ConvertibleFromAny(int a_value) : value(a_value) {}
615  template <typename T>
616  ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
617    ADD_FAILURE() << "Conversion constructor called";
618  }
619  int value;
620};
621
622bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
623  return a.value == b.value;
624}
625
626ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
627  return os << a.value;
628}
629
630TEST(MatcherCastTest, ConversionConstructorIsUsed) {
631  Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
632  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
633  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
634}
635
636TEST(MatcherCastTest, FromConvertibleFromAny) {
637  Matcher<ConvertibleFromAny> m =
638      MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
639  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
640  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
641}
642
643struct IntReferenceWrapper {
644  IntReferenceWrapper(const int& a_value) : value(&a_value) {}
645  const int* value;
646};
647
648bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
649  return a.value == b.value;
650}
651
652TEST(MatcherCastTest, ValueIsNotCopied) {
653  int n = 42;
654  Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
655  // Verify that the matcher holds a reference to n, not to its temporary copy.
656  EXPECT_TRUE(m.Matches(n));
657}
658
659class Base {
660 public:
661  virtual ~Base() {}
662  Base() {}
663 private:
664  GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
665};
666
667class Derived : public Base {
668 public:
669  Derived() : Base() {}
670  int i;
671};
672
673class OtherDerived : public Base {};
674
675// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
676TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
677  Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
678  EXPECT_TRUE(m2.Matches(' '));
679  EXPECT_FALSE(m2.Matches('\n'));
680}
681
682// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
683// T and U are arithmetic types and T can be losslessly converted to
684// U.
685TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
686  Matcher<double> m1 = DoubleEq(1.0);
687  Matcher<float> m2 = SafeMatcherCast<float>(m1);
688  EXPECT_TRUE(m2.Matches(1.0f));
689  EXPECT_FALSE(m2.Matches(2.0f));
690
691  Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
692  EXPECT_TRUE(m3.Matches('a'));
693  EXPECT_FALSE(m3.Matches('b'));
694}
695
696// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
697// are pointers or references to a derived and a base class, correspondingly.
698TEST(SafeMatcherCastTest, FromBaseClass) {
699  Derived d, d2;
700  Matcher<Base*> m1 = Eq(&d);
701  Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
702  EXPECT_TRUE(m2.Matches(&d));
703  EXPECT_FALSE(m2.Matches(&d2));
704
705  Matcher<Base&> m3 = Ref(d);
706  Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
707  EXPECT_TRUE(m4.Matches(d));
708  EXPECT_FALSE(m4.Matches(d2));
709}
710
711// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
712TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
713  int n = 0;
714  Matcher<const int&> m1 = Ref(n);
715  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
716  int n1 = 0;
717  EXPECT_TRUE(m2.Matches(n));
718  EXPECT_FALSE(m2.Matches(n1));
719}
720
721// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
722TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
723  Matcher<int> m1 = Eq(0);
724  Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
725  EXPECT_TRUE(m2.Matches(0));
726  EXPECT_FALSE(m2.Matches(1));
727}
728
729// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
730TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
731  Matcher<int> m1 = Eq(0);
732  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
733  int n = 0;
734  EXPECT_TRUE(m2.Matches(n));
735  n = 1;
736  EXPECT_FALSE(m2.Matches(n));
737}
738
739// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
740TEST(SafeMatcherCastTest, FromSameType) {
741  Matcher<int> m1 = Eq(0);
742  Matcher<int> m2 = SafeMatcherCast<int>(m1);
743  EXPECT_TRUE(m2.Matches(0));
744  EXPECT_FALSE(m2.Matches(1));
745}
746
747TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
748  Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
749  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
750  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
751}
752
753TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
754  Matcher<ConvertibleFromAny> m =
755      SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
756  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
757  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
758}
759
760TEST(SafeMatcherCastTest, ValueIsNotCopied) {
761  int n = 42;
762  Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
763  // Verify that the matcher holds a reference to n, not to its temporary copy.
764  EXPECT_TRUE(m.Matches(n));
765}
766
767TEST(ExpectThat, TakesLiterals) {
768  EXPECT_THAT(1, 1);
769  EXPECT_THAT(1.0, 1.0);
770  EXPECT_THAT(string(), "");
771}
772
773TEST(ExpectThat, TakesFunctions) {
774  struct Helper {
775    static void Func() {}
776  };
777  void (*func)() = Helper::Func;
778  EXPECT_THAT(func, Helper::Func);
779  EXPECT_THAT(func, &Helper::Func);
780}
781
782// Tests that A<T>() matches any value of type T.
783TEST(ATest, MatchesAnyValue) {
784  // Tests a matcher for a value type.
785  Matcher<double> m1 = A<double>();
786  EXPECT_TRUE(m1.Matches(91.43));
787  EXPECT_TRUE(m1.Matches(-15.32));
788
789  // Tests a matcher for a reference type.
790  int a = 2;
791  int b = -6;
792  Matcher<int&> m2 = A<int&>();
793  EXPECT_TRUE(m2.Matches(a));
794  EXPECT_TRUE(m2.Matches(b));
795}
796
797TEST(ATest, WorksForDerivedClass) {
798  Base base;
799  Derived derived;
800  EXPECT_THAT(&base, A<Base*>());
801  // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
802  EXPECT_THAT(&derived, A<Base*>());
803  EXPECT_THAT(&derived, A<Derived*>());
804}
805
806// Tests that A<T>() describes itself properly.
807TEST(ATest, CanDescribeSelf) {
808  EXPECT_EQ("is anything", Describe(A<bool>()));
809}
810
811// Tests that An<T>() matches any value of type T.
812TEST(AnTest, MatchesAnyValue) {
813  // Tests a matcher for a value type.
814  Matcher<int> m1 = An<int>();
815  EXPECT_TRUE(m1.Matches(9143));
816  EXPECT_TRUE(m1.Matches(-1532));
817
818  // Tests a matcher for a reference type.
819  int a = 2;
820  int b = -6;
821  Matcher<int&> m2 = An<int&>();
822  EXPECT_TRUE(m2.Matches(a));
823  EXPECT_TRUE(m2.Matches(b));
824}
825
826// Tests that An<T>() describes itself properly.
827TEST(AnTest, CanDescribeSelf) {
828  EXPECT_EQ("is anything", Describe(An<int>()));
829}
830
831// Tests that _ can be used as a matcher for any type and matches any
832// value of that type.
833TEST(UnderscoreTest, MatchesAnyValue) {
834  // Uses _ as a matcher for a value type.
835  Matcher<int> m1 = _;
836  EXPECT_TRUE(m1.Matches(123));
837  EXPECT_TRUE(m1.Matches(-242));
838
839  // Uses _ as a matcher for a reference type.
840  bool a = false;
841  const bool b = true;
842  Matcher<const bool&> m2 = _;
843  EXPECT_TRUE(m2.Matches(a));
844  EXPECT_TRUE(m2.Matches(b));
845}
846
847// Tests that _ describes itself properly.
848TEST(UnderscoreTest, CanDescribeSelf) {
849  Matcher<int> m = _;
850  EXPECT_EQ("is anything", Describe(m));
851}
852
853// Tests that Eq(x) matches any value equal to x.
854TEST(EqTest, MatchesEqualValue) {
855  // 2 C-strings with same content but different addresses.
856  const char a1[] = "hi";
857  const char a2[] = "hi";
858
859  Matcher<const char*> m1 = Eq(a1);
860  EXPECT_TRUE(m1.Matches(a1));
861  EXPECT_FALSE(m1.Matches(a2));
862}
863
864// Tests that Eq(v) describes itself properly.
865
866class Unprintable {
867 public:
868  Unprintable() : c_('a') {}
869
870  bool operator==(const Unprintable& /* rhs */) { return true; }
871 private:
872  char c_;
873};
874
875TEST(EqTest, CanDescribeSelf) {
876  Matcher<Unprintable> m = Eq(Unprintable());
877  EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
878}
879
880// Tests that Eq(v) can be used to match any type that supports
881// comparing with type T, where T is v's type.
882TEST(EqTest, IsPolymorphic) {
883  Matcher<int> m1 = Eq(1);
884  EXPECT_TRUE(m1.Matches(1));
885  EXPECT_FALSE(m1.Matches(2));
886
887  Matcher<char> m2 = Eq(1);
888  EXPECT_TRUE(m2.Matches('\1'));
889  EXPECT_FALSE(m2.Matches('a'));
890}
891
892// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
893TEST(TypedEqTest, ChecksEqualityForGivenType) {
894  Matcher<char> m1 = TypedEq<char>('a');
895  EXPECT_TRUE(m1.Matches('a'));
896  EXPECT_FALSE(m1.Matches('b'));
897
898  Matcher<int> m2 = TypedEq<int>(6);
899  EXPECT_TRUE(m2.Matches(6));
900  EXPECT_FALSE(m2.Matches(7));
901}
902
903// Tests that TypedEq(v) describes itself properly.
904TEST(TypedEqTest, CanDescribeSelf) {
905  EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
906}
907
908// Tests that TypedEq<T>(v) has type Matcher<T>.
909
910// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
911// is a "bare" type (i.e. not in the form of const U or U&).  If v's
912// type is not T, the compiler will generate a message about
913// "undefined referece".
914template <typename T>
915struct Type {
916  static bool IsTypeOf(const T& /* v */) { return true; }
917
918  template <typename T2>
919  static void IsTypeOf(T2 v);
920};
921
922TEST(TypedEqTest, HasSpecifiedType) {
923  // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
924  Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
925  Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
926}
927
928// Tests that Ge(v) matches anything >= v.
929TEST(GeTest, ImplementsGreaterThanOrEqual) {
930  Matcher<int> m1 = Ge(0);
931  EXPECT_TRUE(m1.Matches(1));
932  EXPECT_TRUE(m1.Matches(0));
933  EXPECT_FALSE(m1.Matches(-1));
934}
935
936// Tests that Ge(v) describes itself properly.
937TEST(GeTest, CanDescribeSelf) {
938  Matcher<int> m = Ge(5);
939  EXPECT_EQ("is >= 5", Describe(m));
940}
941
942// Tests that Gt(v) matches anything > v.
943TEST(GtTest, ImplementsGreaterThan) {
944  Matcher<double> m1 = Gt(0);
945  EXPECT_TRUE(m1.Matches(1.0));
946  EXPECT_FALSE(m1.Matches(0.0));
947  EXPECT_FALSE(m1.Matches(-1.0));
948}
949
950// Tests that Gt(v) describes itself properly.
951TEST(GtTest, CanDescribeSelf) {
952  Matcher<int> m = Gt(5);
953  EXPECT_EQ("is > 5", Describe(m));
954}
955
956// Tests that Le(v) matches anything <= v.
957TEST(LeTest, ImplementsLessThanOrEqual) {
958  Matcher<char> m1 = Le('b');
959  EXPECT_TRUE(m1.Matches('a'));
960  EXPECT_TRUE(m1.Matches('b'));
961  EXPECT_FALSE(m1.Matches('c'));
962}
963
964// Tests that Le(v) describes itself properly.
965TEST(LeTest, CanDescribeSelf) {
966  Matcher<int> m = Le(5);
967  EXPECT_EQ("is <= 5", Describe(m));
968}
969
970// Tests that Lt(v) matches anything < v.
971TEST(LtTest, ImplementsLessThan) {
972  Matcher<const string&> m1 = Lt("Hello");
973  EXPECT_TRUE(m1.Matches("Abc"));
974  EXPECT_FALSE(m1.Matches("Hello"));
975  EXPECT_FALSE(m1.Matches("Hello, world!"));
976}
977
978// Tests that Lt(v) describes itself properly.
979TEST(LtTest, CanDescribeSelf) {
980  Matcher<int> m = Lt(5);
981  EXPECT_EQ("is < 5", Describe(m));
982}
983
984// Tests that Ne(v) matches anything != v.
985TEST(NeTest, ImplementsNotEqual) {
986  Matcher<int> m1 = Ne(0);
987  EXPECT_TRUE(m1.Matches(1));
988  EXPECT_TRUE(m1.Matches(-1));
989  EXPECT_FALSE(m1.Matches(0));
990}
991
992// Tests that Ne(v) describes itself properly.
993TEST(NeTest, CanDescribeSelf) {
994  Matcher<int> m = Ne(5);
995  EXPECT_EQ("isn't equal to 5", Describe(m));
996}
997
998// Tests that IsNull() matches any NULL pointer of any type.
999TEST(IsNullTest, MatchesNullPointer) {
1000  Matcher<int*> m1 = IsNull();
1001  int* p1 = NULL;
1002  int n = 0;
1003  EXPECT_TRUE(m1.Matches(p1));
1004  EXPECT_FALSE(m1.Matches(&n));
1005
1006  Matcher<const char*> m2 = IsNull();
1007  const char* p2 = NULL;
1008  EXPECT_TRUE(m2.Matches(p2));
1009  EXPECT_FALSE(m2.Matches("hi"));
1010
1011#if !GTEST_OS_SYMBIAN
1012  // Nokia's Symbian compiler generates:
1013  // gmock-matchers.h: ambiguous access to overloaded function
1014  // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1015  // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1016  //     MatcherInterface<void *> *)'
1017  // gmock-matchers.h:  (point of instantiation: 'testing::
1018  //     gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1019  // gmock-matchers.h:   (instantiating: 'testing::PolymorphicMatc
1020  Matcher<void*> m3 = IsNull();
1021  void* p3 = NULL;
1022  EXPECT_TRUE(m3.Matches(p3));
1023  EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1024#endif
1025}
1026
1027TEST(IsNullTest, LinkedPtr) {
1028  const Matcher<linked_ptr<int> > m = IsNull();
1029  const linked_ptr<int> null_p;
1030  const linked_ptr<int> non_null_p(new int);
1031
1032  EXPECT_TRUE(m.Matches(null_p));
1033  EXPECT_FALSE(m.Matches(non_null_p));
1034}
1035
1036TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1037  const Matcher<const linked_ptr<double>&> m = IsNull();
1038  const linked_ptr<double> null_p;
1039  const linked_ptr<double> non_null_p(new double);
1040
1041  EXPECT_TRUE(m.Matches(null_p));
1042  EXPECT_FALSE(m.Matches(non_null_p));
1043}
1044
1045#if GTEST_LANG_CXX11
1046TEST(IsNullTest, StdFunction) {
1047  const Matcher<std::function<void()>> m = IsNull();
1048
1049  EXPECT_TRUE(m.Matches(std::function<void()>()));
1050  EXPECT_FALSE(m.Matches([]{}));
1051}
1052#endif  // GTEST_LANG_CXX11
1053
1054// Tests that IsNull() describes itself properly.
1055TEST(IsNullTest, CanDescribeSelf) {
1056  Matcher<int*> m = IsNull();
1057  EXPECT_EQ("is NULL", Describe(m));
1058  EXPECT_EQ("isn't NULL", DescribeNegation(m));
1059}
1060
1061// Tests that NotNull() matches any non-NULL pointer of any type.
1062TEST(NotNullTest, MatchesNonNullPointer) {
1063  Matcher<int*> m1 = NotNull();
1064  int* p1 = NULL;
1065  int n = 0;
1066  EXPECT_FALSE(m1.Matches(p1));
1067  EXPECT_TRUE(m1.Matches(&n));
1068
1069  Matcher<const char*> m2 = NotNull();
1070  const char* p2 = NULL;
1071  EXPECT_FALSE(m2.Matches(p2));
1072  EXPECT_TRUE(m2.Matches("hi"));
1073}
1074
1075TEST(NotNullTest, LinkedPtr) {
1076  const Matcher<linked_ptr<int> > m = NotNull();
1077  const linked_ptr<int> null_p;
1078  const linked_ptr<int> non_null_p(new int);
1079
1080  EXPECT_FALSE(m.Matches(null_p));
1081  EXPECT_TRUE(m.Matches(non_null_p));
1082}
1083
1084TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1085  const Matcher<const linked_ptr<double>&> m = NotNull();
1086  const linked_ptr<double> null_p;
1087  const linked_ptr<double> non_null_p(new double);
1088
1089  EXPECT_FALSE(m.Matches(null_p));
1090  EXPECT_TRUE(m.Matches(non_null_p));
1091}
1092
1093#if GTEST_LANG_CXX11
1094TEST(NotNullTest, StdFunction) {
1095  const Matcher<std::function<void()>> m = NotNull();
1096
1097  EXPECT_TRUE(m.Matches([]{}));
1098  EXPECT_FALSE(m.Matches(std::function<void()>()));
1099}
1100#endif  // GTEST_LANG_CXX11
1101
1102// Tests that NotNull() describes itself properly.
1103TEST(NotNullTest, CanDescribeSelf) {
1104  Matcher<int*> m = NotNull();
1105  EXPECT_EQ("isn't NULL", Describe(m));
1106}
1107
1108// Tests that Ref(variable) matches an argument that references
1109// 'variable'.
1110TEST(RefTest, MatchesSameVariable) {
1111  int a = 0;
1112  int b = 0;
1113  Matcher<int&> m = Ref(a);
1114  EXPECT_TRUE(m.Matches(a));
1115  EXPECT_FALSE(m.Matches(b));
1116}
1117
1118// Tests that Ref(variable) describes itself properly.
1119TEST(RefTest, CanDescribeSelf) {
1120  int n = 5;
1121  Matcher<int&> m = Ref(n);
1122  stringstream ss;
1123  ss << "references the variable @" << &n << " 5";
1124  EXPECT_EQ(string(ss.str()), Describe(m));
1125}
1126
1127// Test that Ref(non_const_varialbe) can be used as a matcher for a
1128// const reference.
1129TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1130  int a = 0;
1131  int b = 0;
1132  Matcher<const int&> m = Ref(a);
1133  EXPECT_TRUE(m.Matches(a));
1134  EXPECT_FALSE(m.Matches(b));
1135}
1136
1137// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1138// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1139// of Ref(base), but not vice versa.
1140
1141TEST(RefTest, IsCovariant) {
1142  Base base, base2;
1143  Derived derived;
1144  Matcher<const Base&> m1 = Ref(base);
1145  EXPECT_TRUE(m1.Matches(base));
1146  EXPECT_FALSE(m1.Matches(base2));
1147  EXPECT_FALSE(m1.Matches(derived));
1148
1149  m1 = Ref(derived);
1150  EXPECT_TRUE(m1.Matches(derived));
1151  EXPECT_FALSE(m1.Matches(base));
1152  EXPECT_FALSE(m1.Matches(base2));
1153}
1154
1155TEST(RefTest, ExplainsResult) {
1156  int n = 0;
1157  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1158              StartsWith("which is located @"));
1159
1160  int m = 0;
1161  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1162              StartsWith("which is located @"));
1163}
1164
1165// Tests string comparison matchers.
1166
1167TEST(StrEqTest, MatchesEqualString) {
1168  Matcher<const char*> m = StrEq(string("Hello"));
1169  EXPECT_TRUE(m.Matches("Hello"));
1170  EXPECT_FALSE(m.Matches("hello"));
1171  EXPECT_FALSE(m.Matches(NULL));
1172
1173  Matcher<const string&> m2 = StrEq("Hello");
1174  EXPECT_TRUE(m2.Matches("Hello"));
1175  EXPECT_FALSE(m2.Matches("Hi"));
1176}
1177
1178TEST(StrEqTest, CanDescribeSelf) {
1179  Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1180  EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1181      Describe(m));
1182
1183  string str("01204500800");
1184  str[3] = '\0';
1185  Matcher<string> m2 = StrEq(str);
1186  EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1187  str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1188  Matcher<string> m3 = StrEq(str);
1189  EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1190}
1191
1192TEST(StrNeTest, MatchesUnequalString) {
1193  Matcher<const char*> m = StrNe("Hello");
1194  EXPECT_TRUE(m.Matches(""));
1195  EXPECT_TRUE(m.Matches(NULL));
1196  EXPECT_FALSE(m.Matches("Hello"));
1197
1198  Matcher<string> m2 = StrNe(string("Hello"));
1199  EXPECT_TRUE(m2.Matches("hello"));
1200  EXPECT_FALSE(m2.Matches("Hello"));
1201}
1202
1203TEST(StrNeTest, CanDescribeSelf) {
1204  Matcher<const char*> m = StrNe("Hi");
1205  EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1206}
1207
1208TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1209  Matcher<const char*> m = StrCaseEq(string("Hello"));
1210  EXPECT_TRUE(m.Matches("Hello"));
1211  EXPECT_TRUE(m.Matches("hello"));
1212  EXPECT_FALSE(m.Matches("Hi"));
1213  EXPECT_FALSE(m.Matches(NULL));
1214
1215  Matcher<const string&> m2 = StrCaseEq("Hello");
1216  EXPECT_TRUE(m2.Matches("hello"));
1217  EXPECT_FALSE(m2.Matches("Hi"));
1218}
1219
1220TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1221  string str1("oabocdooeoo");
1222  string str2("OABOCDOOEOO");
1223  Matcher<const string&> m0 = StrCaseEq(str1);
1224  EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1225
1226  str1[3] = str2[3] = '\0';
1227  Matcher<const string&> m1 = StrCaseEq(str1);
1228  EXPECT_TRUE(m1.Matches(str2));
1229
1230  str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1231  str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1232  Matcher<const string&> m2 = StrCaseEq(str1);
1233  str1[9] = str2[9] = '\0';
1234  EXPECT_FALSE(m2.Matches(str2));
1235
1236  Matcher<const string&> m3 = StrCaseEq(str1);
1237  EXPECT_TRUE(m3.Matches(str2));
1238
1239  EXPECT_FALSE(m3.Matches(str2 + "x"));
1240  str2.append(1, '\0');
1241  EXPECT_FALSE(m3.Matches(str2));
1242  EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1243}
1244
1245TEST(StrCaseEqTest, CanDescribeSelf) {
1246  Matcher<string> m = StrCaseEq("Hi");
1247  EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1248}
1249
1250TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1251  Matcher<const char*> m = StrCaseNe("Hello");
1252  EXPECT_TRUE(m.Matches("Hi"));
1253  EXPECT_TRUE(m.Matches(NULL));
1254  EXPECT_FALSE(m.Matches("Hello"));
1255  EXPECT_FALSE(m.Matches("hello"));
1256
1257  Matcher<string> m2 = StrCaseNe(string("Hello"));
1258  EXPECT_TRUE(m2.Matches(""));
1259  EXPECT_FALSE(m2.Matches("Hello"));
1260}
1261
1262TEST(StrCaseNeTest, CanDescribeSelf) {
1263  Matcher<const char*> m = StrCaseNe("Hi");
1264  EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1265}
1266
1267// Tests that HasSubstr() works for matching string-typed values.
1268TEST(HasSubstrTest, WorksForStringClasses) {
1269  const Matcher<string> m1 = HasSubstr("foo");
1270  EXPECT_TRUE(m1.Matches(string("I love food.")));
1271  EXPECT_FALSE(m1.Matches(string("tofo")));
1272
1273  const Matcher<const std::string&> m2 = HasSubstr("foo");
1274  EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1275  EXPECT_FALSE(m2.Matches(std::string("tofo")));
1276}
1277
1278// Tests that HasSubstr() works for matching C-string-typed values.
1279TEST(HasSubstrTest, WorksForCStrings) {
1280  const Matcher<char*> m1 = HasSubstr("foo");
1281  EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1282  EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1283  EXPECT_FALSE(m1.Matches(NULL));
1284
1285  const Matcher<const char*> m2 = HasSubstr("foo");
1286  EXPECT_TRUE(m2.Matches("I love food."));
1287  EXPECT_FALSE(m2.Matches("tofo"));
1288  EXPECT_FALSE(m2.Matches(NULL));
1289}
1290
1291// Tests that HasSubstr(s) describes itself properly.
1292TEST(HasSubstrTest, CanDescribeSelf) {
1293  Matcher<string> m = HasSubstr("foo\n\"");
1294  EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1295}
1296
1297TEST(KeyTest, CanDescribeSelf) {
1298  Matcher<const pair<std::string, int>&> m = Key("foo");
1299  EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1300  EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1301}
1302
1303TEST(KeyTest, ExplainsResult) {
1304  Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1305  EXPECT_EQ("whose first field is a value which is 5 less than 10",
1306            Explain(m, make_pair(5, true)));
1307  EXPECT_EQ("whose first field is a value which is 5 more than 10",
1308            Explain(m, make_pair(15, true)));
1309}
1310
1311TEST(KeyTest, MatchesCorrectly) {
1312  pair<int, std::string> p(25, "foo");
1313  EXPECT_THAT(p, Key(25));
1314  EXPECT_THAT(p, Not(Key(42)));
1315  EXPECT_THAT(p, Key(Ge(20)));
1316  EXPECT_THAT(p, Not(Key(Lt(25))));
1317}
1318
1319TEST(KeyTest, SafelyCastsInnerMatcher) {
1320  Matcher<int> is_positive = Gt(0);
1321  Matcher<int> is_negative = Lt(0);
1322  pair<char, bool> p('a', true);
1323  EXPECT_THAT(p, Key(is_positive));
1324  EXPECT_THAT(p, Not(Key(is_negative)));
1325}
1326
1327TEST(KeyTest, InsideContainsUsingMap) {
1328  map<int, char> container;
1329  container.insert(make_pair(1, 'a'));
1330  container.insert(make_pair(2, 'b'));
1331  container.insert(make_pair(4, 'c'));
1332  EXPECT_THAT(container, Contains(Key(1)));
1333  EXPECT_THAT(container, Not(Contains(Key(3))));
1334}
1335
1336TEST(KeyTest, InsideContainsUsingMultimap) {
1337  multimap<int, char> container;
1338  container.insert(make_pair(1, 'a'));
1339  container.insert(make_pair(2, 'b'));
1340  container.insert(make_pair(4, 'c'));
1341
1342  EXPECT_THAT(container, Not(Contains(Key(25))));
1343  container.insert(make_pair(25, 'd'));
1344  EXPECT_THAT(container, Contains(Key(25)));
1345  container.insert(make_pair(25, 'e'));
1346  EXPECT_THAT(container, Contains(Key(25)));
1347
1348  EXPECT_THAT(container, Contains(Key(1)));
1349  EXPECT_THAT(container, Not(Contains(Key(3))));
1350}
1351
1352TEST(PairTest, Typing) {
1353  // Test verifies the following type conversions can be compiled.
1354  Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1355  Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1356  Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1357
1358  Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1359  Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1360}
1361
1362TEST(PairTest, CanDescribeSelf) {
1363  Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1364  EXPECT_EQ("has a first field that is equal to \"foo\""
1365            ", and has a second field that is equal to 42",
1366            Describe(m1));
1367  EXPECT_EQ("has a first field that isn't equal to \"foo\""
1368            ", or has a second field that isn't equal to 42",
1369            DescribeNegation(m1));
1370  // Double and triple negation (1 or 2 times not and description of negation).
1371  Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1372  EXPECT_EQ("has a first field that isn't equal to 13"
1373            ", and has a second field that is equal to 42",
1374            DescribeNegation(m2));
1375}
1376
1377TEST(PairTest, CanExplainMatchResultTo) {
1378  // If neither field matches, Pair() should explain about the first
1379  // field.
1380  const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1381  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1382            Explain(m, make_pair(-1, -2)));
1383
1384  // If the first field matches but the second doesn't, Pair() should
1385  // explain about the second field.
1386  EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1387            Explain(m, make_pair(1, -2)));
1388
1389  // If the first field doesn't match but the second does, Pair()
1390  // should explain about the first field.
1391  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1392            Explain(m, make_pair(-1, 2)));
1393
1394  // If both fields match, Pair() should explain about them both.
1395  EXPECT_EQ("whose both fields match, where the first field is a value "
1396            "which is 1 more than 0, and the second field is a value "
1397            "which is 2 more than 0",
1398            Explain(m, make_pair(1, 2)));
1399
1400  // If only the first match has an explanation, only this explanation should
1401  // be printed.
1402  const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1403  EXPECT_EQ("whose both fields match, where the first field is a value "
1404            "which is 1 more than 0",
1405            Explain(explain_first, make_pair(1, 0)));
1406
1407  // If only the second match has an explanation, only this explanation should
1408  // be printed.
1409  const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1410  EXPECT_EQ("whose both fields match, where the second field is a value "
1411            "which is 1 more than 0",
1412            Explain(explain_second, make_pair(0, 1)));
1413}
1414
1415TEST(PairTest, MatchesCorrectly) {
1416  pair<int, std::string> p(25, "foo");
1417
1418  // Both fields match.
1419  EXPECT_THAT(p, Pair(25, "foo"));
1420  EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1421
1422  // 'first' doesnt' match, but 'second' matches.
1423  EXPECT_THAT(p, Not(Pair(42, "foo")));
1424  EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1425
1426  // 'first' matches, but 'second' doesn't match.
1427  EXPECT_THAT(p, Not(Pair(25, "bar")));
1428  EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1429
1430  // Neither field matches.
1431  EXPECT_THAT(p, Not(Pair(13, "bar")));
1432  EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1433}
1434
1435TEST(PairTest, SafelyCastsInnerMatchers) {
1436  Matcher<int> is_positive = Gt(0);
1437  Matcher<int> is_negative = Lt(0);
1438  pair<char, bool> p('a', true);
1439  EXPECT_THAT(p, Pair(is_positive, _));
1440  EXPECT_THAT(p, Not(Pair(is_negative, _)));
1441  EXPECT_THAT(p, Pair(_, is_positive));
1442  EXPECT_THAT(p, Not(Pair(_, is_negative)));
1443}
1444
1445TEST(PairTest, InsideContainsUsingMap) {
1446  map<int, char> container;
1447  container.insert(make_pair(1, 'a'));
1448  container.insert(make_pair(2, 'b'));
1449  container.insert(make_pair(4, 'c'));
1450  EXPECT_THAT(container, Contains(Pair(1, 'a')));
1451  EXPECT_THAT(container, Contains(Pair(1, _)));
1452  EXPECT_THAT(container, Contains(Pair(_, 'a')));
1453  EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1454}
1455
1456// Tests StartsWith(s).
1457
1458TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1459  const Matcher<const char*> m1 = StartsWith(string(""));
1460  EXPECT_TRUE(m1.Matches("Hi"));
1461  EXPECT_TRUE(m1.Matches(""));
1462  EXPECT_FALSE(m1.Matches(NULL));
1463
1464  const Matcher<const string&> m2 = StartsWith("Hi");
1465  EXPECT_TRUE(m2.Matches("Hi"));
1466  EXPECT_TRUE(m2.Matches("Hi Hi!"));
1467  EXPECT_TRUE(m2.Matches("High"));
1468  EXPECT_FALSE(m2.Matches("H"));
1469  EXPECT_FALSE(m2.Matches(" Hi"));
1470}
1471
1472TEST(StartsWithTest, CanDescribeSelf) {
1473  Matcher<const std::string> m = StartsWith("Hi");
1474  EXPECT_EQ("starts with \"Hi\"", Describe(m));
1475}
1476
1477// Tests EndsWith(s).
1478
1479TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1480  const Matcher<const char*> m1 = EndsWith("");
1481  EXPECT_TRUE(m1.Matches("Hi"));
1482  EXPECT_TRUE(m1.Matches(""));
1483  EXPECT_FALSE(m1.Matches(NULL));
1484
1485  const Matcher<const string&> m2 = EndsWith(string("Hi"));
1486  EXPECT_TRUE(m2.Matches("Hi"));
1487  EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1488  EXPECT_TRUE(m2.Matches("Super Hi"));
1489  EXPECT_FALSE(m2.Matches("i"));
1490  EXPECT_FALSE(m2.Matches("Hi "));
1491}
1492
1493TEST(EndsWithTest, CanDescribeSelf) {
1494  Matcher<const std::string> m = EndsWith("Hi");
1495  EXPECT_EQ("ends with \"Hi\"", Describe(m));
1496}
1497
1498// Tests MatchesRegex().
1499
1500TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1501  const Matcher<const char*> m1 = MatchesRegex("a.*z");
1502  EXPECT_TRUE(m1.Matches("az"));
1503  EXPECT_TRUE(m1.Matches("abcz"));
1504  EXPECT_FALSE(m1.Matches(NULL));
1505
1506  const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1507  EXPECT_TRUE(m2.Matches("azbz"));
1508  EXPECT_FALSE(m2.Matches("az1"));
1509  EXPECT_FALSE(m2.Matches("1az"));
1510}
1511
1512TEST(MatchesRegexTest, CanDescribeSelf) {
1513  Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1514  EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1515
1516  Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1517  EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1518}
1519
1520// Tests ContainsRegex().
1521
1522TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1523  const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1524  EXPECT_TRUE(m1.Matches("az"));
1525  EXPECT_TRUE(m1.Matches("0abcz1"));
1526  EXPECT_FALSE(m1.Matches(NULL));
1527
1528  const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1529  EXPECT_TRUE(m2.Matches("azbz"));
1530  EXPECT_TRUE(m2.Matches("az1"));
1531  EXPECT_FALSE(m2.Matches("1a"));
1532}
1533
1534TEST(ContainsRegexTest, CanDescribeSelf) {
1535  Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1536  EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1537
1538  Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1539  EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1540}
1541
1542// Tests for wide strings.
1543#if GTEST_HAS_STD_WSTRING
1544TEST(StdWideStrEqTest, MatchesEqual) {
1545  Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1546  EXPECT_TRUE(m.Matches(L"Hello"));
1547  EXPECT_FALSE(m.Matches(L"hello"));
1548  EXPECT_FALSE(m.Matches(NULL));
1549
1550  Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1551  EXPECT_TRUE(m2.Matches(L"Hello"));
1552  EXPECT_FALSE(m2.Matches(L"Hi"));
1553
1554  Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1555  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1556  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1557
1558  ::std::wstring str(L"01204500800");
1559  str[3] = L'\0';
1560  Matcher<const ::std::wstring&> m4 = StrEq(str);
1561  EXPECT_TRUE(m4.Matches(str));
1562  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1563  Matcher<const ::std::wstring&> m5 = StrEq(str);
1564  EXPECT_TRUE(m5.Matches(str));
1565}
1566
1567TEST(StdWideStrEqTest, CanDescribeSelf) {
1568  Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1569  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1570    Describe(m));
1571
1572  Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1573  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1574    Describe(m2));
1575
1576  ::std::wstring str(L"01204500800");
1577  str[3] = L'\0';
1578  Matcher<const ::std::wstring&> m4 = StrEq(str);
1579  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1580  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1581  Matcher<const ::std::wstring&> m5 = StrEq(str);
1582  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1583}
1584
1585TEST(StdWideStrNeTest, MatchesUnequalString) {
1586  Matcher<const wchar_t*> m = StrNe(L"Hello");
1587  EXPECT_TRUE(m.Matches(L""));
1588  EXPECT_TRUE(m.Matches(NULL));
1589  EXPECT_FALSE(m.Matches(L"Hello"));
1590
1591  Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1592  EXPECT_TRUE(m2.Matches(L"hello"));
1593  EXPECT_FALSE(m2.Matches(L"Hello"));
1594}
1595
1596TEST(StdWideStrNeTest, CanDescribeSelf) {
1597  Matcher<const wchar_t*> m = StrNe(L"Hi");
1598  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1599}
1600
1601TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1602  Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1603  EXPECT_TRUE(m.Matches(L"Hello"));
1604  EXPECT_TRUE(m.Matches(L"hello"));
1605  EXPECT_FALSE(m.Matches(L"Hi"));
1606  EXPECT_FALSE(m.Matches(NULL));
1607
1608  Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1609  EXPECT_TRUE(m2.Matches(L"hello"));
1610  EXPECT_FALSE(m2.Matches(L"Hi"));
1611}
1612
1613TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1614  ::std::wstring str1(L"oabocdooeoo");
1615  ::std::wstring str2(L"OABOCDOOEOO");
1616  Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1617  EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1618
1619  str1[3] = str2[3] = L'\0';
1620  Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1621  EXPECT_TRUE(m1.Matches(str2));
1622
1623  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1624  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1625  Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1626  str1[9] = str2[9] = L'\0';
1627  EXPECT_FALSE(m2.Matches(str2));
1628
1629  Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1630  EXPECT_TRUE(m3.Matches(str2));
1631
1632  EXPECT_FALSE(m3.Matches(str2 + L"x"));
1633  str2.append(1, L'\0');
1634  EXPECT_FALSE(m3.Matches(str2));
1635  EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1636}
1637
1638TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1639  Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1640  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1641}
1642
1643TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1644  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1645  EXPECT_TRUE(m.Matches(L"Hi"));
1646  EXPECT_TRUE(m.Matches(NULL));
1647  EXPECT_FALSE(m.Matches(L"Hello"));
1648  EXPECT_FALSE(m.Matches(L"hello"));
1649
1650  Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1651  EXPECT_TRUE(m2.Matches(L""));
1652  EXPECT_FALSE(m2.Matches(L"Hello"));
1653}
1654
1655TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1656  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1657  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1658}
1659
1660// Tests that HasSubstr() works for matching wstring-typed values.
1661TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1662  const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1663  EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1664  EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1665
1666  const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1667  EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1668  EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1669}
1670
1671// Tests that HasSubstr() works for matching C-wide-string-typed values.
1672TEST(StdWideHasSubstrTest, WorksForCStrings) {
1673  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1674  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1675  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1676  EXPECT_FALSE(m1.Matches(NULL));
1677
1678  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1679  EXPECT_TRUE(m2.Matches(L"I love food."));
1680  EXPECT_FALSE(m2.Matches(L"tofo"));
1681  EXPECT_FALSE(m2.Matches(NULL));
1682}
1683
1684// Tests that HasSubstr(s) describes itself properly.
1685TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1686  Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1687  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1688}
1689
1690// Tests StartsWith(s).
1691
1692TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1693  const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1694  EXPECT_TRUE(m1.Matches(L"Hi"));
1695  EXPECT_TRUE(m1.Matches(L""));
1696  EXPECT_FALSE(m1.Matches(NULL));
1697
1698  const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1699  EXPECT_TRUE(m2.Matches(L"Hi"));
1700  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1701  EXPECT_TRUE(m2.Matches(L"High"));
1702  EXPECT_FALSE(m2.Matches(L"H"));
1703  EXPECT_FALSE(m2.Matches(L" Hi"));
1704}
1705
1706TEST(StdWideStartsWithTest, CanDescribeSelf) {
1707  Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1708  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1709}
1710
1711// Tests EndsWith(s).
1712
1713TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1714  const Matcher<const wchar_t*> m1 = EndsWith(L"");
1715  EXPECT_TRUE(m1.Matches(L"Hi"));
1716  EXPECT_TRUE(m1.Matches(L""));
1717  EXPECT_FALSE(m1.Matches(NULL));
1718
1719  const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1720  EXPECT_TRUE(m2.Matches(L"Hi"));
1721  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1722  EXPECT_TRUE(m2.Matches(L"Super Hi"));
1723  EXPECT_FALSE(m2.Matches(L"i"));
1724  EXPECT_FALSE(m2.Matches(L"Hi "));
1725}
1726
1727TEST(StdWideEndsWithTest, CanDescribeSelf) {
1728  Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1729  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1730}
1731
1732#endif  // GTEST_HAS_STD_WSTRING
1733
1734#if GTEST_HAS_GLOBAL_WSTRING
1735TEST(GlobalWideStrEqTest, MatchesEqual) {
1736  Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1737  EXPECT_TRUE(m.Matches(L"Hello"));
1738  EXPECT_FALSE(m.Matches(L"hello"));
1739  EXPECT_FALSE(m.Matches(NULL));
1740
1741  Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1742  EXPECT_TRUE(m2.Matches(L"Hello"));
1743  EXPECT_FALSE(m2.Matches(L"Hi"));
1744
1745  Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1746  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1747  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1748
1749  ::wstring str(L"01204500800");
1750  str[3] = L'\0';
1751  Matcher<const ::wstring&> m4 = StrEq(str);
1752  EXPECT_TRUE(m4.Matches(str));
1753  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1754  Matcher<const ::wstring&> m5 = StrEq(str);
1755  EXPECT_TRUE(m5.Matches(str));
1756}
1757
1758TEST(GlobalWideStrEqTest, CanDescribeSelf) {
1759  Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1760  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1761    Describe(m));
1762
1763  Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1764  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1765    Describe(m2));
1766
1767  ::wstring str(L"01204500800");
1768  str[3] = L'\0';
1769  Matcher<const ::wstring&> m4 = StrEq(str);
1770  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1771  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1772  Matcher<const ::wstring&> m5 = StrEq(str);
1773  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1774}
1775
1776TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1777  Matcher<const wchar_t*> m = StrNe(L"Hello");
1778  EXPECT_TRUE(m.Matches(L""));
1779  EXPECT_TRUE(m.Matches(NULL));
1780  EXPECT_FALSE(m.Matches(L"Hello"));
1781
1782  Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1783  EXPECT_TRUE(m2.Matches(L"hello"));
1784  EXPECT_FALSE(m2.Matches(L"Hello"));
1785}
1786
1787TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1788  Matcher<const wchar_t*> m = StrNe(L"Hi");
1789  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1790}
1791
1792TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1793  Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1794  EXPECT_TRUE(m.Matches(L"Hello"));
1795  EXPECT_TRUE(m.Matches(L"hello"));
1796  EXPECT_FALSE(m.Matches(L"Hi"));
1797  EXPECT_FALSE(m.Matches(NULL));
1798
1799  Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1800  EXPECT_TRUE(m2.Matches(L"hello"));
1801  EXPECT_FALSE(m2.Matches(L"Hi"));
1802}
1803
1804TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1805  ::wstring str1(L"oabocdooeoo");
1806  ::wstring str2(L"OABOCDOOEOO");
1807  Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1808  EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1809
1810  str1[3] = str2[3] = L'\0';
1811  Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1812  EXPECT_TRUE(m1.Matches(str2));
1813
1814  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1815  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1816  Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1817  str1[9] = str2[9] = L'\0';
1818  EXPECT_FALSE(m2.Matches(str2));
1819
1820  Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1821  EXPECT_TRUE(m3.Matches(str2));
1822
1823  EXPECT_FALSE(m3.Matches(str2 + L"x"));
1824  str2.append(1, L'\0');
1825  EXPECT_FALSE(m3.Matches(str2));
1826  EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1827}
1828
1829TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1830  Matcher< ::wstring> m = StrCaseEq(L"Hi");
1831  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1832}
1833
1834TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1835  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1836  EXPECT_TRUE(m.Matches(L"Hi"));
1837  EXPECT_TRUE(m.Matches(NULL));
1838  EXPECT_FALSE(m.Matches(L"Hello"));
1839  EXPECT_FALSE(m.Matches(L"hello"));
1840
1841  Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1842  EXPECT_TRUE(m2.Matches(L""));
1843  EXPECT_FALSE(m2.Matches(L"Hello"));
1844}
1845
1846TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1847  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1848  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1849}
1850
1851// Tests that HasSubstr() works for matching wstring-typed values.
1852TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1853  const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1854  EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1855  EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1856
1857  const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1858  EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1859  EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1860}
1861
1862// Tests that HasSubstr() works for matching C-wide-string-typed values.
1863TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1864  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1865  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1866  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1867  EXPECT_FALSE(m1.Matches(NULL));
1868
1869  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1870  EXPECT_TRUE(m2.Matches(L"I love food."));
1871  EXPECT_FALSE(m2.Matches(L"tofo"));
1872  EXPECT_FALSE(m2.Matches(NULL));
1873}
1874
1875// Tests that HasSubstr(s) describes itself properly.
1876TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1877  Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1878  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1879}
1880
1881// Tests StartsWith(s).
1882
1883TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1884  const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1885  EXPECT_TRUE(m1.Matches(L"Hi"));
1886  EXPECT_TRUE(m1.Matches(L""));
1887  EXPECT_FALSE(m1.Matches(NULL));
1888
1889  const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1890  EXPECT_TRUE(m2.Matches(L"Hi"));
1891  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1892  EXPECT_TRUE(m2.Matches(L"High"));
1893  EXPECT_FALSE(m2.Matches(L"H"));
1894  EXPECT_FALSE(m2.Matches(L" Hi"));
1895}
1896
1897TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1898  Matcher<const ::wstring> m = StartsWith(L"Hi");
1899  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1900}
1901
1902// Tests EndsWith(s).
1903
1904TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1905  const Matcher<const wchar_t*> m1 = EndsWith(L"");
1906  EXPECT_TRUE(m1.Matches(L"Hi"));
1907  EXPECT_TRUE(m1.Matches(L""));
1908  EXPECT_FALSE(m1.Matches(NULL));
1909
1910  const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1911  EXPECT_TRUE(m2.Matches(L"Hi"));
1912  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1913  EXPECT_TRUE(m2.Matches(L"Super Hi"));
1914  EXPECT_FALSE(m2.Matches(L"i"));
1915  EXPECT_FALSE(m2.Matches(L"Hi "));
1916}
1917
1918TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1919  Matcher<const ::wstring> m = EndsWith(L"Hi");
1920  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1921}
1922
1923#endif  // GTEST_HAS_GLOBAL_WSTRING
1924
1925
1926typedef ::testing::tuple<long, int> Tuple2;  // NOLINT
1927
1928// Tests that Eq() matches a 2-tuple where the first field == the
1929// second field.
1930TEST(Eq2Test, MatchesEqualArguments) {
1931  Matcher<const Tuple2&> m = Eq();
1932  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1933  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1934}
1935
1936// Tests that Eq() describes itself properly.
1937TEST(Eq2Test, CanDescribeSelf) {
1938  Matcher<const Tuple2&> m = Eq();
1939  EXPECT_EQ("are an equal pair", Describe(m));
1940}
1941
1942// Tests that Ge() matches a 2-tuple where the first field >= the
1943// second field.
1944TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1945  Matcher<const Tuple2&> m = Ge();
1946  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1947  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1948  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1949}
1950
1951// Tests that Ge() describes itself properly.
1952TEST(Ge2Test, CanDescribeSelf) {
1953  Matcher<const Tuple2&> m = Ge();
1954  EXPECT_EQ("are a pair where the first >= the second", Describe(m));
1955}
1956
1957// Tests that Gt() matches a 2-tuple where the first field > the
1958// second field.
1959TEST(Gt2Test, MatchesGreaterThanArguments) {
1960  Matcher<const Tuple2&> m = Gt();
1961  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1962  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1963  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1964}
1965
1966// Tests that Gt() describes itself properly.
1967TEST(Gt2Test, CanDescribeSelf) {
1968  Matcher<const Tuple2&> m = Gt();
1969  EXPECT_EQ("are a pair where the first > the second", Describe(m));
1970}
1971
1972// Tests that Le() matches a 2-tuple where the first field <= the
1973// second field.
1974TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1975  Matcher<const Tuple2&> m = Le();
1976  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1977  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1978  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1979}
1980
1981// Tests that Le() describes itself properly.
1982TEST(Le2Test, CanDescribeSelf) {
1983  Matcher<const Tuple2&> m = Le();
1984  EXPECT_EQ("are a pair where the first <= the second", Describe(m));
1985}
1986
1987// Tests that Lt() matches a 2-tuple where the first field < the
1988// second field.
1989TEST(Lt2Test, MatchesLessThanArguments) {
1990  Matcher<const Tuple2&> m = Lt();
1991  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1992  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1993  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1994}
1995
1996// Tests that Lt() describes itself properly.
1997TEST(Lt2Test, CanDescribeSelf) {
1998  Matcher<const Tuple2&> m = Lt();
1999  EXPECT_EQ("are a pair where the first < the second", Describe(m));
2000}
2001
2002// Tests that Ne() matches a 2-tuple where the first field != the
2003// second field.
2004TEST(Ne2Test, MatchesUnequalArguments) {
2005  Matcher<const Tuple2&> m = Ne();
2006  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2007  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2008  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2009}
2010
2011// Tests that Ne() describes itself properly.
2012TEST(Ne2Test, CanDescribeSelf) {
2013  Matcher<const Tuple2&> m = Ne();
2014  EXPECT_EQ("are an unequal pair", Describe(m));
2015}
2016
2017// Tests that Not(m) matches any value that doesn't match m.
2018TEST(NotTest, NegatesMatcher) {
2019  Matcher<int> m;
2020  m = Not(Eq(2));
2021  EXPECT_TRUE(m.Matches(3));
2022  EXPECT_FALSE(m.Matches(2));
2023}
2024
2025// Tests that Not(m) describes itself properly.
2026TEST(NotTest, CanDescribeSelf) {
2027  Matcher<int> m = Not(Eq(5));
2028  EXPECT_EQ("isn't equal to 5", Describe(m));
2029}
2030
2031// Tests that monomorphic matchers are safely cast by the Not matcher.
2032TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2033  // greater_than_5 is a monomorphic matcher.
2034  Matcher<int> greater_than_5 = Gt(5);
2035
2036  Matcher<const int&> m = Not(greater_than_5);
2037  Matcher<int&> m2 = Not(greater_than_5);
2038  Matcher<int&> m3 = Not(m);
2039}
2040
2041// Helper to allow easy testing of AllOf matchers with num parameters.
2042void AllOfMatches(int num, const Matcher<int>& m) {
2043  SCOPED_TRACE(Describe(m));
2044  EXPECT_TRUE(m.Matches(0));
2045  for (int i = 1; i <= num; ++i) {
2046    EXPECT_FALSE(m.Matches(i));
2047  }
2048  EXPECT_TRUE(m.Matches(num + 1));
2049}
2050
2051// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2052// the given matchers.
2053TEST(AllOfTest, MatchesWhenAllMatch) {
2054  Matcher<int> m;
2055  m = AllOf(Le(2), Ge(1));
2056  EXPECT_TRUE(m.Matches(1));
2057  EXPECT_TRUE(m.Matches(2));
2058  EXPECT_FALSE(m.Matches(0));
2059  EXPECT_FALSE(m.Matches(3));
2060
2061  m = AllOf(Gt(0), Ne(1), Ne(2));
2062  EXPECT_TRUE(m.Matches(3));
2063  EXPECT_FALSE(m.Matches(2));
2064  EXPECT_FALSE(m.Matches(1));
2065  EXPECT_FALSE(m.Matches(0));
2066
2067  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2068  EXPECT_TRUE(m.Matches(4));
2069  EXPECT_FALSE(m.Matches(3));
2070  EXPECT_FALSE(m.Matches(2));
2071  EXPECT_FALSE(m.Matches(1));
2072  EXPECT_FALSE(m.Matches(0));
2073
2074  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2075  EXPECT_TRUE(m.Matches(0));
2076  EXPECT_TRUE(m.Matches(1));
2077  EXPECT_FALSE(m.Matches(3));
2078
2079  // The following tests for varying number of sub-matchers. Due to the way
2080  // the sub-matchers are handled it is enough to test every sub-matcher once
2081  // with sub-matchers using the same matcher type. Varying matcher types are
2082  // checked for above.
2083  AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2084  AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2085  AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2086  AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2087  AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2088  AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2089  AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2090                        Ne(8)));
2091  AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2092                        Ne(8), Ne(9)));
2093  AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2094                         Ne(9), Ne(10)));
2095}
2096
2097#if GTEST_LANG_CXX11
2098// Tests the variadic version of the AllOfMatcher.
2099TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2100  // Make sure AllOf is defined in the right namespace and does not depend on
2101  // ADL.
2102  ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2103  Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2104                         Ne(9), Ne(10), Ne(11));
2105  EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2106  AllOfMatches(11, m);
2107  AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2108                         Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2109                         Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2110                         Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2111                         Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2112                         Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2113                         Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2114                         Ne(50)));
2115}
2116
2117#endif  // GTEST_LANG_CXX11
2118
2119// Tests that AllOf(m1, ..., mn) describes itself properly.
2120TEST(AllOfTest, CanDescribeSelf) {
2121  Matcher<int> m;
2122  m = AllOf(Le(2), Ge(1));
2123  EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2124
2125  m = AllOf(Gt(0), Ne(1), Ne(2));
2126  EXPECT_EQ("(is > 0) and "
2127            "((isn't equal to 1) and "
2128            "(isn't equal to 2))",
2129            Describe(m));
2130
2131
2132  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2133  EXPECT_EQ("((is > 0) and "
2134            "(isn't equal to 1)) and "
2135            "((isn't equal to 2) and "
2136            "(isn't equal to 3))",
2137            Describe(m));
2138
2139
2140  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2141  EXPECT_EQ("((is >= 0) and "
2142            "(is < 10)) and "
2143            "((isn't equal to 3) and "
2144            "((isn't equal to 5) and "
2145            "(isn't equal to 7)))",
2146            Describe(m));
2147}
2148
2149// Tests that AllOf(m1, ..., mn) describes its negation properly.
2150TEST(AllOfTest, CanDescribeNegation) {
2151  Matcher<int> m;
2152  m = AllOf(Le(2), Ge(1));
2153  EXPECT_EQ("(isn't <= 2) or "
2154            "(isn't >= 1)",
2155            DescribeNegation(m));
2156
2157  m = AllOf(Gt(0), Ne(1), Ne(2));
2158  EXPECT_EQ("(isn't > 0) or "
2159            "((is equal to 1) or "
2160            "(is equal to 2))",
2161            DescribeNegation(m));
2162
2163
2164  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2165  EXPECT_EQ("((isn't > 0) or "
2166            "(is equal to 1)) or "
2167            "((is equal to 2) or "
2168            "(is equal to 3))",
2169            DescribeNegation(m));
2170
2171
2172  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2173  EXPECT_EQ("((isn't >= 0) or "
2174            "(isn't < 10)) or "
2175            "((is equal to 3) or "
2176            "((is equal to 5) or "
2177            "(is equal to 7)))",
2178            DescribeNegation(m));
2179}
2180
2181// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2182TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2183  // greater_than_5 and less_than_10 are monomorphic matchers.
2184  Matcher<int> greater_than_5 = Gt(5);
2185  Matcher<int> less_than_10 = Lt(10);
2186
2187  Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2188  Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2189  Matcher<int&> m3 = AllOf(greater_than_5, m2);
2190
2191  // Tests that BothOf works when composing itself.
2192  Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2193  Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2194}
2195
2196TEST(AllOfTest, ExplainsResult) {
2197  Matcher<int> m;
2198
2199  // Successful match.  Both matchers need to explain.  The second
2200  // matcher doesn't give an explanation, so only the first matcher's
2201  // explanation is printed.
2202  m = AllOf(GreaterThan(10), Lt(30));
2203  EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2204
2205  // Successful match.  Both matchers need to explain.
2206  m = AllOf(GreaterThan(10), GreaterThan(20));
2207  EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2208            Explain(m, 30));
2209
2210  // Successful match.  All matchers need to explain.  The second
2211  // matcher doesn't given an explanation.
2212  m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2213  EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2214            Explain(m, 25));
2215
2216  // Successful match.  All matchers need to explain.
2217  m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2218  EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2219            "and which is 10 more than 30",
2220            Explain(m, 40));
2221
2222  // Failed match.  The first matcher, which failed, needs to
2223  // explain.
2224  m = AllOf(GreaterThan(10), GreaterThan(20));
2225  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2226
2227  // Failed match.  The second matcher, which failed, needs to
2228  // explain.  Since it doesn't given an explanation, nothing is
2229  // printed.
2230  m = AllOf(GreaterThan(10), Lt(30));
2231  EXPECT_EQ("", Explain(m, 40));
2232
2233  // Failed match.  The second matcher, which failed, needs to
2234  // explain.
2235  m = AllOf(GreaterThan(10), GreaterThan(20));
2236  EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2237}
2238
2239// Helper to allow easy testing of AnyOf matchers with num parameters.
2240void AnyOfMatches(int num, const Matcher<int>& m) {
2241  SCOPED_TRACE(Describe(m));
2242  EXPECT_FALSE(m.Matches(0));
2243  for (int i = 1; i <= num; ++i) {
2244    EXPECT_TRUE(m.Matches(i));
2245  }
2246  EXPECT_FALSE(m.Matches(num + 1));
2247}
2248
2249// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2250// least one of the given matchers.
2251TEST(AnyOfTest, MatchesWhenAnyMatches) {
2252  Matcher<int> m;
2253  m = AnyOf(Le(1), Ge(3));
2254  EXPECT_TRUE(m.Matches(1));
2255  EXPECT_TRUE(m.Matches(4));
2256  EXPECT_FALSE(m.Matches(2));
2257
2258  m = AnyOf(Lt(0), Eq(1), Eq(2));
2259  EXPECT_TRUE(m.Matches(-1));
2260  EXPECT_TRUE(m.Matches(1));
2261  EXPECT_TRUE(m.Matches(2));
2262  EXPECT_FALSE(m.Matches(0));
2263
2264  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2265  EXPECT_TRUE(m.Matches(-1));
2266  EXPECT_TRUE(m.Matches(1));
2267  EXPECT_TRUE(m.Matches(2));
2268  EXPECT_TRUE(m.Matches(3));
2269  EXPECT_FALSE(m.Matches(0));
2270
2271  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2272  EXPECT_TRUE(m.Matches(0));
2273  EXPECT_TRUE(m.Matches(11));
2274  EXPECT_TRUE(m.Matches(3));
2275  EXPECT_FALSE(m.Matches(2));
2276
2277  // The following tests for varying number of sub-matchers. Due to the way
2278  // the sub-matchers are handled it is enough to test every sub-matcher once
2279  // with sub-matchers using the same matcher type. Varying matcher types are
2280  // checked for above.
2281  AnyOfMatches(2, AnyOf(1, 2));
2282  AnyOfMatches(3, AnyOf(1, 2, 3));
2283  AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2284  AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2285  AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2286  AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2287  AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2288  AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2289  AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2290}
2291
2292#if GTEST_LANG_CXX11
2293// Tests the variadic version of the AnyOfMatcher.
2294TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2295  // Also make sure AnyOf is defined in the right namespace and does not depend
2296  // on ADL.
2297  Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2298
2299  EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2300  AnyOfMatches(11, m);
2301  AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2302                         11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2303                         21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2304                         31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2305                         41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2306}
2307
2308#endif  // GTEST_LANG_CXX11
2309
2310// Tests that AnyOf(m1, ..., mn) describes itself properly.
2311TEST(AnyOfTest, CanDescribeSelf) {
2312  Matcher<int> m;
2313  m = AnyOf(Le(1), Ge(3));
2314  EXPECT_EQ("(is <= 1) or (is >= 3)",
2315            Describe(m));
2316
2317  m = AnyOf(Lt(0), Eq(1), Eq(2));
2318  EXPECT_EQ("(is < 0) or "
2319            "((is equal to 1) or (is equal to 2))",
2320            Describe(m));
2321
2322  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2323  EXPECT_EQ("((is < 0) or "
2324            "(is equal to 1)) or "
2325            "((is equal to 2) or "
2326            "(is equal to 3))",
2327            Describe(m));
2328
2329  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2330  EXPECT_EQ("((is <= 0) or "
2331            "(is > 10)) or "
2332            "((is equal to 3) or "
2333            "((is equal to 5) or "
2334            "(is equal to 7)))",
2335            Describe(m));
2336}
2337
2338// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2339TEST(AnyOfTest, CanDescribeNegation) {
2340  Matcher<int> m;
2341  m = AnyOf(Le(1), Ge(3));
2342  EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2343            DescribeNegation(m));
2344
2345  m = AnyOf(Lt(0), Eq(1), Eq(2));
2346  EXPECT_EQ("(isn't < 0) and "
2347            "((isn't equal to 1) and (isn't equal to 2))",
2348            DescribeNegation(m));
2349
2350  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2351  EXPECT_EQ("((isn't < 0) and "
2352            "(isn't equal to 1)) and "
2353            "((isn't equal to 2) and "
2354            "(isn't equal to 3))",
2355            DescribeNegation(m));
2356
2357  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2358  EXPECT_EQ("((isn't <= 0) and "
2359            "(isn't > 10)) and "
2360            "((isn't equal to 3) and "
2361            "((isn't equal to 5) and "
2362            "(isn't equal to 7)))",
2363            DescribeNegation(m));
2364}
2365
2366// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2367TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2368  // greater_than_5 and less_than_10 are monomorphic matchers.
2369  Matcher<int> greater_than_5 = Gt(5);
2370  Matcher<int> less_than_10 = Lt(10);
2371
2372  Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2373  Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2374  Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2375
2376  // Tests that EitherOf works when composing itself.
2377  Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2378  Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2379}
2380
2381TEST(AnyOfTest, ExplainsResult) {
2382  Matcher<int> m;
2383
2384  // Failed match.  Both matchers need to explain.  The second
2385  // matcher doesn't give an explanation, so only the first matcher's
2386  // explanation is printed.
2387  m = AnyOf(GreaterThan(10), Lt(0));
2388  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2389
2390  // Failed match.  Both matchers need to explain.
2391  m = AnyOf(GreaterThan(10), GreaterThan(20));
2392  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2393            Explain(m, 5));
2394
2395  // Failed match.  All matchers need to explain.  The second
2396  // matcher doesn't given an explanation.
2397  m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2398  EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2399            Explain(m, 5));
2400
2401  // Failed match.  All matchers need to explain.
2402  m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2403  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2404            "and which is 25 less than 30",
2405            Explain(m, 5));
2406
2407  // Successful match.  The first matcher, which succeeded, needs to
2408  // explain.
2409  m = AnyOf(GreaterThan(10), GreaterThan(20));
2410  EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2411
2412  // Successful match.  The second matcher, which succeeded, needs to
2413  // explain.  Since it doesn't given an explanation, nothing is
2414  // printed.
2415  m = AnyOf(GreaterThan(10), Lt(30));
2416  EXPECT_EQ("", Explain(m, 0));
2417
2418  // Successful match.  The second matcher, which succeeded, needs to
2419  // explain.
2420  m = AnyOf(GreaterThan(30), GreaterThan(20));
2421  EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2422}
2423
2424// The following predicate function and predicate functor are for
2425// testing the Truly(predicate) matcher.
2426
2427// Returns non-zero if the input is positive.  Note that the return
2428// type of this function is not bool.  It's OK as Truly() accepts any
2429// unary function or functor whose return type can be implicitly
2430// converted to bool.
2431int IsPositive(double x) {
2432  return x > 0 ? 1 : 0;
2433}
2434
2435// This functor returns true if the input is greater than the given
2436// number.
2437class IsGreaterThan {
2438 public:
2439  explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2440
2441  bool operator()(int n) const { return n > threshold_; }
2442
2443 private:
2444  int threshold_;
2445};
2446
2447// For testing Truly().
2448const int foo = 0;
2449
2450// This predicate returns true iff the argument references foo and has
2451// a zero value.
2452bool ReferencesFooAndIsZero(const int& n) {
2453  return (&n == &foo) && (n == 0);
2454}
2455
2456// Tests that Truly(predicate) matches what satisfies the given
2457// predicate.
2458TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2459  Matcher<double> m = Truly(IsPositive);
2460  EXPECT_TRUE(m.Matches(2.0));
2461  EXPECT_FALSE(m.Matches(-1.5));
2462}
2463
2464// Tests that Truly(predicate_functor) works too.
2465TEST(TrulyTest, CanBeUsedWithFunctor) {
2466  Matcher<int> m = Truly(IsGreaterThan(5));
2467  EXPECT_TRUE(m.Matches(6));
2468  EXPECT_FALSE(m.Matches(4));
2469}
2470
2471// A class that can be implicitly converted to bool.
2472class ConvertibleToBool {
2473 public:
2474  explicit ConvertibleToBool(int number) : number_(number) {}
2475  operator bool() const { return number_ != 0; }
2476
2477 private:
2478  int number_;
2479};
2480
2481ConvertibleToBool IsNotZero(int number) {
2482  return ConvertibleToBool(number);
2483}
2484
2485// Tests that the predicate used in Truly() may return a class that's
2486// implicitly convertible to bool, even when the class has no
2487// operator!().
2488TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2489  Matcher<int> m = Truly(IsNotZero);
2490  EXPECT_TRUE(m.Matches(1));
2491  EXPECT_FALSE(m.Matches(0));
2492}
2493
2494// Tests that Truly(predicate) can describe itself properly.
2495TEST(TrulyTest, CanDescribeSelf) {
2496  Matcher<double> m = Truly(IsPositive);
2497  EXPECT_EQ("satisfies the given predicate",
2498            Describe(m));
2499}
2500
2501// Tests that Truly(predicate) works when the matcher takes its
2502// argument by reference.
2503TEST(TrulyTest, WorksForByRefArguments) {
2504  Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2505  EXPECT_TRUE(m.Matches(foo));
2506  int n = 0;
2507  EXPECT_FALSE(m.Matches(n));
2508}
2509
2510// Tests that Matches(m) is a predicate satisfied by whatever that
2511// matches matcher m.
2512TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2513  EXPECT_TRUE(Matches(Ge(0))(1));
2514  EXPECT_FALSE(Matches(Eq('a'))('b'));
2515}
2516
2517// Tests that Matches(m) works when the matcher takes its argument by
2518// reference.
2519TEST(MatchesTest, WorksOnByRefArguments) {
2520  int m = 0, n = 0;
2521  EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2522  EXPECT_FALSE(Matches(Ref(m))(n));
2523}
2524
2525// Tests that a Matcher on non-reference type can be used in
2526// Matches().
2527TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2528  Matcher<int> eq5 = Eq(5);
2529  EXPECT_TRUE(Matches(eq5)(5));
2530  EXPECT_FALSE(Matches(eq5)(2));
2531}
2532
2533// Tests Value(value, matcher).  Since Value() is a simple wrapper for
2534// Matches(), which has been tested already, we don't spend a lot of
2535// effort on testing Value().
2536TEST(ValueTest, WorksWithPolymorphicMatcher) {
2537  EXPECT_TRUE(Value("hi", StartsWith("h")));
2538  EXPECT_FALSE(Value(5, Gt(10)));
2539}
2540
2541TEST(ValueTest, WorksWithMonomorphicMatcher) {
2542  const Matcher<int> is_zero = Eq(0);
2543  EXPECT_TRUE(Value(0, is_zero));
2544  EXPECT_FALSE(Value('a', is_zero));
2545
2546  int n = 0;
2547  const Matcher<const int&> ref_n = Ref(n);
2548  EXPECT_TRUE(Value(n, ref_n));
2549  EXPECT_FALSE(Value(1, ref_n));
2550}
2551
2552TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
2553  StringMatchResultListener listener1;
2554  EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
2555  EXPECT_EQ("% 2 == 0", listener1.str());
2556
2557  StringMatchResultListener listener2;
2558  EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
2559  EXPECT_EQ("", listener2.str());
2560}
2561
2562TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
2563  const Matcher<int> is_even = PolymorphicIsEven();
2564  StringMatchResultListener listener1;
2565  EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
2566  EXPECT_EQ("% 2 == 0", listener1.str());
2567
2568  const Matcher<const double&> is_zero = Eq(0);
2569  StringMatchResultListener listener2;
2570  EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
2571  EXPECT_EQ("", listener2.str());
2572}
2573
2574MATCHER_P(Really, inner_matcher, "") {
2575  return ExplainMatchResult(inner_matcher, arg, result_listener);
2576}
2577
2578TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2579  EXPECT_THAT(0, Really(Eq(0)));
2580}
2581
2582TEST(AllArgsTest, WorksForTuple) {
2583  EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2584  EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2585}
2586
2587TEST(AllArgsTest, WorksForNonTuple) {
2588  EXPECT_THAT(42, AllArgs(Gt(0)));
2589  EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2590}
2591
2592class AllArgsHelper {
2593 public:
2594  AllArgsHelper() {}
2595
2596  MOCK_METHOD2(Helper, int(char x, int y));
2597
2598 private:
2599  GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
2600};
2601
2602TEST(AllArgsTest, WorksInWithClause) {
2603  AllArgsHelper helper;
2604  ON_CALL(helper, Helper(_, _))
2605      .With(AllArgs(Lt()))
2606      .WillByDefault(Return(1));
2607  EXPECT_CALL(helper, Helper(_, _));
2608  EXPECT_CALL(helper, Helper(_, _))
2609      .With(AllArgs(Gt()))
2610      .WillOnce(Return(2));
2611
2612  EXPECT_EQ(1, helper.Helper('\1', 2));
2613  EXPECT_EQ(2, helper.Helper('a', 1));
2614}
2615
2616// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2617// matches the matcher.
2618TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2619  ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2620  ASSERT_THAT("Foo", EndsWith("oo"));
2621  EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2622  EXPECT_THAT("Hello", StartsWith("Hell"));
2623}
2624
2625// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2626// doesn't match the matcher.
2627TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2628  // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2629  // which cannot reference auto variables.
2630  static unsigned short n;  // NOLINT
2631  n = 5;
2632
2633  // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2634  // functions declared in the namespace scope from within nested classes.
2635  // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2636  // namespace-level functions invoked inside them need to be explicitly
2637  // resolved.
2638  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
2639                       "Value of: n\n"
2640                       "Expected: is > 10\n"
2641                       "  Actual: 5" + OfType("unsigned short"));
2642  n = 0;
2643  EXPECT_NONFATAL_FAILURE(
2644      EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2645      "Value of: n\n"
2646      "Expected: (is <= 7) and (is >= 5)\n"
2647      "  Actual: 0" + OfType("unsigned short"));
2648}
2649
2650// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2651// has a reference type.
2652TEST(MatcherAssertionTest, WorksForByRefArguments) {
2653  // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2654  // reference auto variables.
2655  static int n;
2656  n = 0;
2657  EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
2658  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2659                       "Value of: n\n"
2660                       "Expected: does not reference the variable @");
2661  // Tests the "Actual" part.
2662  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2663                       "Actual: 0" + OfType("int") + ", which is located @");
2664}
2665
2666#if !GTEST_OS_SYMBIAN
2667// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2668// monomorphic.
2669
2670// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2671// Symbian compiler: it tries to compile
2672// template<T, U> class MatcherCastImpl { ...
2673//   virtual bool MatchAndExplain(T x, ...) const {
2674//     return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
2675// with U == string and T == const char*
2676// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2677// the compiler silently crashes with no output.
2678// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2679// the code compiles but the converted string is bogus.
2680TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2681  Matcher<const char*> starts_with_he = StartsWith("he");
2682  ASSERT_THAT("hello", starts_with_he);
2683
2684  Matcher<const string&> ends_with_ok = EndsWith("ok");
2685  ASSERT_THAT("book", ends_with_ok);
2686  const string bad = "bad";
2687  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2688                          "Value of: bad\n"
2689                          "Expected: ends with \"ok\"\n"
2690                          "  Actual: \"bad\"");
2691  Matcher<int> is_greater_than_5 = Gt(5);
2692  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2693                          "Value of: 5\n"
2694                          "Expected: is > 5\n"
2695                          "  Actual: 5" + OfType("int"));
2696}
2697#endif  // !GTEST_OS_SYMBIAN
2698
2699// Tests floating-point matchers.
2700template <typename RawType>
2701class FloatingPointTest : public testing::Test {
2702 protected:
2703  typedef testing::internal::FloatingPoint<RawType> Floating;
2704  typedef typename Floating::Bits Bits;
2705
2706  FloatingPointTest()
2707      : max_ulps_(Floating::kMaxUlps),
2708        zero_bits_(Floating(0).bits()),
2709        one_bits_(Floating(1).bits()),
2710        infinity_bits_(Floating(Floating::Infinity()).bits()),
2711        close_to_positive_zero_(
2712            Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2713        close_to_negative_zero_(
2714            -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2715        further_from_negative_zero_(-Floating::ReinterpretBits(
2716            zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2717        close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2718        further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2719        infinity_(Floating::Infinity()),
2720        close_to_infinity_(
2721            Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2722        further_from_infinity_(
2723            Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2724        max_(Floating::Max()),
2725        nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2726        nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
2727  }
2728
2729  void TestSize() {
2730    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2731  }
2732
2733  // A battery of tests for FloatingEqMatcher::Matches.
2734  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2735  void TestMatches(
2736      testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2737    Matcher<RawType> m1 = matcher_maker(0.0);
2738    EXPECT_TRUE(m1.Matches(-0.0));
2739    EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2740    EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2741    EXPECT_FALSE(m1.Matches(1.0));
2742
2743    Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2744    EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2745
2746    Matcher<RawType> m3 = matcher_maker(1.0);
2747    EXPECT_TRUE(m3.Matches(close_to_one_));
2748    EXPECT_FALSE(m3.Matches(further_from_one_));
2749
2750    // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2751    EXPECT_FALSE(m3.Matches(0.0));
2752
2753    Matcher<RawType> m4 = matcher_maker(-infinity_);
2754    EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2755
2756    Matcher<RawType> m5 = matcher_maker(infinity_);
2757    EXPECT_TRUE(m5.Matches(close_to_infinity_));
2758
2759    // This is interesting as the representations of infinity_ and nan1_
2760    // are only 1 DLP apart.
2761    EXPECT_FALSE(m5.Matches(nan1_));
2762
2763    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2764    // some cases.
2765    Matcher<const RawType&> m6 = matcher_maker(0.0);
2766    EXPECT_TRUE(m6.Matches(-0.0));
2767    EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2768    EXPECT_FALSE(m6.Matches(1.0));
2769
2770    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2771    // cases.
2772    Matcher<RawType&> m7 = matcher_maker(0.0);
2773    RawType x = 0.0;
2774    EXPECT_TRUE(m7.Matches(x));
2775    x = 0.01f;
2776    EXPECT_FALSE(m7.Matches(x));
2777  }
2778
2779  // Pre-calculated numbers to be used by the tests.
2780
2781  const size_t max_ulps_;
2782
2783  const Bits zero_bits_;  // The bits that represent 0.0.
2784  const Bits one_bits_;  // The bits that represent 1.0.
2785  const Bits infinity_bits_;  // The bits that represent +infinity.
2786
2787  // Some numbers close to 0.0.
2788  const RawType close_to_positive_zero_;
2789  const RawType close_to_negative_zero_;
2790  const RawType further_from_negative_zero_;
2791
2792  // Some numbers close to 1.0.
2793  const RawType close_to_one_;
2794  const RawType further_from_one_;
2795
2796  // Some numbers close to +infinity.
2797  const RawType infinity_;
2798  const RawType close_to_infinity_;
2799  const RawType further_from_infinity_;
2800
2801  // Maximum representable value that's not infinity.
2802  const RawType max_;
2803
2804  // Some NaNs.
2805  const RawType nan1_;
2806  const RawType nan2_;
2807};
2808
2809// Tests floating-point matchers with fixed epsilons.
2810template <typename RawType>
2811class FloatingPointNearTest : public FloatingPointTest<RawType> {
2812 protected:
2813  typedef FloatingPointTest<RawType> ParentType;
2814
2815  // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2816  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2817  void TestNearMatches(
2818      testing::internal::FloatingEqMatcher<RawType>
2819          (*matcher_maker)(RawType, RawType)) {
2820    Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2821    EXPECT_TRUE(m1.Matches(0.0));
2822    EXPECT_TRUE(m1.Matches(-0.0));
2823    EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2824    EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2825    EXPECT_FALSE(m1.Matches(1.0));
2826
2827    Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2828    EXPECT_TRUE(m2.Matches(0.0));
2829    EXPECT_TRUE(m2.Matches(-0.0));
2830    EXPECT_TRUE(m2.Matches(1.0));
2831    EXPECT_TRUE(m2.Matches(-1.0));
2832    EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2833    EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2834
2835    // Check that inf matches inf, regardless of the of the specified max
2836    // absolute error.
2837    Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2838    EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2839    EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2840    EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2841
2842    Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2843    EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2844    EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2845    EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2846
2847    // Test various overflow scenarios.
2848    Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2849    EXPECT_TRUE(m5.Matches(ParentType::max_));
2850    EXPECT_FALSE(m5.Matches(-ParentType::max_));
2851
2852    Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2853    EXPECT_FALSE(m6.Matches(ParentType::max_));
2854    EXPECT_TRUE(m6.Matches(-ParentType::max_));
2855
2856    Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2857    EXPECT_TRUE(m7.Matches(ParentType::max_));
2858    EXPECT_FALSE(m7.Matches(-ParentType::max_));
2859
2860    Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2861    EXPECT_FALSE(m8.Matches(ParentType::max_));
2862    EXPECT_TRUE(m8.Matches(-ParentType::max_));
2863
2864    // The difference between max() and -max() normally overflows to infinity,
2865    // but it should still match if the max_abs_error is also infinity.
2866    Matcher<RawType> m9 = matcher_maker(
2867        ParentType::max_, ParentType::infinity_);
2868    EXPECT_TRUE(m8.Matches(-ParentType::max_));
2869
2870    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2871    // some cases.
2872    Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2873    EXPECT_TRUE(m10.Matches(-0.0));
2874    EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2875    EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2876
2877    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2878    // cases.
2879    Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2880    RawType x = 0.0;
2881    EXPECT_TRUE(m11.Matches(x));
2882    x = 1.0f;
2883    EXPECT_TRUE(m11.Matches(x));
2884    x = -1.0f;
2885    EXPECT_TRUE(m11.Matches(x));
2886    x = 1.1f;
2887    EXPECT_FALSE(m11.Matches(x));
2888    x = -1.1f;
2889    EXPECT_FALSE(m11.Matches(x));
2890  }
2891};
2892
2893// Instantiate FloatingPointTest for testing floats.
2894typedef FloatingPointTest<float> FloatTest;
2895
2896TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2897  TestMatches(&FloatEq);
2898}
2899
2900TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2901  TestMatches(&NanSensitiveFloatEq);
2902}
2903
2904TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2905  // FloatEq never matches NaN.
2906  Matcher<float> m = FloatEq(nan1_);
2907  EXPECT_FALSE(m.Matches(nan1_));
2908  EXPECT_FALSE(m.Matches(nan2_));
2909  EXPECT_FALSE(m.Matches(1.0));
2910}
2911
2912TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2913  // NanSensitiveFloatEq will match NaN.
2914  Matcher<float> m = NanSensitiveFloatEq(nan1_);
2915  EXPECT_TRUE(m.Matches(nan1_));
2916  EXPECT_TRUE(m.Matches(nan2_));
2917  EXPECT_FALSE(m.Matches(1.0));
2918}
2919
2920TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2921  Matcher<float> m1 = FloatEq(2.0f);
2922  EXPECT_EQ("is approximately 2", Describe(m1));
2923  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2924
2925  Matcher<float> m2 = FloatEq(0.5f);
2926  EXPECT_EQ("is approximately 0.5", Describe(m2));
2927  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2928
2929  Matcher<float> m3 = FloatEq(nan1_);
2930  EXPECT_EQ("never matches", Describe(m3));
2931  EXPECT_EQ("is anything", DescribeNegation(m3));
2932}
2933
2934TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2935  Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2936  EXPECT_EQ("is approximately 2", Describe(m1));
2937  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2938
2939  Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2940  EXPECT_EQ("is approximately 0.5", Describe(m2));
2941  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2942
2943  Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2944  EXPECT_EQ("is NaN", Describe(m3));
2945  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2946}
2947
2948// Instantiate FloatingPointTest for testing floats with a user-specified
2949// max absolute error.
2950typedef FloatingPointNearTest<float> FloatNearTest;
2951
2952TEST_F(FloatNearTest, FloatNearMatches) {
2953  TestNearMatches(&FloatNear);
2954}
2955
2956TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2957  TestNearMatches(&NanSensitiveFloatNear);
2958}
2959
2960TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2961  Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2962  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2963  EXPECT_EQ(
2964      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2965
2966  Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2967  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2968  EXPECT_EQ(
2969      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2970
2971  Matcher<float> m3 = FloatNear(nan1_, 0.0);
2972  EXPECT_EQ("never matches", Describe(m3));
2973  EXPECT_EQ("is anything", DescribeNegation(m3));
2974}
2975
2976TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2977  Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2978  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2979  EXPECT_EQ(
2980      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2981
2982  Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2983  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2984  EXPECT_EQ(
2985      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2986
2987  Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2988  EXPECT_EQ("is NaN", Describe(m3));
2989  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2990}
2991
2992TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2993  // FloatNear never matches NaN.
2994  Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2995  EXPECT_FALSE(m.Matches(nan1_));
2996  EXPECT_FALSE(m.Matches(nan2_));
2997  EXPECT_FALSE(m.Matches(1.0));
2998}
2999
3000TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3001  // NanSensitiveFloatNear will match NaN.
3002  Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3003  EXPECT_TRUE(m.Matches(nan1_));
3004  EXPECT_TRUE(m.Matches(nan2_));
3005  EXPECT_FALSE(m.Matches(1.0));
3006}
3007
3008// Instantiate FloatingPointTest for testing doubles.
3009typedef FloatingPointTest<double> DoubleTest;
3010
3011TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3012  TestMatches(&DoubleEq);
3013}
3014
3015TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3016  TestMatches(&NanSensitiveDoubleEq);
3017}
3018
3019TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3020  // DoubleEq never matches NaN.
3021  Matcher<double> m = DoubleEq(nan1_);
3022  EXPECT_FALSE(m.Matches(nan1_));
3023  EXPECT_FALSE(m.Matches(nan2_));
3024  EXPECT_FALSE(m.Matches(1.0));
3025}
3026
3027TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3028  // NanSensitiveDoubleEq will match NaN.
3029  Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3030  EXPECT_TRUE(m.Matches(nan1_));
3031  EXPECT_TRUE(m.Matches(nan2_));
3032  EXPECT_FALSE(m.Matches(1.0));
3033}
3034
3035TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3036  Matcher<double> m1 = DoubleEq(2.0);
3037  EXPECT_EQ("is approximately 2", Describe(m1));
3038  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3039
3040  Matcher<double> m2 = DoubleEq(0.5);
3041  EXPECT_EQ("is approximately 0.5", Describe(m2));
3042  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3043
3044  Matcher<double> m3 = DoubleEq(nan1_);
3045  EXPECT_EQ("never matches", Describe(m3));
3046  EXPECT_EQ("is anything", DescribeNegation(m3));
3047}
3048
3049TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3050  Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3051  EXPECT_EQ("is approximately 2", Describe(m1));
3052  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3053
3054  Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3055  EXPECT_EQ("is approximately 0.5", Describe(m2));
3056  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3057
3058  Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3059  EXPECT_EQ("is NaN", Describe(m3));
3060  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3061}
3062
3063// Instantiate FloatingPointTest for testing floats with a user-specified
3064// max absolute error.
3065typedef FloatingPointNearTest<double> DoubleNearTest;
3066
3067TEST_F(DoubleNearTest, DoubleNearMatches) {
3068  TestNearMatches(&DoubleNear);
3069}
3070
3071TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3072  TestNearMatches(&NanSensitiveDoubleNear);
3073}
3074
3075TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3076  Matcher<double> m1 = DoubleNear(2.0, 0.5);
3077  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3078  EXPECT_EQ(
3079      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3080
3081  Matcher<double> m2 = DoubleNear(0.5, 0.5);
3082  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3083  EXPECT_EQ(
3084      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3085
3086  Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3087  EXPECT_EQ("never matches", Describe(m3));
3088  EXPECT_EQ("is anything", DescribeNegation(m3));
3089}
3090
3091TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3092  EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3093  EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3094  EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3095
3096  const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3097  // Different C++ implementations may print floating-point numbers
3098  // slightly differently.
3099  EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" ||  // GCC
3100              explanation == "which is 1.2e-010 from 2.1")   // MSVC
3101      << " where explanation is \"" << explanation << "\".";
3102}
3103
3104TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3105  Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3106  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3107  EXPECT_EQ(
3108      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3109
3110  Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3111  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3112  EXPECT_EQ(
3113      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3114
3115  Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3116  EXPECT_EQ("is NaN", Describe(m3));
3117  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3118}
3119
3120TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3121  // DoubleNear never matches NaN.
3122  Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3123  EXPECT_FALSE(m.Matches(nan1_));
3124  EXPECT_FALSE(m.Matches(nan2_));
3125  EXPECT_FALSE(m.Matches(1.0));
3126}
3127
3128TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3129  // NanSensitiveDoubleNear will match NaN.
3130  Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3131  EXPECT_TRUE(m.Matches(nan1_));
3132  EXPECT_TRUE(m.Matches(nan2_));
3133  EXPECT_FALSE(m.Matches(1.0));
3134}
3135
3136TEST(PointeeTest, RawPointer) {
3137  const Matcher<int*> m = Pointee(Ge(0));
3138
3139  int n = 1;
3140  EXPECT_TRUE(m.Matches(&n));
3141  n = -1;
3142  EXPECT_FALSE(m.Matches(&n));
3143  EXPECT_FALSE(m.Matches(NULL));
3144}
3145
3146TEST(PointeeTest, RawPointerToConst) {
3147  const Matcher<const double*> m = Pointee(Ge(0));
3148
3149  double x = 1;
3150  EXPECT_TRUE(m.Matches(&x));
3151  x = -1;
3152  EXPECT_FALSE(m.Matches(&x));
3153  EXPECT_FALSE(m.Matches(NULL));
3154}
3155
3156TEST(PointeeTest, ReferenceToConstRawPointer) {
3157  const Matcher<int* const &> m = Pointee(Ge(0));
3158
3159  int n = 1;
3160  EXPECT_TRUE(m.Matches(&n));
3161  n = -1;
3162  EXPECT_FALSE(m.Matches(&n));
3163  EXPECT_FALSE(m.Matches(NULL));
3164}
3165
3166TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3167  const Matcher<double* &> m = Pointee(Ge(0));
3168
3169  double x = 1.0;
3170  double* p = &x;
3171  EXPECT_TRUE(m.Matches(p));
3172  x = -1;
3173  EXPECT_FALSE(m.Matches(p));
3174  p = NULL;
3175  EXPECT_FALSE(m.Matches(p));
3176}
3177
3178MATCHER_P(FieldIIs, inner_matcher, "") {
3179  return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3180}
3181
3182TEST(WhenDynamicCastToTest, SameType) {
3183  Derived derived;
3184  derived.i = 4;
3185
3186  // Right type. A pointer is passed down.
3187  Base* as_base_ptr = &derived;
3188  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3189  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3190  EXPECT_THAT(as_base_ptr,
3191              Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3192}
3193
3194TEST(WhenDynamicCastToTest, WrongTypes) {
3195  Base base;
3196  Derived derived;
3197  OtherDerived other_derived;
3198
3199  // Wrong types. NULL is passed.
3200  EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3201  EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3202  Base* as_base_ptr = &derived;
3203  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3204  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3205  as_base_ptr = &other_derived;
3206  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3207  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3208}
3209
3210TEST(WhenDynamicCastToTest, AlreadyNull) {
3211  // Already NULL.
3212  Base* as_base_ptr = NULL;
3213  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3214}
3215
3216struct AmbiguousCastTypes {
3217  class VirtualDerived : public virtual Base {};
3218  class DerivedSub1 : public VirtualDerived {};
3219  class DerivedSub2 : public VirtualDerived {};
3220  class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3221};
3222
3223TEST(WhenDynamicCastToTest, AmbiguousCast) {
3224  AmbiguousCastTypes::DerivedSub1 sub1;
3225  AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3226  // Multiply derived from Base. dynamic_cast<> returns NULL.
3227  Base* as_base_ptr =
3228      static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3229  EXPECT_THAT(as_base_ptr,
3230              WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3231  as_base_ptr = &sub1;
3232  EXPECT_THAT(
3233      as_base_ptr,
3234      WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3235}
3236
3237TEST(WhenDynamicCastToTest, Describe) {
3238  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3239#if GTEST_HAS_RTTI
3240  const string prefix =
3241      "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3242#else  // GTEST_HAS_RTTI
3243  const string prefix = "when dynamic_cast, ";
3244#endif  // GTEST_HAS_RTTI
3245  EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3246  EXPECT_EQ(prefix + "does not point to a value that is anything",
3247            DescribeNegation(matcher));
3248}
3249
3250TEST(WhenDynamicCastToTest, Explain) {
3251  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3252  Base* null = NULL;
3253  EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3254  Derived derived;
3255  EXPECT_TRUE(matcher.Matches(&derived));
3256  EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3257
3258  // With references, the matcher itself can fail. Test for that one.
3259  Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3260  EXPECT_THAT(Explain(ref_matcher, derived),
3261              HasSubstr("which cannot be dynamic_cast"));
3262}
3263
3264TEST(WhenDynamicCastToTest, GoodReference) {
3265  Derived derived;
3266  derived.i = 4;
3267  Base& as_base_ref = derived;
3268  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3269  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3270}
3271
3272TEST(WhenDynamicCastToTest, BadReference) {
3273  Derived derived;
3274  Base& as_base_ref = derived;
3275  EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3276}
3277
3278// Minimal const-propagating pointer.
3279template <typename T>
3280class ConstPropagatingPtr {
3281 public:
3282  typedef T element_type;
3283
3284  ConstPropagatingPtr() : val_() {}
3285  explicit ConstPropagatingPtr(T* t) : val_(t) {}
3286  ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3287
3288  T* get() { return val_; }
3289  T& operator*() { return *val_; }
3290  // Most smart pointers return non-const T* and T& from the next methods.
3291  const T* get() const { return val_; }
3292  const T& operator*() const { return *val_; }
3293
3294 private:
3295  T* val_;
3296};
3297
3298TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3299  const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3300  int three = 3;
3301  const ConstPropagatingPtr<int> co(&three);
3302  ConstPropagatingPtr<int> o(&three);
3303  EXPECT_TRUE(m.Matches(o));
3304  EXPECT_TRUE(m.Matches(co));
3305  *o = 6;
3306  EXPECT_FALSE(m.Matches(o));
3307  EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3308}
3309
3310TEST(PointeeTest, NeverMatchesNull) {
3311  const Matcher<const char*> m = Pointee(_);
3312  EXPECT_FALSE(m.Matches(NULL));
3313}
3314
3315// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3316TEST(PointeeTest, MatchesAgainstAValue) {
3317  const Matcher<int*> m = Pointee(5);
3318
3319  int n = 5;
3320  EXPECT_TRUE(m.Matches(&n));
3321  n = -1;
3322  EXPECT_FALSE(m.Matches(&n));
3323  EXPECT_FALSE(m.Matches(NULL));
3324}
3325
3326TEST(PointeeTest, CanDescribeSelf) {
3327  const Matcher<int*> m = Pointee(Gt(3));
3328  EXPECT_EQ("points to a value that is > 3", Describe(m));
3329  EXPECT_EQ("does not point to a value that is > 3",
3330            DescribeNegation(m));
3331}
3332
3333TEST(PointeeTest, CanExplainMatchResult) {
3334  const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3335
3336  EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3337
3338  const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT
3339  long n = 3;  // NOLINT
3340  EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3341            Explain(m2, &n));
3342}
3343
3344TEST(PointeeTest, AlwaysExplainsPointee) {
3345  const Matcher<int*> m = Pointee(0);
3346  int n = 42;
3347  EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3348}
3349
3350// An uncopyable class.
3351class Uncopyable {
3352 public:
3353  Uncopyable() : value_(-1) {}
3354  explicit Uncopyable(int a_value) : value_(a_value) {}
3355
3356  int value() const { return value_; }
3357  void set_value(int i) { value_ = i; }
3358
3359 private:
3360  int value_;
3361  GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3362};
3363
3364// Returns true iff x.value() is positive.
3365bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3366
3367MATCHER_P(UncopyableIs, inner_matcher, "") {
3368  return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3369}
3370
3371// A user-defined struct for testing Field().
3372struct AStruct {
3373  AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3374  AStruct(const AStruct& rhs)
3375      : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3376
3377  int x;           // A non-const field.
3378  const double y;  // A const field.
3379  Uncopyable z;    // An uncopyable field.
3380  const char* p;   // A pointer field.
3381
3382 private:
3383  GTEST_DISALLOW_ASSIGN_(AStruct);
3384};
3385
3386// A derived struct for testing Field().
3387struct DerivedStruct : public AStruct {
3388  char ch;
3389
3390 private:
3391  GTEST_DISALLOW_ASSIGN_(DerivedStruct);
3392};
3393
3394// Tests that Field(&Foo::field, ...) works when field is non-const.
3395TEST(FieldTest, WorksForNonConstField) {
3396  Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3397
3398  AStruct a;
3399  EXPECT_TRUE(m.Matches(a));
3400  a.x = -1;
3401  EXPECT_FALSE(m.Matches(a));
3402}
3403
3404// Tests that Field(&Foo::field, ...) works when field is const.
3405TEST(FieldTest, WorksForConstField) {
3406  AStruct a;
3407
3408  Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3409  EXPECT_TRUE(m.Matches(a));
3410  m = Field(&AStruct::y, Le(0.0));
3411  EXPECT_FALSE(m.Matches(a));
3412}
3413
3414// Tests that Field(&Foo::field, ...) works when field is not copyable.
3415TEST(FieldTest, WorksForUncopyableField) {
3416  AStruct a;
3417
3418  Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3419  EXPECT_TRUE(m.Matches(a));
3420  m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3421  EXPECT_FALSE(m.Matches(a));
3422}
3423
3424// Tests that Field(&Foo::field, ...) works when field is a pointer.
3425TEST(FieldTest, WorksForPointerField) {
3426  // Matching against NULL.
3427  Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3428  AStruct a;
3429  EXPECT_TRUE(m.Matches(a));
3430  a.p = "hi";
3431  EXPECT_FALSE(m.Matches(a));
3432
3433  // Matching a pointer that is not NULL.
3434  m = Field(&AStruct::p, StartsWith("hi"));
3435  a.p = "hill";
3436  EXPECT_TRUE(m.Matches(a));
3437  a.p = "hole";
3438  EXPECT_FALSE(m.Matches(a));
3439}
3440
3441// Tests that Field() works when the object is passed by reference.
3442TEST(FieldTest, WorksForByRefArgument) {
3443  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3444
3445  AStruct a;
3446  EXPECT_TRUE(m.Matches(a));
3447  a.x = -1;
3448  EXPECT_FALSE(m.Matches(a));
3449}
3450
3451// Tests that Field(&Foo::field, ...) works when the argument's type
3452// is a sub-type of Foo.
3453TEST(FieldTest, WorksForArgumentOfSubType) {
3454  // Note that the matcher expects DerivedStruct but we say AStruct
3455  // inside Field().
3456  Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3457
3458  DerivedStruct d;
3459  EXPECT_TRUE(m.Matches(d));
3460  d.x = -1;
3461  EXPECT_FALSE(m.Matches(d));
3462}
3463
3464// Tests that Field(&Foo::field, m) works when field's type and m's
3465// argument type are compatible but not the same.
3466TEST(FieldTest, WorksForCompatibleMatcherType) {
3467  // The field is an int, but the inner matcher expects a signed char.
3468  Matcher<const AStruct&> m = Field(&AStruct::x,
3469                                    Matcher<signed char>(Ge(0)));
3470
3471  AStruct a;
3472  EXPECT_TRUE(m.Matches(a));
3473  a.x = -1;
3474  EXPECT_FALSE(m.Matches(a));
3475}
3476
3477// Tests that Field() can describe itself.
3478TEST(FieldTest, CanDescribeSelf) {
3479  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3480
3481  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3482  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3483}
3484
3485// Tests that Field() can explain the match result.
3486TEST(FieldTest, CanExplainMatchResult) {
3487  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3488
3489  AStruct a;
3490  a.x = 1;
3491  EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
3492
3493  m = Field(&AStruct::x, GreaterThan(0));
3494  EXPECT_EQ(
3495      "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3496      Explain(m, a));
3497}
3498
3499// Tests that Field() works when the argument is a pointer to const.
3500TEST(FieldForPointerTest, WorksForPointerToConst) {
3501  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3502
3503  AStruct a;
3504  EXPECT_TRUE(m.Matches(&a));
3505  a.x = -1;
3506  EXPECT_FALSE(m.Matches(&a));
3507}
3508
3509// Tests that Field() works when the argument is a pointer to non-const.
3510TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3511  Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3512
3513  AStruct a;
3514  EXPECT_TRUE(m.Matches(&a));
3515  a.x = -1;
3516  EXPECT_FALSE(m.Matches(&a));
3517}
3518
3519// Tests that Field() works when the argument is a reference to a const pointer.
3520TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3521  Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3522
3523  AStruct a;
3524  EXPECT_TRUE(m.Matches(&a));
3525  a.x = -1;
3526  EXPECT_FALSE(m.Matches(&a));
3527}
3528
3529// Tests that Field() does not match the NULL pointer.
3530TEST(FieldForPointerTest, DoesNotMatchNull) {
3531  Matcher<const AStruct*> m = Field(&AStruct::x, _);
3532  EXPECT_FALSE(m.Matches(NULL));
3533}
3534
3535// Tests that Field(&Foo::field, ...) works when the argument's type
3536// is a sub-type of const Foo*.
3537TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3538  // Note that the matcher expects DerivedStruct but we say AStruct
3539  // inside Field().
3540  Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3541
3542  DerivedStruct d;
3543  EXPECT_TRUE(m.Matches(&d));
3544  d.x = -1;
3545  EXPECT_FALSE(m.Matches(&d));
3546}
3547
3548// Tests that Field() can describe itself when used to match a pointer.
3549TEST(FieldForPointerTest, CanDescribeSelf) {
3550  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3551
3552  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3553  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3554}
3555
3556// Tests that Field() can explain the result of matching a pointer.
3557TEST(FieldForPointerTest, CanExplainMatchResult) {
3558  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3559
3560  AStruct a;
3561  a.x = 1;
3562  EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
3563  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3564            Explain(m, &a));
3565
3566  m = Field(&AStruct::x, GreaterThan(0));
3567  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3568            ", which is 1 more than 0", Explain(m, &a));
3569}
3570
3571// A user-defined class for testing Property().
3572class AClass {
3573 public:
3574  AClass() : n_(0) {}
3575
3576  // A getter that returns a non-reference.
3577  int n() const { return n_; }
3578
3579  void set_n(int new_n) { n_ = new_n; }
3580
3581  // A getter that returns a reference to const.
3582  const string& s() const { return s_; }
3583
3584  void set_s(const string& new_s) { s_ = new_s; }
3585
3586  // A getter that returns a reference to non-const.
3587  double& x() const { return x_; }
3588 private:
3589  int n_;
3590  string s_;
3591
3592  static double x_;
3593};
3594
3595double AClass::x_ = 0.0;
3596
3597// A derived class for testing Property().
3598class DerivedClass : public AClass {
3599 public:
3600  int k() const { return k_; }
3601 private:
3602  int k_;
3603};
3604
3605// Tests that Property(&Foo::property, ...) works when property()
3606// returns a non-reference.
3607TEST(PropertyTest, WorksForNonReferenceProperty) {
3608  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3609
3610  AClass a;
3611  a.set_n(1);
3612  EXPECT_TRUE(m.Matches(a));
3613
3614  a.set_n(-1);
3615  EXPECT_FALSE(m.Matches(a));
3616}
3617
3618// Tests that Property(&Foo::property, ...) works when property()
3619// returns a reference to const.
3620TEST(PropertyTest, WorksForReferenceToConstProperty) {
3621  Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3622
3623  AClass a;
3624  a.set_s("hill");
3625  EXPECT_TRUE(m.Matches(a));
3626
3627  a.set_s("hole");
3628  EXPECT_FALSE(m.Matches(a));
3629}
3630
3631// Tests that Property(&Foo::property, ...) works when property()
3632// returns a reference to non-const.
3633TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3634  double x = 0.0;
3635  AClass a;
3636
3637  Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3638  EXPECT_FALSE(m.Matches(a));
3639
3640  m = Property(&AClass::x, Not(Ref(x)));
3641  EXPECT_TRUE(m.Matches(a));
3642}
3643
3644// Tests that Property(&Foo::property, ...) works when the argument is
3645// passed by value.
3646TEST(PropertyTest, WorksForByValueArgument) {
3647  Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3648
3649  AClass a;
3650  a.set_s("hill");
3651  EXPECT_TRUE(m.Matches(a));
3652
3653  a.set_s("hole");
3654  EXPECT_FALSE(m.Matches(a));
3655}
3656
3657// Tests that Property(&Foo::property, ...) works when the argument's
3658// type is a sub-type of Foo.
3659TEST(PropertyTest, WorksForArgumentOfSubType) {
3660  // The matcher expects a DerivedClass, but inside the Property() we
3661  // say AClass.
3662  Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3663
3664  DerivedClass d;
3665  d.set_n(1);
3666  EXPECT_TRUE(m.Matches(d));
3667
3668  d.set_n(-1);
3669  EXPECT_FALSE(m.Matches(d));
3670}
3671
3672// Tests that Property(&Foo::property, m) works when property()'s type
3673// and m's argument type are compatible but different.
3674TEST(PropertyTest, WorksForCompatibleMatcherType) {
3675  // n() returns an int but the inner matcher expects a signed char.
3676  Matcher<const AClass&> m = Property(&AClass::n,
3677                                      Matcher<signed char>(Ge(0)));
3678
3679  AClass a;
3680  EXPECT_TRUE(m.Matches(a));
3681  a.set_n(-1);
3682  EXPECT_FALSE(m.Matches(a));
3683}
3684
3685// Tests that Property() can describe itself.
3686TEST(PropertyTest, CanDescribeSelf) {
3687  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3688
3689  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3690  EXPECT_EQ("is an object whose given property isn't >= 0",
3691            DescribeNegation(m));
3692}
3693
3694// Tests that Property() can explain the match result.
3695TEST(PropertyTest, CanExplainMatchResult) {
3696  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3697
3698  AClass a;
3699  a.set_n(1);
3700  EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
3701
3702  m = Property(&AClass::n, GreaterThan(0));
3703  EXPECT_EQ(
3704      "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3705      Explain(m, a));
3706}
3707
3708// Tests that Property() works when the argument is a pointer to const.
3709TEST(PropertyForPointerTest, WorksForPointerToConst) {
3710  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3711
3712  AClass a;
3713  a.set_n(1);
3714  EXPECT_TRUE(m.Matches(&a));
3715
3716  a.set_n(-1);
3717  EXPECT_FALSE(m.Matches(&a));
3718}
3719
3720// Tests that Property() works when the argument is a pointer to non-const.
3721TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3722  Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3723
3724  AClass a;
3725  a.set_s("hill");
3726  EXPECT_TRUE(m.Matches(&a));
3727
3728  a.set_s("hole");
3729  EXPECT_FALSE(m.Matches(&a));
3730}
3731
3732// Tests that Property() works when the argument is a reference to a
3733// const pointer.
3734TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3735  Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3736
3737  AClass a;
3738  a.set_s("hill");
3739  EXPECT_TRUE(m.Matches(&a));
3740
3741  a.set_s("hole");
3742  EXPECT_FALSE(m.Matches(&a));
3743}
3744
3745// Tests that Property() does not match the NULL pointer.
3746TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3747  Matcher<const AClass*> m = Property(&AClass::x, _);
3748  EXPECT_FALSE(m.Matches(NULL));
3749}
3750
3751// Tests that Property(&Foo::property, ...) works when the argument's
3752// type is a sub-type of const Foo*.
3753TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3754  // The matcher expects a DerivedClass, but inside the Property() we
3755  // say AClass.
3756  Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3757
3758  DerivedClass d;
3759  d.set_n(1);
3760  EXPECT_TRUE(m.Matches(&d));
3761
3762  d.set_n(-1);
3763  EXPECT_FALSE(m.Matches(&d));
3764}
3765
3766// Tests that Property() can describe itself when used to match a pointer.
3767TEST(PropertyForPointerTest, CanDescribeSelf) {
3768  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3769
3770  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3771  EXPECT_EQ("is an object whose given property isn't >= 0",
3772            DescribeNegation(m));
3773}
3774
3775// Tests that Property() can explain the result of matching a pointer.
3776TEST(PropertyForPointerTest, CanExplainMatchResult) {
3777  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3778
3779  AClass a;
3780  a.set_n(1);
3781  EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
3782  EXPECT_EQ(
3783      "which points to an object whose given property is 1" + OfType("int"),
3784      Explain(m, &a));
3785
3786  m = Property(&AClass::n, GreaterThan(0));
3787  EXPECT_EQ("which points to an object whose given property is 1" +
3788            OfType("int") + ", which is 1 more than 0",
3789            Explain(m, &a));
3790}
3791
3792// Tests ResultOf.
3793
3794// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3795// function pointer.
3796string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3797
3798TEST(ResultOfTest, WorksForFunctionPointers) {
3799  Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3800
3801  EXPECT_TRUE(matcher.Matches(1));
3802  EXPECT_FALSE(matcher.Matches(2));
3803}
3804
3805// Tests that ResultOf() can describe itself.
3806TEST(ResultOfTest, CanDescribeItself) {
3807  Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3808
3809  EXPECT_EQ("is mapped by the given callable to a value that "
3810            "is equal to \"foo\"", Describe(matcher));
3811  EXPECT_EQ("is mapped by the given callable to a value that "
3812            "isn't equal to \"foo\"", DescribeNegation(matcher));
3813}
3814
3815// Tests that ResultOf() can explain the match result.
3816int IntFunction(int input) { return input == 42 ? 80 : 90; }
3817
3818TEST(ResultOfTest, CanExplainMatchResult) {
3819  Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
3820  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
3821            Explain(matcher, 36));
3822
3823  matcher = ResultOf(&IntFunction, GreaterThan(85));
3824  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3825            ", which is 5 more than 85", Explain(matcher, 36));
3826}
3827
3828// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3829// returns a non-reference.
3830TEST(ResultOfTest, WorksForNonReferenceResults) {
3831  Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3832
3833  EXPECT_TRUE(matcher.Matches(42));
3834  EXPECT_FALSE(matcher.Matches(36));
3835}
3836
3837// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3838// returns a reference to non-const.
3839double& DoubleFunction(double& input) { return input; }  // NOLINT
3840
3841Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
3842  return obj;
3843}
3844
3845TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3846  double x = 3.14;
3847  double x2 = x;
3848  Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3849
3850  EXPECT_TRUE(matcher.Matches(x));
3851  EXPECT_FALSE(matcher.Matches(x2));
3852
3853  // Test that ResultOf works with uncopyable objects
3854  Uncopyable obj(0);
3855  Uncopyable obj2(0);
3856  Matcher<Uncopyable&> matcher2 =
3857      ResultOf(&RefUncopyableFunction, Ref(obj));
3858
3859  EXPECT_TRUE(matcher2.Matches(obj));
3860  EXPECT_FALSE(matcher2.Matches(obj2));
3861}
3862
3863// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3864// returns a reference to const.
3865const string& StringFunction(const string& input) { return input; }
3866
3867TEST(ResultOfTest, WorksForReferenceToConstResults) {
3868  string s = "foo";
3869  string s2 = s;
3870  Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3871
3872  EXPECT_TRUE(matcher.Matches(s));
3873  EXPECT_FALSE(matcher.Matches(s2));
3874}
3875
3876// Tests that ResultOf(f, m) works when f(x) and m's
3877// argument types are compatible but different.
3878TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3879  // IntFunction() returns int but the inner matcher expects a signed char.
3880  Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3881
3882  EXPECT_TRUE(matcher.Matches(36));
3883  EXPECT_FALSE(matcher.Matches(42));
3884}
3885
3886// Tests that the program aborts when ResultOf is passed
3887// a NULL function pointer.
3888TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
3889  EXPECT_DEATH_IF_SUPPORTED(
3890      ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
3891               "NULL function pointer is passed into ResultOf\\(\\)\\.");
3892}
3893
3894// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3895// function reference.
3896TEST(ResultOfTest, WorksForFunctionReferences) {
3897  Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3898  EXPECT_TRUE(matcher.Matches(1));
3899  EXPECT_FALSE(matcher.Matches(2));
3900}
3901
3902// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3903// function object.
3904struct Functor : public ::std::unary_function<int, string> {
3905  result_type operator()(argument_type input) const {
3906    return IntToStringFunction(input);
3907  }
3908};
3909
3910TEST(ResultOfTest, WorksForFunctors) {
3911  Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3912
3913  EXPECT_TRUE(matcher.Matches(1));
3914  EXPECT_FALSE(matcher.Matches(2));
3915}
3916
3917// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3918// functor with more then one operator() defined. ResultOf() must work
3919// for each defined operator().
3920struct PolymorphicFunctor {
3921  typedef int result_type;
3922  int operator()(int n) { return n; }
3923  int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3924};
3925
3926TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3927  Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3928
3929  EXPECT_TRUE(matcher_int.Matches(10));
3930  EXPECT_FALSE(matcher_int.Matches(2));
3931
3932  Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3933
3934  EXPECT_TRUE(matcher_string.Matches("long string"));
3935  EXPECT_FALSE(matcher_string.Matches("shrt"));
3936}
3937
3938const int* ReferencingFunction(const int& n) { return &n; }
3939
3940struct ReferencingFunctor {
3941  typedef const int* result_type;
3942  result_type operator()(const int& n) { return &n; }
3943};
3944
3945TEST(ResultOfTest, WorksForReferencingCallables) {
3946  const int n = 1;
3947  const int n2 = 1;
3948  Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3949  EXPECT_TRUE(matcher2.Matches(n));
3950  EXPECT_FALSE(matcher2.Matches(n2));
3951
3952  Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3953  EXPECT_TRUE(matcher3.Matches(n));
3954  EXPECT_FALSE(matcher3.Matches(n2));
3955}
3956
3957class DivisibleByImpl {
3958 public:
3959  explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
3960
3961  // For testing using ExplainMatchResultTo() with polymorphic matchers.
3962  template <typename T>
3963  bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
3964    *listener << "which is " << (n % divider_) << " modulo "
3965              << divider_;
3966    return (n % divider_) == 0;
3967  }
3968
3969  void DescribeTo(ostream* os) const {
3970    *os << "is divisible by " << divider_;
3971  }
3972
3973  void DescribeNegationTo(ostream* os) const {
3974    *os << "is not divisible by " << divider_;
3975  }
3976
3977  void set_divider(int a_divider) { divider_ = a_divider; }
3978  int divider() const { return divider_; }
3979
3980 private:
3981  int divider_;
3982};
3983
3984PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3985  return MakePolymorphicMatcher(DivisibleByImpl(n));
3986}
3987
3988// Tests that when AllOf() fails, only the first failing matcher is
3989// asked to explain why.
3990TEST(ExplainMatchResultTest, AllOf_False_False) {
3991  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
3992  EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
3993}
3994
3995// Tests that when AllOf() fails, only the first failing matcher is
3996// asked to explain why.
3997TEST(ExplainMatchResultTest, AllOf_False_True) {
3998  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
3999  EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4000}
4001
4002// Tests that when AllOf() fails, only the first failing matcher is
4003// asked to explain why.
4004TEST(ExplainMatchResultTest, AllOf_True_False) {
4005  const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4006  EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4007}
4008
4009// Tests that when AllOf() succeeds, all matchers are asked to explain
4010// why.
4011TEST(ExplainMatchResultTest, AllOf_True_True) {
4012  const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4013  EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4014}
4015
4016TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4017  const Matcher<int> m = AllOf(Ge(2), Le(3));
4018  EXPECT_EQ("", Explain(m, 2));
4019}
4020
4021TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4022  const Matcher<int> m = GreaterThan(5);
4023  EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4024}
4025
4026// The following two tests verify that values without a public copy
4027// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4028// with the help of ByRef().
4029
4030class NotCopyable {
4031 public:
4032  explicit NotCopyable(int a_value) : value_(a_value) {}
4033
4034  int value() const { return value_; }
4035
4036  bool operator==(const NotCopyable& rhs) const {
4037    return value() == rhs.value();
4038  }
4039
4040  bool operator>=(const NotCopyable& rhs) const {
4041    return value() >= rhs.value();
4042  }
4043 private:
4044  int value_;
4045
4046  GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4047};
4048
4049TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4050  const NotCopyable const_value1(1);
4051  const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4052
4053  const NotCopyable n1(1), n2(2);
4054  EXPECT_TRUE(m.Matches(n1));
4055  EXPECT_FALSE(m.Matches(n2));
4056}
4057
4058TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4059  NotCopyable value2(2);
4060  const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4061
4062  NotCopyable n1(1), n2(2);
4063  EXPECT_FALSE(m.Matches(n1));
4064  EXPECT_TRUE(m.Matches(n2));
4065}
4066
4067TEST(IsEmptyTest, ImplementsIsEmpty) {
4068  vector<int> container;
4069  EXPECT_THAT(container, IsEmpty());
4070  container.push_back(0);
4071  EXPECT_THAT(container, Not(IsEmpty()));
4072  container.push_back(1);
4073  EXPECT_THAT(container, Not(IsEmpty()));
4074}
4075
4076TEST(IsEmptyTest, WorksWithString) {
4077  string text;
4078  EXPECT_THAT(text, IsEmpty());
4079  text = "foo";
4080  EXPECT_THAT(text, Not(IsEmpty()));
4081  text = string("\0", 1);
4082  EXPECT_THAT(text, Not(IsEmpty()));
4083}
4084
4085TEST(IsEmptyTest, CanDescribeSelf) {
4086  Matcher<vector<int> > m = IsEmpty();
4087  EXPECT_EQ("is empty", Describe(m));
4088  EXPECT_EQ("isn't empty", DescribeNegation(m));
4089}
4090
4091TEST(IsEmptyTest, ExplainsResult) {
4092  Matcher<vector<int> > m = IsEmpty();
4093  vector<int> container;
4094  EXPECT_EQ("", Explain(m, container));
4095  container.push_back(0);
4096  EXPECT_EQ("whose size is 1", Explain(m, container));
4097}
4098
4099TEST(SizeIsTest, ImplementsSizeIs) {
4100  vector<int> container;
4101  EXPECT_THAT(container, SizeIs(0));
4102  EXPECT_THAT(container, Not(SizeIs(1)));
4103  container.push_back(0);
4104  EXPECT_THAT(container, Not(SizeIs(0)));
4105  EXPECT_THAT(container, SizeIs(1));
4106  container.push_back(0);
4107  EXPECT_THAT(container, Not(SizeIs(0)));
4108  EXPECT_THAT(container, SizeIs(2));
4109}
4110
4111TEST(SizeIsTest, WorksWithMap) {
4112  map<string, int> container;
4113  EXPECT_THAT(container, SizeIs(0));
4114  EXPECT_THAT(container, Not(SizeIs(1)));
4115  container.insert(make_pair("foo", 1));
4116  EXPECT_THAT(container, Not(SizeIs(0)));
4117  EXPECT_THAT(container, SizeIs(1));
4118  container.insert(make_pair("bar", 2));
4119  EXPECT_THAT(container, Not(SizeIs(0)));
4120  EXPECT_THAT(container, SizeIs(2));
4121}
4122
4123TEST(SizeIsTest, WorksWithReferences) {
4124  vector<int> container;
4125  Matcher<const vector<int>&> m = SizeIs(1);
4126  EXPECT_THAT(container, Not(m));
4127  container.push_back(0);
4128  EXPECT_THAT(container, m);
4129}
4130
4131TEST(SizeIsTest, CanDescribeSelf) {
4132  Matcher<vector<int> > m = SizeIs(2);
4133  EXPECT_EQ("size is equal to 2", Describe(m));
4134  EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4135}
4136
4137TEST(SizeIsTest, ExplainsResult) {
4138  Matcher<vector<int> > m1 = SizeIs(2);
4139  Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4140  Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4141  Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4142  vector<int> container;
4143  EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4144  EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4145  EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4146  EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4147            Explain(m4, container));
4148  container.push_back(0);
4149  container.push_back(0);
4150  EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4151  EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4152  EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4153  EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4154            Explain(m4, container));
4155}
4156
4157#if GTEST_HAS_TYPED_TEST
4158// Tests ContainerEq with different container types, and
4159// different element types.
4160
4161template <typename T>
4162class ContainerEqTest : public testing::Test {};
4163
4164typedef testing::Types<
4165    set<int>,
4166    vector<size_t>,
4167    multiset<size_t>,
4168    list<int> >
4169    ContainerEqTestTypes;
4170
4171TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4172
4173// Tests that the filled container is equal to itself.
4174TYPED_TEST(ContainerEqTest, EqualsSelf) {
4175  static const int vals[] = {1, 1, 2, 3, 5, 8};
4176  TypeParam my_set(vals, vals + 6);
4177  const Matcher<TypeParam> m = ContainerEq(my_set);
4178  EXPECT_TRUE(m.Matches(my_set));
4179  EXPECT_EQ("", Explain(m, my_set));
4180}
4181
4182// Tests that missing values are reported.
4183TYPED_TEST(ContainerEqTest, ValueMissing) {
4184  static const int vals[] = {1, 1, 2, 3, 5, 8};
4185  static const int test_vals[] = {2, 1, 8, 5};
4186  TypeParam my_set(vals, vals + 6);
4187  TypeParam test_set(test_vals, test_vals + 4);
4188  const Matcher<TypeParam> m = ContainerEq(my_set);
4189  EXPECT_FALSE(m.Matches(test_set));
4190  EXPECT_EQ("which doesn't have these expected elements: 3",
4191            Explain(m, test_set));
4192}
4193
4194// Tests that added values are reported.
4195TYPED_TEST(ContainerEqTest, ValueAdded) {
4196  static const int vals[] = {1, 1, 2, 3, 5, 8};
4197  static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4198  TypeParam my_set(vals, vals + 6);
4199  TypeParam test_set(test_vals, test_vals + 6);
4200  const Matcher<const TypeParam&> m = ContainerEq(my_set);
4201  EXPECT_FALSE(m.Matches(test_set));
4202  EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
4203}
4204
4205// Tests that added and missing values are reported together.
4206TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4207  static const int vals[] = {1, 1, 2, 3, 5, 8};
4208  static const int test_vals[] = {1, 2, 3, 8, 46};
4209  TypeParam my_set(vals, vals + 6);
4210  TypeParam test_set(test_vals, test_vals + 5);
4211  const Matcher<TypeParam> m = ContainerEq(my_set);
4212  EXPECT_FALSE(m.Matches(test_set));
4213  EXPECT_EQ("which has these unexpected elements: 46,\n"
4214            "and doesn't have these expected elements: 5",
4215            Explain(m, test_set));
4216}
4217
4218// Tests duplicated value -- expect no explanation.
4219TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4220  static const int vals[] = {1, 1, 2, 3, 5, 8};
4221  static const int test_vals[] = {1, 2, 3, 5, 8};
4222  TypeParam my_set(vals, vals + 6);
4223  TypeParam test_set(test_vals, test_vals + 5);
4224  const Matcher<const TypeParam&> m = ContainerEq(my_set);
4225  // Depending on the container, match may be true or false
4226  // But in any case there should be no explanation.
4227  EXPECT_EQ("", Explain(m, test_set));
4228}
4229#endif  // GTEST_HAS_TYPED_TEST
4230
4231// Tests that mutliple missing values are reported.
4232// Using just vector here, so order is predicatble.
4233TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4234  static const int vals[] = {1, 1, 2, 3, 5, 8};
4235  static const int test_vals[] = {2, 1, 5};
4236  vector<int> my_set(vals, vals + 6);
4237  vector<int> test_set(test_vals, test_vals + 3);
4238  const Matcher<vector<int> > m = ContainerEq(my_set);
4239  EXPECT_FALSE(m.Matches(test_set));
4240  EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4241            Explain(m, test_set));
4242}
4243
4244// Tests that added values are reported.
4245// Using just vector here, so order is predicatble.
4246TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4247  static const int vals[] = {1, 1, 2, 3, 5, 8};
4248  static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
4249  list<size_t> my_set(vals, vals + 6);
4250  list<size_t> test_set(test_vals, test_vals + 7);
4251  const Matcher<const list<size_t>&> m = ContainerEq(my_set);
4252  EXPECT_FALSE(m.Matches(test_set));
4253  EXPECT_EQ("which has these unexpected elements: 92, 46",
4254            Explain(m, test_set));
4255}
4256
4257// Tests that added and missing values are reported together.
4258TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4259  static const int vals[] = {1, 1, 2, 3, 5, 8};
4260  static const int test_vals[] = {1, 2, 3, 92, 46};
4261  list<size_t> my_set(vals, vals + 6);
4262  list<size_t> test_set(test_vals, test_vals + 5);
4263  const Matcher<const list<size_t> > m = ContainerEq(my_set);
4264  EXPECT_FALSE(m.Matches(test_set));
4265  EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4266            "and doesn't have these expected elements: 5, 8",
4267            Explain(m, test_set));
4268}
4269
4270// Tests to see that duplicate elements are detected,
4271// but (as above) not reported in the explanation.
4272TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4273  static const int vals[] = {1, 1, 2, 3, 5, 8};
4274  static const int test_vals[] = {1, 2, 3, 5, 8};
4275  vector<int> my_set(vals, vals + 6);
4276  vector<int> test_set(test_vals, test_vals + 5);
4277  const Matcher<vector<int> > m = ContainerEq(my_set);
4278  EXPECT_TRUE(m.Matches(my_set));
4279  EXPECT_FALSE(m.Matches(test_set));
4280  // There is nothing to report when both sets contain all the same values.
4281  EXPECT_EQ("", Explain(m, test_set));
4282}
4283
4284// Tests that ContainerEq works for non-trivial associative containers,
4285// like maps.
4286TEST(ContainerEqExtraTest, WorksForMaps) {
4287  map<int, std::string> my_map;
4288  my_map[0] = "a";
4289  my_map[1] = "b";
4290
4291  map<int, std::string> test_map;
4292  test_map[0] = "aa";
4293  test_map[1] = "b";
4294
4295  const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
4296  EXPECT_TRUE(m.Matches(my_map));
4297  EXPECT_FALSE(m.Matches(test_map));
4298
4299  EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4300            "and doesn't have these expected elements: (0, \"a\")",
4301            Explain(m, test_map));
4302}
4303
4304TEST(ContainerEqExtraTest, WorksForNativeArray) {
4305  int a1[] = {1, 2, 3};
4306  int a2[] = {1, 2, 3};
4307  int b[] = {1, 2, 4};
4308
4309  EXPECT_THAT(a1, ContainerEq(a2));
4310  EXPECT_THAT(a1, Not(ContainerEq(b)));
4311}
4312
4313TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4314  const char a1[][3] = {"hi", "lo"};
4315  const char a2[][3] = {"hi", "lo"};
4316  const char b[][3] = {"lo", "hi"};
4317
4318  // Tests using ContainerEq() in the first dimension.
4319  EXPECT_THAT(a1, ContainerEq(a2));
4320  EXPECT_THAT(a1, Not(ContainerEq(b)));
4321
4322  // Tests using ContainerEq() in the second dimension.
4323  EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4324  EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4325}
4326
4327TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4328  const int a1[] = {1, 2, 3};
4329  const int a2[] = {1, 2, 3};
4330  const int b[] = {1, 2, 3, 4};
4331
4332  const int* const p1 = a1;
4333  EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4334  EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
4335
4336  const int c[] = {1, 3, 2};
4337  EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
4338}
4339
4340TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4341  std::string a1[][3] = {
4342    {"hi", "hello", "ciao"},
4343    {"bye", "see you", "ciao"}
4344  };
4345
4346  std::string a2[][3] = {
4347    {"hi", "hello", "ciao"},
4348    {"bye", "see you", "ciao"}
4349  };
4350
4351  const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4352  EXPECT_THAT(a1, m);
4353
4354  a2[0][0] = "ha";
4355  EXPECT_THAT(a1, m);
4356}
4357
4358TEST(WhenSortedByTest, WorksForEmptyContainer) {
4359  const vector<int> numbers;
4360  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4361  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4362}
4363
4364TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4365  vector<unsigned> numbers;
4366  numbers.push_back(3);
4367  numbers.push_back(1);
4368  numbers.push_back(2);
4369  numbers.push_back(2);
4370  EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4371                                    ElementsAre(3, 2, 2, 1)));
4372  EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4373                                        ElementsAre(1, 2, 2, 3))));
4374}
4375
4376TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4377  list<string> words;
4378  words.push_back("say");
4379  words.push_back("hello");
4380  words.push_back("world");
4381  EXPECT_THAT(words, WhenSortedBy(less<string>(),
4382                                  ElementsAre("hello", "say", "world")));
4383  EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4384                                      ElementsAre("say", "hello", "world"))));
4385}
4386
4387TEST(WhenSortedByTest, WorksForNativeArray) {
4388  const int numbers[] = {1, 3, 2, 4};
4389  const int sorted_numbers[] = {1, 2, 3, 4};
4390  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4391  EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4392                                    ElementsAreArray(sorted_numbers)));
4393  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4394}
4395
4396TEST(WhenSortedByTest, CanDescribeSelf) {
4397  const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4398  EXPECT_EQ("(when sorted) has 2 elements where\n"
4399            "element #0 is equal to 1,\n"
4400            "element #1 is equal to 2",
4401            Describe(m));
4402  EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4403            "element #0 isn't equal to 1, or\n"
4404            "element #1 isn't equal to 2",
4405            DescribeNegation(m));
4406}
4407
4408TEST(WhenSortedByTest, ExplainsMatchResult) {
4409  const int a[] = {2, 1};
4410  EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4411            Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4412  EXPECT_EQ("which is { 1, 2 } when sorted",
4413            Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4414}
4415
4416// WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
4417// need to test it as exhaustively as we test the latter.
4418
4419TEST(WhenSortedTest, WorksForEmptyContainer) {
4420  const vector<int> numbers;
4421  EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4422  EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4423}
4424
4425TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4426  list<string> words;
4427  words.push_back("3");
4428  words.push_back("1");
4429  words.push_back("2");
4430  words.push_back("2");
4431  EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4432  EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4433}
4434
4435TEST(WhenSortedTest, WorksForMapTypes) {
4436    map<string, int> word_counts;
4437    word_counts["and"] = 1;
4438    word_counts["the"] = 1;
4439    word_counts["buffalo"] = 2;
4440    EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4441            Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4442    EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4443            Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4444}
4445
4446TEST(WhenSortedTest, WorksForMultiMapTypes) {
4447    multimap<int, int> ifib;
4448    ifib.insert(make_pair(8, 6));
4449    ifib.insert(make_pair(2, 3));
4450    ifib.insert(make_pair(1, 1));
4451    ifib.insert(make_pair(3, 4));
4452    ifib.insert(make_pair(1, 2));
4453    ifib.insert(make_pair(5, 5));
4454    EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4455                                             Pair(1, 2),
4456                                             Pair(2, 3),
4457                                             Pair(3, 4),
4458                                             Pair(5, 5),
4459                                             Pair(8, 6))));
4460    EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4461                                                 Pair(2, 3),
4462                                                 Pair(1, 1),
4463                                                 Pair(3, 4),
4464                                                 Pair(1, 2),
4465                                                 Pair(5, 5)))));
4466}
4467
4468TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4469    std::deque<int> d;
4470    d.push_back(2);
4471    d.push_back(1);
4472    EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4473    EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4474}
4475
4476TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4477    std::deque<int> d;
4478    d.push_back(2);
4479    d.push_back(1);
4480    Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4481    EXPECT_THAT(d, WhenSorted(vector_match));
4482    Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4483    EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4484}
4485
4486// Deliberately bare pseudo-container.
4487// Offers only begin() and end() accessors, yielding InputIterator.
4488template <typename T>
4489class Streamlike {
4490 private:
4491  class ConstIter;
4492 public:
4493  typedef ConstIter const_iterator;
4494  typedef T value_type;
4495
4496  template <typename InIter>
4497  Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4498
4499  const_iterator begin() const {
4500    return const_iterator(this, remainder_.begin());
4501  }
4502  const_iterator end() const {
4503    return const_iterator(this, remainder_.end());
4504  }
4505
4506 private:
4507  class ConstIter : public std::iterator<std::input_iterator_tag,
4508                                         value_type,
4509                                         ptrdiff_t,
4510                                         const value_type*,
4511                                         const value_type&> {
4512   public:
4513    ConstIter(const Streamlike* s,
4514              typename std::list<value_type>::iterator pos)
4515        : s_(s), pos_(pos) {}
4516
4517    const value_type& operator*() const { return *pos_; }
4518    const value_type* operator->() const { return &*pos_; }
4519    ConstIter& operator++() {
4520      s_->remainder_.erase(pos_++);
4521      return *this;
4522    }
4523
4524    // *iter++ is required to work (see std::istreambuf_iterator).
4525    // (void)iter++ is also required to work.
4526    class PostIncrProxy {
4527     public:
4528      explicit PostIncrProxy(const value_type& value) : value_(value) {}
4529      value_type operator*() const { return value_; }
4530     private:
4531      value_type value_;
4532    };
4533    PostIncrProxy operator++(int) {
4534      PostIncrProxy proxy(**this);
4535      ++(*this);
4536      return proxy;
4537    }
4538
4539    friend bool operator==(const ConstIter& a, const ConstIter& b) {
4540      return a.s_ == b.s_ && a.pos_ == b.pos_;
4541    }
4542    friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4543      return !(a == b);
4544    }
4545
4546   private:
4547    const Streamlike* s_;
4548    typename std::list<value_type>::iterator pos_;
4549  };
4550
4551  friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4552    os << "[";
4553    typedef typename std::list<value_type>::const_iterator Iter;
4554    const char* sep = "";
4555    for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4556      os << sep << *it;
4557      sep = ",";
4558    }
4559    os << "]";
4560    return os;
4561  }
4562
4563  mutable std::list<value_type> remainder_;  // modified by iteration
4564};
4565
4566TEST(StreamlikeTest, Iteration) {
4567  const int a[5] = {2, 1, 4, 5, 3};
4568  Streamlike<int> s(a, a + 5);
4569  Streamlike<int>::const_iterator it = s.begin();
4570  const int* ip = a;
4571  while (it != s.end()) {
4572    SCOPED_TRACE(ip - a);
4573    EXPECT_EQ(*ip++, *it++);
4574  }
4575}
4576
4577#if GTEST_HAS_STD_FORWARD_LIST_
4578TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4579  std::forward_list<int> container;
4580  EXPECT_THAT(container, BeginEndDistanceIs(0));
4581  EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4582  container.push_front(0);
4583  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4584  EXPECT_THAT(container, BeginEndDistanceIs(1));
4585  container.push_front(0);
4586  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4587  EXPECT_THAT(container, BeginEndDistanceIs(2));
4588}
4589#endif  // GTEST_HAS_STD_FORWARD_LIST_
4590
4591TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
4592  const int a[5] = {1, 2, 3, 4, 5};
4593  Streamlike<int> s(a, a + 5);
4594  EXPECT_THAT(s, BeginEndDistanceIs(5));
4595}
4596
4597TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4598  Matcher<vector<int> > m = BeginEndDistanceIs(2);
4599  EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4600  EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4601            DescribeNegation(m));
4602}
4603
4604TEST(BeginEndDistanceIsTest, ExplainsResult) {
4605  Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4606  Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4607  Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4608  Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4609  vector<int> container;
4610  EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4611            Explain(m1, container));
4612  EXPECT_EQ("whose distance between begin() and end() 0 matches",
4613            Explain(m2, container));
4614  EXPECT_EQ("whose distance between begin() and end() 0 matches",
4615            Explain(m3, container));
4616  EXPECT_EQ(
4617      "whose distance between begin() and end() 0 doesn't match, which is 1 "
4618      "less than 1",
4619      Explain(m4, container));
4620  container.push_back(0);
4621  container.push_back(0);
4622  EXPECT_EQ("whose distance between begin() and end() 2 matches",
4623            Explain(m1, container));
4624  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4625            Explain(m2, container));
4626  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4627            Explain(m3, container));
4628  EXPECT_EQ(
4629      "whose distance between begin() and end() 2 matches, which is 1 more "
4630      "than 1",
4631      Explain(m4, container));
4632}
4633
4634TEST(WhenSortedTest, WorksForStreamlike) {
4635  // Streamlike 'container' provides only minimal iterator support.
4636  // Its iterators are tagged with input_iterator_tag.
4637  const int a[5] = {2, 1, 4, 5, 3};
4638  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4639  EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4640  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4641}
4642
4643TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
4644  const int a[] = {2, 1, 4, 5, 3};
4645  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4646  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4647  EXPECT_THAT(s, WhenSorted(vector_match));
4648  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4649}
4650
4651// Tests using ElementsAre() and ElementsAreArray() with stream-like
4652// "containers".
4653
4654TEST(ElemensAreStreamTest, WorksForStreamlike) {
4655  const int a[5] = {1, 2, 3, 4, 5};
4656  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4657  EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4658  EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4659}
4660
4661TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4662  const int a[5] = {1, 2, 3, 4, 5};
4663  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4664
4665  vector<int> expected;
4666  expected.push_back(1);
4667  expected.push_back(2);
4668  expected.push_back(3);
4669  expected.push_back(4);
4670  expected.push_back(5);
4671  EXPECT_THAT(s, ElementsAreArray(expected));
4672
4673  expected[3] = 0;
4674  EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4675}
4676
4677TEST(ElementsAreTest, WorksWithUncopyable) {
4678  Uncopyable objs[2];
4679  objs[0].set_value(-3);
4680  objs[1].set_value(1);
4681  EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4682}
4683
4684TEST(ElementsAreTest, TakesStlContainer) {
4685  const int actual[] = {3, 1, 2};
4686
4687  ::std::list<int> expected;
4688  expected.push_back(3);
4689  expected.push_back(1);
4690  expected.push_back(2);
4691  EXPECT_THAT(actual, ElementsAreArray(expected));
4692
4693  expected.push_back(4);
4694  EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4695}
4696
4697// Tests for UnorderedElementsAreArray()
4698
4699TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4700  const int a[] = {0, 1, 2, 3, 4};
4701  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4702  do {
4703    StringMatchResultListener listener;
4704    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4705                                   s, &listener)) << listener.str();
4706  } while (std::next_permutation(s.begin(), s.end()));
4707}
4708
4709TEST(UnorderedElementsAreArrayTest, VectorBool) {
4710  const bool a[] = {0, 1, 0, 1, 1};
4711  const bool b[] = {1, 0, 1, 1, 0};
4712  std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4713  std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
4714  StringMatchResultListener listener;
4715  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4716                                 actual, &listener)) << listener.str();
4717}
4718
4719TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4720  // Streamlike 'container' provides only minimal iterator support.
4721  // Its iterators are tagged with input_iterator_tag, and it has no
4722  // size() or empty() methods.
4723  const int a[5] = {2, 1, 4, 5, 3};
4724  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4725
4726  ::std::vector<int> expected;
4727  expected.push_back(1);
4728  expected.push_back(2);
4729  expected.push_back(3);
4730  expected.push_back(4);
4731  expected.push_back(5);
4732  EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4733
4734  expected.push_back(6);
4735  EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4736}
4737
4738TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4739  const int actual[] = {3, 1, 2};
4740
4741  ::std::list<int> expected;
4742  expected.push_back(1);
4743  expected.push_back(2);
4744  expected.push_back(3);
4745  EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4746
4747  expected.push_back(4);
4748  EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4749}
4750
4751#if GTEST_HAS_STD_INITIALIZER_LIST_
4752
4753TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4754  const int a[5] = {2, 1, 4, 5, 3};
4755  EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4756  EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
4757}
4758
4759TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4760  const string a[5] = {"a", "b", "c", "d", "e"};
4761  EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4762  EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
4763}
4764
4765TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4766  const int a[5] = {2, 1, 4, 5, 3};
4767  EXPECT_THAT(a, UnorderedElementsAreArray(
4768      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
4769  EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4770      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
4771}
4772
4773TEST(UnorderedElementsAreArrayTest,
4774     TakesInitializerListOfDifferentTypedMatchers) {
4775  const int a[5] = {2, 1, 4, 5, 3};
4776  // The compiler cannot infer the type of the initializer list if its
4777  // elements have different types.  We must explicitly specify the
4778  // unified element type in this case.
4779  EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4780      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
4781  EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4782      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
4783}
4784
4785#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4786
4787class UnorderedElementsAreTest : public testing::Test {
4788 protected:
4789  typedef std::vector<int> IntVec;
4790};
4791
4792TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4793  Uncopyable objs[2];
4794  objs[0].set_value(-3);
4795  objs[1].set_value(1);
4796  EXPECT_THAT(objs,
4797              UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4798}
4799
4800TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4801  const int a[] = {1, 2, 3};
4802  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4803  do {
4804    StringMatchResultListener listener;
4805    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4806                                   s, &listener)) << listener.str();
4807  } while (std::next_permutation(s.begin(), s.end()));
4808}
4809
4810TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4811  const int a[] = {1, 2, 3};
4812  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4813  std::vector<Matcher<int> > mv;
4814  mv.push_back(1);
4815  mv.push_back(2);
4816  mv.push_back(2);
4817  // The element with value '3' matches nothing: fail fast.
4818  StringMatchResultListener listener;
4819  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4820                                  s, &listener)) << listener.str();
4821}
4822
4823TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4824  // Streamlike 'container' provides only minimal iterator support.
4825  // Its iterators are tagged with input_iterator_tag, and it has no
4826  // size() or empty() methods.
4827  const int a[5] = {2, 1, 4, 5, 3};
4828  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4829
4830  EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4831  EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4832}
4833
4834// One naive implementation of the matcher runs in O(N!) time, which is too
4835// slow for many real-world inputs. This test shows that our matcher can match
4836// 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158
4837// iterations and obviously effectively incomputable.
4838// [ RUN      ] UnorderedElementsAreTest.Performance
4839// [       OK ] UnorderedElementsAreTest.Performance (4 ms)
4840TEST_F(UnorderedElementsAreTest, Performance) {
4841  std::vector<int> s;
4842  std::vector<Matcher<int> > mv;
4843  for (int i = 0; i < 100; ++i) {
4844    s.push_back(i);
4845    mv.push_back(_);
4846  }
4847  mv[50] = Eq(0);
4848  StringMatchResultListener listener;
4849  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4850                                 s, &listener)) << listener.str();
4851}
4852
4853// Another variant of 'Performance' with similar expectations.
4854// [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
4855// [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4856TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4857  std::vector<int> s;
4858  std::vector<Matcher<int> > mv;
4859  for (int i = 0; i < 100; ++i) {
4860    s.push_back(i);
4861    if (i & 1) {
4862      mv.push_back(_);
4863    } else {
4864      mv.push_back(i);
4865    }
4866  }
4867  StringMatchResultListener listener;
4868  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4869                                 s, &listener)) << listener.str();
4870}
4871
4872TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4873  std::vector<int> v;
4874  v.push_back(4);
4875  StringMatchResultListener listener;
4876  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4877                                  v, &listener)) << listener.str();
4878  EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4879}
4880
4881TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4882  std::vector<int> v;
4883  StringMatchResultListener listener;
4884  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4885                                  v, &listener)) << listener.str();
4886  EXPECT_THAT(listener.str(), Eq(""));
4887}
4888
4889TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4890  std::vector<int> v;
4891  v.push_back(1);
4892  v.push_back(1);
4893  StringMatchResultListener listener;
4894  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4895                                  v, &listener)) << listener.str();
4896  EXPECT_THAT(
4897      listener.str(),
4898      Eq("where the following matchers don't match any elements:\n"
4899         "matcher #1: is equal to 2"));
4900}
4901
4902TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4903  std::vector<int> v;
4904  v.push_back(1);
4905  v.push_back(2);
4906  StringMatchResultListener listener;
4907  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4908                                  v, &listener)) << listener.str();
4909  EXPECT_THAT(
4910      listener.str(),
4911      Eq("where the following elements don't match any matchers:\n"
4912         "element #1: 2"));
4913}
4914
4915TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4916  std::vector<int> v;
4917  v.push_back(2);
4918  v.push_back(3);
4919  StringMatchResultListener listener;
4920  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4921                                  v, &listener)) << listener.str();
4922  EXPECT_THAT(
4923      listener.str(),
4924      Eq("where"
4925         " the following matchers don't match any elements:\n"
4926         "matcher #0: is equal to 1\n"
4927         "and"
4928         " where"
4929         " the following elements don't match any matchers:\n"
4930         "element #1: 3"));
4931}
4932
4933// Test helper for formatting element, matcher index pairs in expectations.
4934static string EMString(int element, int matcher) {
4935  stringstream ss;
4936  ss << "(element #" << element << ", matcher #" << matcher << ")";
4937  return ss.str();
4938}
4939
4940TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4941  // A situation where all elements and matchers have a match
4942  // associated with them, but the max matching is not perfect.
4943  std::vector<string> v;
4944  v.push_back("a");
4945  v.push_back("b");
4946  v.push_back("c");
4947  StringMatchResultListener listener;
4948  EXPECT_FALSE(ExplainMatchResult(
4949      UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4950      << listener.str();
4951
4952  string prefix =
4953      "where no permutation of the elements can satisfy all matchers, "
4954      "and the closest match is 2 of 3 matchers with the "
4955      "pairings:\n";
4956
4957  // We have to be a bit loose here, because there are 4 valid max matches.
4958  EXPECT_THAT(
4959      listener.str(),
4960      AnyOf(prefix + "{\n  " + EMString(0, 0) +
4961                     ",\n  " + EMString(1, 2) + "\n}",
4962            prefix + "{\n  " + EMString(0, 1) +
4963                     ",\n  " + EMString(1, 2) + "\n}",
4964            prefix + "{\n  " + EMString(0, 0) +
4965                     ",\n  " + EMString(2, 2) + "\n}",
4966            prefix + "{\n  " + EMString(0, 1) +
4967                     ",\n  " + EMString(2, 2) + "\n}"));
4968}
4969
4970TEST_F(UnorderedElementsAreTest, Describe) {
4971  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4972              Eq("is empty"));
4973  EXPECT_THAT(
4974      Describe<IntVec>(UnorderedElementsAre(345)),
4975      Eq("has 1 element and that element is equal to 345"));
4976  EXPECT_THAT(
4977      Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4978      Eq("has 3 elements and there exists some permutation "
4979         "of elements such that:\n"
4980         " - element #0 is equal to 111, and\n"
4981         " - element #1 is equal to 222, and\n"
4982         " - element #2 is equal to 333"));
4983}
4984
4985TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4986  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4987              Eq("isn't empty"));
4988  EXPECT_THAT(
4989      DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4990      Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4991  EXPECT_THAT(
4992      DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4993      Eq("doesn't have 3 elements, or there exists no permutation "
4994         "of elements such that:\n"
4995         " - element #0 is equal to 123, and\n"
4996         " - element #1 is equal to 234, and\n"
4997         " - element #2 is equal to 345"));
4998}
4999
5000namespace {
5001
5002// Used as a check on the more complex max flow method used in the
5003// real testing::internal::FindMaxBipartiteMatching. This method is
5004// compatible but runs in worst-case factorial time, so we only
5005// use it in testing for small problem sizes.
5006template <typename Graph>
5007class BacktrackingMaxBPMState {
5008 public:
5009  // Does not take ownership of 'g'.
5010  explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5011
5012  ElementMatcherPairs Compute() {
5013    if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5014      return best_so_far_;
5015    }
5016    lhs_used_.assign(graph_->LhsSize(), kUnused);
5017    rhs_used_.assign(graph_->RhsSize(), kUnused);
5018    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5019      matches_.clear();
5020      RecurseInto(irhs);
5021      if (best_so_far_.size() == graph_->RhsSize())
5022        break;
5023    }
5024    return best_so_far_;
5025  }
5026
5027 private:
5028  static const size_t kUnused = static_cast<size_t>(-1);
5029
5030  void PushMatch(size_t lhs, size_t rhs) {
5031    matches_.push_back(ElementMatcherPair(lhs, rhs));
5032    lhs_used_[lhs] = rhs;
5033    rhs_used_[rhs] = lhs;
5034    if (matches_.size() > best_so_far_.size()) {
5035      best_so_far_ = matches_;
5036    }
5037  }
5038
5039  void PopMatch() {
5040    const ElementMatcherPair& back = matches_.back();
5041    lhs_used_[back.first] = kUnused;
5042    rhs_used_[back.second] = kUnused;
5043    matches_.pop_back();
5044  }
5045
5046  bool RecurseInto(size_t irhs) {
5047    if (rhs_used_[irhs] != kUnused) {
5048      return true;
5049    }
5050    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5051      if (lhs_used_[ilhs] != kUnused) {
5052        continue;
5053      }
5054      if (!graph_->HasEdge(ilhs, irhs)) {
5055        continue;
5056      }
5057      PushMatch(ilhs, irhs);
5058      if (best_so_far_.size() == graph_->RhsSize()) {
5059        return false;
5060      }
5061      for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5062        if (!RecurseInto(mi)) return false;
5063      }
5064      PopMatch();
5065    }
5066    return true;
5067  }
5068
5069  const Graph* graph_;  // not owned
5070  std::vector<size_t> lhs_used_;
5071  std::vector<size_t> rhs_used_;
5072  ElementMatcherPairs matches_;
5073  ElementMatcherPairs best_so_far_;
5074};
5075
5076template <typename Graph>
5077const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5078
5079}  // namespace
5080
5081// Implement a simple backtracking algorithm to determine if it is possible
5082// to find one element per matcher, without reusing elements.
5083template <typename Graph>
5084ElementMatcherPairs
5085FindBacktrackingMaxBPM(const Graph& g) {
5086  return BacktrackingMaxBPMState<Graph>(&g).Compute();
5087}
5088
5089class BacktrackingBPMTest : public ::testing::Test { };
5090
5091// Tests the MaxBipartiteMatching algorithm with square matrices.
5092// The single int param is the # of nodes on each of the left and right sides.
5093class BipartiteTest : public ::testing::TestWithParam<int> { };
5094
5095// Verify all match graphs up to some moderate number of edges.
5096TEST_P(BipartiteTest, Exhaustive) {
5097  int nodes = GetParam();
5098  MatchMatrix graph(nodes, nodes);
5099  do {
5100    ElementMatcherPairs matches =
5101        internal::FindMaxBipartiteMatching(graph);
5102    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5103        << "graph: " << graph.DebugString();
5104    // Check that all elements of matches are in the graph.
5105    // Check that elements of first and second are unique.
5106    std::vector<bool> seen_element(graph.LhsSize());
5107    std::vector<bool> seen_matcher(graph.RhsSize());
5108    SCOPED_TRACE(PrintToString(matches));
5109    for (size_t i = 0; i < matches.size(); ++i) {
5110      size_t ilhs = matches[i].first;
5111      size_t irhs = matches[i].second;
5112      EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5113      EXPECT_FALSE(seen_element[ilhs]);
5114      EXPECT_FALSE(seen_matcher[irhs]);
5115      seen_element[ilhs] = true;
5116      seen_matcher[irhs] = true;
5117    }
5118  } while (graph.NextGraph());
5119}
5120
5121INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5122                        ::testing::Range(0, 5));
5123
5124// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5125class BipartiteNonSquareTest
5126    : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5127};
5128
5129TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5130  //   .......
5131  // 0:-----\ :
5132  // 1:---\ | :
5133  // 2:---\ | :
5134  // 3:-\ | | :
5135  //  :.......:
5136  //    0 1 2
5137  MatchMatrix g(4, 3);
5138  static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
5139  for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
5140    g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5141  }
5142  EXPECT_THAT(FindBacktrackingMaxBPM(g),
5143              ElementsAre(Pair(3, 0),
5144                          Pair(AnyOf(1, 2), 1),
5145                          Pair(0, 2))) << g.DebugString();
5146}
5147
5148// Verify a few nonsquare matrices.
5149TEST_P(BipartiteNonSquareTest, Exhaustive) {
5150  size_t nlhs = GetParam().first;
5151  size_t nrhs = GetParam().second;
5152  MatchMatrix graph(nlhs, nrhs);
5153  do {
5154    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5155              internal::FindMaxBipartiteMatching(graph).size())
5156        << "graph: " << graph.DebugString()
5157        << "\nbacktracking: "
5158        << PrintToString(FindBacktrackingMaxBPM(graph))
5159        << "\nmax flow: "
5160        << PrintToString(internal::FindMaxBipartiteMatching(graph));
5161  } while (graph.NextGraph());
5162}
5163
5164INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5165    testing::Values(
5166        std::make_pair(1, 2),
5167        std::make_pair(2, 1),
5168        std::make_pair(3, 2),
5169        std::make_pair(2, 3),
5170        std::make_pair(4, 1),
5171        std::make_pair(1, 4),
5172        std::make_pair(4, 3),
5173        std::make_pair(3, 4)));
5174
5175class BipartiteRandomTest
5176    : public ::testing::TestWithParam<std::pair<int, int> > {
5177};
5178
5179// Verifies a large sample of larger graphs.
5180TEST_P(BipartiteRandomTest, LargerNets) {
5181  int nodes = GetParam().first;
5182  int iters = GetParam().second;
5183  MatchMatrix graph(nodes, nodes);
5184
5185  testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5186  if (seed == 0) {
5187    seed = static_cast<testing::internal::Int32>(time(NULL));
5188  }
5189
5190  for (; iters > 0; --iters, ++seed) {
5191    srand(static_cast<int>(seed));
5192    graph.Randomize();
5193    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5194              internal::FindMaxBipartiteMatching(graph).size())
5195        << " graph: " << graph.DebugString()
5196        << "\nTo reproduce the failure, rerun the test with the flag"
5197           " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5198  }
5199}
5200
5201// Test argument is a std::pair<int, int> representing (nodes, iters).
5202INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5203    testing::Values(
5204        std::make_pair(5, 10000),
5205        std::make_pair(6, 5000),
5206        std::make_pair(7, 2000),
5207        std::make_pair(8, 500),
5208        std::make_pair(9, 100)));
5209
5210// Tests IsReadableTypeName().
5211
5212TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5213  EXPECT_TRUE(IsReadableTypeName("int"));
5214  EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5215  EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5216  EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5217}
5218
5219TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5220  EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5221  EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5222  EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5223}
5224
5225TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5226  EXPECT_FALSE(
5227      IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5228  EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5229}
5230
5231TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5232  EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5233}
5234
5235// Tests JoinAsTuple().
5236
5237TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5238  EXPECT_EQ("", JoinAsTuple(Strings()));
5239}
5240
5241TEST(JoinAsTupleTest, JoinsOneTuple) {
5242  const char* fields[] = {"1"};
5243  EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5244}
5245
5246TEST(JoinAsTupleTest, JoinsTwoTuple) {
5247  const char* fields[] = {"1", "a"};
5248  EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5249}
5250
5251TEST(JoinAsTupleTest, JoinsTenTuple) {
5252  const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
5253  EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5254            JoinAsTuple(Strings(fields, fields + 10)));
5255}
5256
5257// Tests FormatMatcherDescription().
5258
5259TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5260  EXPECT_EQ("is even",
5261            FormatMatcherDescription(false, "IsEven", Strings()));
5262  EXPECT_EQ("not (is even)",
5263            FormatMatcherDescription(true, "IsEven", Strings()));
5264
5265  const char* params[] = {"5"};
5266  EXPECT_EQ("equals 5",
5267            FormatMatcherDescription(false, "Equals",
5268                                     Strings(params, params + 1)));
5269
5270  const char* params2[] = {"5", "8"};
5271  EXPECT_EQ("is in range (5, 8)",
5272            FormatMatcherDescription(false, "IsInRange",
5273                                     Strings(params2, params2 + 2)));
5274}
5275
5276// Tests PolymorphicMatcher::mutable_impl().
5277TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5278  PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5279  DivisibleByImpl& impl = m.mutable_impl();
5280  EXPECT_EQ(42, impl.divider());
5281
5282  impl.set_divider(0);
5283  EXPECT_EQ(0, m.mutable_impl().divider());
5284}
5285
5286// Tests PolymorphicMatcher::impl().
5287TEST(PolymorphicMatcherTest, CanAccessImpl) {
5288  const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5289  const DivisibleByImpl& impl = m.impl();
5290  EXPECT_EQ(42, impl.divider());
5291}
5292
5293TEST(MatcherTupleTest, ExplainsMatchFailure) {
5294  stringstream ss1;
5295  ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5296                             make_tuple('a', 10), &ss1);
5297  EXPECT_EQ("", ss1.str());  // Successful match.
5298
5299  stringstream ss2;
5300  ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5301                             make_tuple(2, 'b'), &ss2);
5302  EXPECT_EQ("  Expected arg #0: is > 5\n"
5303            "           Actual: 2, which is 3 less than 5\n"
5304            "  Expected arg #1: is equal to 'a' (97, 0x61)\n"
5305            "           Actual: 'b' (98, 0x62)\n",
5306            ss2.str());  // Failed match where both arguments need explanation.
5307
5308  stringstream ss3;
5309  ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5310                             make_tuple(2, 'a'), &ss3);
5311  EXPECT_EQ("  Expected arg #0: is > 5\n"
5312            "           Actual: 2, which is 3 less than 5\n",
5313            ss3.str());  // Failed match where only one argument needs
5314                         // explanation.
5315}
5316
5317// Tests Each().
5318
5319TEST(EachTest, ExplainsMatchResultCorrectly) {
5320  set<int> a;  // empty
5321
5322  Matcher<set<int> > m = Each(2);
5323  EXPECT_EQ("", Explain(m, a));
5324
5325  Matcher<const int(&)[1]> n = Each(1);  // NOLINT
5326
5327  const int b[1] = {1};
5328  EXPECT_EQ("", Explain(n, b));
5329
5330  n = Each(3);
5331  EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5332
5333  a.insert(1);
5334  a.insert(2);
5335  a.insert(3);
5336  m = Each(GreaterThan(0));
5337  EXPECT_EQ("", Explain(m, a));
5338
5339  m = Each(GreaterThan(10));
5340  EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5341            Explain(m, a));
5342}
5343
5344TEST(EachTest, DescribesItselfCorrectly) {
5345  Matcher<vector<int> > m = Each(1);
5346  EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5347
5348  Matcher<vector<int> > m2 = Not(m);
5349  EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5350}
5351
5352TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5353  vector<int> some_vector;
5354  EXPECT_THAT(some_vector, Each(1));
5355  some_vector.push_back(3);
5356  EXPECT_THAT(some_vector, Not(Each(1)));
5357  EXPECT_THAT(some_vector, Each(3));
5358  some_vector.push_back(1);
5359  some_vector.push_back(2);
5360  EXPECT_THAT(some_vector, Not(Each(3)));
5361  EXPECT_THAT(some_vector, Each(Lt(3.5)));
5362
5363  vector<string> another_vector;
5364  another_vector.push_back("fee");
5365  EXPECT_THAT(another_vector, Each(string("fee")));
5366  another_vector.push_back("fie");
5367  another_vector.push_back("foe");
5368  another_vector.push_back("fum");
5369  EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5370}
5371
5372TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5373  map<const char*, int> my_map;
5374  const char* bar = "a string";
5375  my_map[bar] = 2;
5376  EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5377
5378  map<string, int> another_map;
5379  EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5380  another_map["fee"] = 1;
5381  EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5382  another_map["fie"] = 2;
5383  another_map["foe"] = 3;
5384  another_map["fum"] = 4;
5385  EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5386  EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5387  EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5388}
5389
5390TEST(EachTest, AcceptsMatcher) {
5391  const int a[] = {1, 2, 3};
5392  EXPECT_THAT(a, Each(Gt(0)));
5393  EXPECT_THAT(a, Not(Each(Gt(1))));
5394}
5395
5396TEST(EachTest, WorksForNativeArrayAsTuple) {
5397  const int a[] = {1, 2};
5398  const int* const pointer = a;
5399  EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5400  EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5401}
5402
5403// For testing Pointwise().
5404class IsHalfOfMatcher {
5405 public:
5406  template <typename T1, typename T2>
5407  bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5408                       MatchResultListener* listener) const {
5409    if (get<0>(a_pair) == get<1>(a_pair)/2) {
5410      *listener << "where the second is " << get<1>(a_pair);
5411      return true;
5412    } else {
5413      *listener << "where the second/2 is " << get<1>(a_pair)/2;
5414      return false;
5415    }
5416  }
5417
5418  void DescribeTo(ostream* os) const {
5419    *os << "are a pair where the first is half of the second";
5420  }
5421
5422  void DescribeNegationTo(ostream* os) const {
5423    *os << "are a pair where the first isn't half of the second";
5424  }
5425};
5426
5427PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5428  return MakePolymorphicMatcher(IsHalfOfMatcher());
5429}
5430
5431TEST(PointwiseTest, DescribesSelf) {
5432  vector<int> rhs;
5433  rhs.push_back(1);
5434  rhs.push_back(2);
5435  rhs.push_back(3);
5436  const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5437  EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5438            "in { 1, 2, 3 } are a pair where the first is half of the second",
5439            Describe(m));
5440  EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5441            "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5442            "where the first isn't half of the second",
5443            DescribeNegation(m));
5444}
5445
5446TEST(PointwiseTest, MakesCopyOfRhs) {
5447  list<signed char> rhs;
5448  rhs.push_back(2);
5449  rhs.push_back(4);
5450
5451  int lhs[] = {1, 2};
5452  const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5453  EXPECT_THAT(lhs, m);
5454
5455  // Changing rhs now shouldn't affect m, which made a copy of rhs.
5456  rhs.push_back(6);
5457  EXPECT_THAT(lhs, m);
5458}
5459
5460TEST(PointwiseTest, WorksForLhsNativeArray) {
5461  const int lhs[] = {1, 2, 3};
5462  vector<int> rhs;
5463  rhs.push_back(2);
5464  rhs.push_back(4);
5465  rhs.push_back(6);
5466  EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5467  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5468}
5469
5470TEST(PointwiseTest, WorksForRhsNativeArray) {
5471  const int rhs[] = {1, 2, 3};
5472  vector<int> lhs;
5473  lhs.push_back(2);
5474  lhs.push_back(4);
5475  lhs.push_back(6);
5476  EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5477  EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5478}
5479
5480#if GTEST_HAS_STD_INITIALIZER_LIST_
5481
5482TEST(PointwiseTest, WorksForRhsInitializerList) {
5483  const vector<int> lhs{2, 4, 6};
5484  EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5485  EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5486}
5487
5488#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
5489
5490TEST(PointwiseTest, RejectsWrongSize) {
5491  const double lhs[2] = {1, 2};
5492  const int rhs[1] = {0};
5493  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5494  EXPECT_EQ("which contains 2 values",
5495            Explain(Pointwise(Gt(), rhs), lhs));
5496
5497  const int rhs2[3] = {0, 1, 2};
5498  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5499}
5500
5501TEST(PointwiseTest, RejectsWrongContent) {
5502  const double lhs[3] = {1, 2, 3};
5503  const int rhs[3] = {2, 6, 4};
5504  EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5505  EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5506            "where the second/2 is 3",
5507            Explain(Pointwise(IsHalfOf(), rhs), lhs));
5508}
5509
5510TEST(PointwiseTest, AcceptsCorrectContent) {
5511  const double lhs[3] = {1, 2, 3};
5512  const int rhs[3] = {2, 4, 6};
5513  EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5514  EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5515}
5516
5517TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5518  const double lhs[3] = {1, 2, 3};
5519  const int rhs[3] = {2, 4, 6};
5520  const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5521  EXPECT_THAT(lhs, Pointwise(m1, rhs));
5522  EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5523
5524  // This type works as a tuple<const double&, const int&> can be
5525  // implicitly cast to tuple<double, int>.
5526  const Matcher<tuple<double, int> > m2 = IsHalfOf();
5527  EXPECT_THAT(lhs, Pointwise(m2, rhs));
5528  EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5529}
5530
5531TEST(UnorderedPointwiseTest, DescribesSelf) {
5532  vector<int> rhs;
5533  rhs.push_back(1);
5534  rhs.push_back(2);
5535  rhs.push_back(3);
5536  const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5537  EXPECT_EQ(
5538      "has 3 elements and there exists some permutation of elements such "
5539      "that:\n"
5540      " - element #0 and 1 are a pair where the first is half of the second, "
5541      "and\n"
5542      " - element #1 and 2 are a pair where the first is half of the second, "
5543      "and\n"
5544      " - element #2 and 3 are a pair where the first is half of the second",
5545      Describe(m));
5546  EXPECT_EQ(
5547      "doesn't have 3 elements, or there exists no permutation of elements "
5548      "such that:\n"
5549      " - element #0 and 1 are a pair where the first is half of the second, "
5550      "and\n"
5551      " - element #1 and 2 are a pair where the first is half of the second, "
5552      "and\n"
5553      " - element #2 and 3 are a pair where the first is half of the second",
5554      DescribeNegation(m));
5555}
5556
5557TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5558  list<signed char> rhs;
5559  rhs.push_back(2);
5560  rhs.push_back(4);
5561
5562  int lhs[] = {2, 1};
5563  const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5564  EXPECT_THAT(lhs, m);
5565
5566  // Changing rhs now shouldn't affect m, which made a copy of rhs.
5567  rhs.push_back(6);
5568  EXPECT_THAT(lhs, m);
5569}
5570
5571TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5572  const int lhs[] = {1, 2, 3};
5573  vector<int> rhs;
5574  rhs.push_back(4);
5575  rhs.push_back(6);
5576  rhs.push_back(2);
5577  EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5578  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5579}
5580
5581TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5582  const int rhs[] = {1, 2, 3};
5583  vector<int> lhs;
5584  lhs.push_back(4);
5585  lhs.push_back(2);
5586  lhs.push_back(6);
5587  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5588  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5589}
5590
5591#if GTEST_HAS_STD_INITIALIZER_LIST_
5592
5593TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5594  const vector<int> lhs{2, 4, 6};
5595  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5596  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5597}
5598
5599#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
5600
5601TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5602  const double lhs[2] = {1, 2};
5603  const int rhs[1] = {0};
5604  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5605  EXPECT_EQ("which has 2 elements",
5606            Explain(UnorderedPointwise(Gt(), rhs), lhs));
5607
5608  const int rhs2[3] = {0, 1, 2};
5609  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5610}
5611
5612TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5613  const double lhs[3] = {1, 2, 3};
5614  const int rhs[3] = {2, 6, 6};
5615  EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5616  EXPECT_EQ("where the following elements don't match any matchers:\n"
5617            "element #1: 2",
5618            Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5619}
5620
5621TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5622  const double lhs[3] = {1, 2, 3};
5623  const int rhs[3] = {2, 4, 6};
5624  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5625}
5626
5627TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5628  const double lhs[3] = {1, 2, 3};
5629  const int rhs[3] = {6, 4, 2};
5630  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5631}
5632
5633TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5634  const double lhs[3] = {1, 2, 3};
5635  const int rhs[3] = {4, 6, 2};
5636  const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5637  EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5638
5639  // This type works as a tuple<const double&, const int&> can be
5640  // implicitly cast to tuple<double, int>.
5641  const Matcher<tuple<double, int> > m2 = IsHalfOf();
5642  EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5643}
5644
5645}  // namespace gmock_matchers_test
5646}  // namespace testing
trunk/3rdparty/googletest/googlemock/test/gmock-more-actions_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the built-in actions in gmock-more-actions.h.
35
36#include "gmock/gmock-more-actions.h"
37
38#include <functional>
39#include <sstream>
40#include <string>
41#include "gmock/gmock.h"
42#include "gtest/gtest.h"
43#include "gtest/internal/gtest-linked_ptr.h"
44
45namespace testing {
46namespace gmock_more_actions_test {
47
48using ::std::plus;
49using ::std::string;
50using testing::get;
51using testing::make_tuple;
52using testing::tuple;
53using testing::tuple_element;
54using testing::_;
55using testing::Action;
56using testing::ActionInterface;
57using testing::DeleteArg;
58using testing::Invoke;
59using testing::Return;
60using testing::ReturnArg;
61using testing::ReturnPointee;
62using testing::SaveArg;
63using testing::SaveArgPointee;
64using testing::SetArgReferee;
65using testing::StaticAssertTypeEq;
66using testing::Unused;
67using testing::WithArg;
68using testing::WithoutArgs;
69using testing::internal::linked_ptr;
70
71// For suppressing compiler warnings on conversion possibly losing precision.
72inline short Short(short n) { return n; }  // NOLINT
73inline char Char(char ch) { return ch; }
74
75// Sample functions and functors for testing Invoke() and etc.
76int Nullary() { return 1; }
77
78class NullaryFunctor {
79 public:
80  int operator()() { return 2; }
81};
82
83bool g_done = false;
84void VoidNullary() { g_done = true; }
85
86class VoidNullaryFunctor {
87 public:
88  void operator()() { g_done = true; }
89};
90
91bool Unary(int x) { return x < 0; }
92
93const char* Plus1(const char* s) { return s + 1; }
94
95void VoidUnary(int /* n */) { g_done = true; }
96
97bool ByConstRef(const string& s) { return s == "Hi"; }
98
99const double g_double = 0;
100bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
101
102string ByNonConstRef(string& s) { return s += "+"; }  // NOLINT
103
104struct UnaryFunctor {
105  int operator()(bool x) { return x ? 1 : -1; }
106};
107
108const char* Binary(const char* input, short n) { return input + n; }  // NOLINT
109
110void VoidBinary(int, char) { g_done = true; }
111
112int Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT
113
114void VoidTernary(int, char, bool) { g_done = true; }
115
116int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
117
118int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; }
119
120void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; }
121
122string Concat4(const char* s1, const char* s2, const char* s3,
123               const char* s4) {
124  return string(s1) + s2 + s3 + s4;
125}
126
127int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
128
129struct SumOf5Functor {
130  int operator()(int a, int b, int c, int d, int e) {
131    return a + b + c + d + e;
132  }
133};
134
135string Concat5(const char* s1, const char* s2, const char* s3,
136               const char* s4, const char* s5) {
137  return string(s1) + s2 + s3 + s4 + s5;
138}
139
140int SumOf6(int a, int b, int c, int d, int e, int f) {
141  return a + b + c + d + e + f;
142}
143
144struct SumOf6Functor {
145  int operator()(int a, int b, int c, int d, int e, int f) {
146    return a + b + c + d + e + f;
147  }
148};
149
150string Concat6(const char* s1, const char* s2, const char* s3,
151               const char* s4, const char* s5, const char* s6) {
152  return string(s1) + s2 + s3 + s4 + s5 + s6;
153}
154
155string Concat7(const char* s1, const char* s2, const char* s3,
156               const char* s4, const char* s5, const char* s6,
157               const char* s7) {
158  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
159}
160
161string Concat8(const char* s1, const char* s2, const char* s3,
162               const char* s4, const char* s5, const char* s6,
163               const char* s7, const char* s8) {
164  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
165}
166
167string Concat9(const char* s1, const char* s2, const char* s3,
168               const char* s4, const char* s5, const char* s6,
169               const char* s7, const char* s8, const char* s9) {
170  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
171}
172
173string Concat10(const char* s1, const char* s2, const char* s3,
174                const char* s4, const char* s5, const char* s6,
175                const char* s7, const char* s8, const char* s9,
176                const char* s10) {
177  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
178}
179
180class Foo {
181 public:
182  Foo() : value_(123) {}
183
184  int Nullary() const { return value_; }
185
186  short Unary(long x) { return static_cast<short>(value_ + x); }  // NOLINT
187
188  string Binary(const string& str, char c) const { return str + c; }
189
190  int Ternary(int x, bool y, char z) { return value_ + x + y*z; }
191
192  int SumOf4(int a, int b, int c, int d) const {
193    return a + b + c + d + value_;
194  }
195
196  int SumOfLast2(Unused, Unused, int a, int b) const { return a + b; }
197
198  int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
199
200  int SumOf6(int a, int b, int c, int d, int e, int f) {
201    return a + b + c + d + e + f;
202  }
203
204  string Concat7(const char* s1, const char* s2, const char* s3,
205                 const char* s4, const char* s5, const char* s6,
206                 const char* s7) {
207    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
208  }
209
210  string Concat8(const char* s1, const char* s2, const char* s3,
211                 const char* s4, const char* s5, const char* s6,
212                 const char* s7, const char* s8) {
213    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
214  }
215
216  string Concat9(const char* s1, const char* s2, const char* s3,
217                 const char* s4, const char* s5, const char* s6,
218                 const char* s7, const char* s8, const char* s9) {
219    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
220  }
221
222  string Concat10(const char* s1, const char* s2, const char* s3,
223                  const char* s4, const char* s5, const char* s6,
224                  const char* s7, const char* s8, const char* s9,
225                  const char* s10) {
226    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
227  }
228
229 private:
230  int value_;
231};
232
233// Tests using Invoke() with a nullary function.
234TEST(InvokeTest, Nullary) {
235  Action<int()> a = Invoke(Nullary);  // NOLINT
236  EXPECT_EQ(1, a.Perform(make_tuple()));
237}
238
239// Tests using Invoke() with a unary function.
240TEST(InvokeTest, Unary) {
241  Action<bool(int)> a = Invoke(Unary);  // NOLINT
242  EXPECT_FALSE(a.Perform(make_tuple(1)));
243  EXPECT_TRUE(a.Perform(make_tuple(-1)));
244}
245
246// Tests using Invoke() with a binary function.
247TEST(InvokeTest, Binary) {
248  Action<const char*(const char*, short)> a = Invoke(Binary);  // NOLINT
249  const char* p = "Hello";
250  EXPECT_EQ(p + 2, a.Perform(make_tuple(p, Short(2))));
251}
252
253// Tests using Invoke() with a ternary function.
254TEST(InvokeTest, Ternary) {
255  Action<int(int, char, short)> a = Invoke(Ternary);  // NOLINT
256  EXPECT_EQ(6, a.Perform(make_tuple(1, '\2', Short(3))));
257}
258
259// Tests using Invoke() with a 4-argument function.
260TEST(InvokeTest, FunctionThatTakes4Arguments) {
261  Action<int(int, int, int, int)> a = Invoke(SumOf4);  // NOLINT
262  EXPECT_EQ(1234, a.Perform(make_tuple(1000, 200, 30, 4)));
263}
264
265// Tests using Invoke() with a 5-argument function.
266TEST(InvokeTest, FunctionThatTakes5Arguments) {
267  Action<int(int, int, int, int, int)> a = Invoke(SumOf5);  // NOLINT
268  EXPECT_EQ(12345, a.Perform(make_tuple(10000, 2000, 300, 40, 5)));
269}
270
271// Tests using Invoke() with a 6-argument function.
272TEST(InvokeTest, FunctionThatTakes6Arguments) {
273  Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6);  // NOLINT
274  EXPECT_EQ(123456, a.Perform(make_tuple(100000, 20000, 3000, 400, 50, 6)));
275}
276
277// A helper that turns the type of a C-string literal from const
278// char[N] to const char*.
279inline const char* CharPtr(const char* s) { return s; }
280
281// Tests using Invoke() with a 7-argument function.
282TEST(InvokeTest, FunctionThatTakes7Arguments) {
283  Action<string(const char*, const char*, const char*, const char*,
284                const char*, const char*, const char*)> a =
285      Invoke(Concat7);
286  EXPECT_EQ("1234567",
287            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
288                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
289                                 CharPtr("7"))));
290}
291
292// Tests using Invoke() with a 8-argument function.
293TEST(InvokeTest, FunctionThatTakes8Arguments) {
294  Action<string(const char*, const char*, const char*, const char*,
295                const char*, const char*, const char*, const char*)> a =
296      Invoke(Concat8);
297  EXPECT_EQ("12345678",
298            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
299                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
300                                 CharPtr("7"), CharPtr("8"))));
301}
302
303// Tests using Invoke() with a 9-argument function.
304TEST(InvokeTest, FunctionThatTakes9Arguments) {
305  Action<string(const char*, const char*, const char*, const char*,
306                const char*, const char*, const char*, const char*,
307                const char*)> a = Invoke(Concat9);
308  EXPECT_EQ("123456789",
309            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
310                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
311                                 CharPtr("7"), CharPtr("8"), CharPtr("9"))));
312}
313
314// Tests using Invoke() with a 10-argument function.
315TEST(InvokeTest, FunctionThatTakes10Arguments) {
316  Action<string(const char*, const char*, const char*, const char*,
317                const char*, const char*, const char*, const char*,
318                const char*, const char*)> a = Invoke(Concat10);
319  EXPECT_EQ("1234567890",
320            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
321                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
322                                 CharPtr("7"), CharPtr("8"), CharPtr("9"),
323                                 CharPtr("0"))));
324}
325
326// Tests using Invoke() with functions with parameters declared as Unused.
327TEST(InvokeTest, FunctionWithUnusedParameters) {
328  Action<int(int, int, double, const string&)> a1 =
329      Invoke(SumOfFirst2);
330  EXPECT_EQ(12, a1.Perform(make_tuple(10, 2, 5.6, string("hi"))));
331
332  Action<int(int, int, bool, int*)> a2 =
333      Invoke(SumOfFirst2);
334  EXPECT_EQ(23, a2.Perform(make_tuple(20, 3, true, static_cast<int*>(NULL))));
335}
336
337// Tests using Invoke() with methods with parameters declared as Unused.
338TEST(InvokeTest, MethodWithUnusedParameters) {
339  Foo foo;
340  Action<int(string, bool, int, int)> a1 =
341      Invoke(&foo, &Foo::SumOfLast2);
342  EXPECT_EQ(12, a1.Perform(make_tuple(CharPtr("hi"), true, 10, 2)));
343
344  Action<int(char, double, int, int)> a2 =
345      Invoke(&foo, &Foo::SumOfLast2);
346  EXPECT_EQ(23, a2.Perform(make_tuple('a', 2.5, 20, 3)));
347}
348
349// Tests using Invoke() with a functor.
350TEST(InvokeTest, Functor) {
351  Action<long(long, int)> a = Invoke(plus<long>());  // NOLINT
352  EXPECT_EQ(3L, a.Perform(make_tuple(1, 2)));
353}
354
355// Tests using Invoke(f) as an action of a compatible type.
356TEST(InvokeTest, FunctionWithCompatibleType) {
357  Action<long(int, short, char, bool)> a = Invoke(SumOf4);  // NOLINT
358  EXPECT_EQ(4321, a.Perform(make_tuple(4000, Short(300), Char(20), true)));
359}
360
361// Tests using Invoke() with an object pointer and a method pointer.
362
363// Tests using Invoke() with a nullary method.
364TEST(InvokeMethodTest, Nullary) {
365  Foo foo;
366  Action<int()> a = Invoke(&foo, &Foo::Nullary);  // NOLINT
367  EXPECT_EQ(123, a.Perform(make_tuple()));
368}
369
370// Tests using Invoke() with a unary method.
371TEST(InvokeMethodTest, Unary) {
372  Foo foo;
373  Action<short(long)> a = Invoke(&foo, &Foo::Unary);  // NOLINT
374  EXPECT_EQ(4123, a.Perform(make_tuple(4000)));
375}
376
377// Tests using Invoke() with a binary method.
378TEST(InvokeMethodTest, Binary) {
379  Foo foo;
380  Action<string(const string&, char)> a = Invoke(&foo, &Foo::Binary);
381  string s("Hell");
382  EXPECT_EQ("Hello", a.Perform(make_tuple(s, 'o')));
383}
384
385// Tests using Invoke() with a ternary method.
386TEST(InvokeMethodTest, Ternary) {
387  Foo foo;
388  Action<int(int, bool, char)> a = Invoke(&foo, &Foo::Ternary);  // NOLINT
389  EXPECT_EQ(1124, a.Perform(make_tuple(1000, true, Char(1))));
390}
391
392// Tests using Invoke() with a 4-argument method.
393TEST(InvokeMethodTest, MethodThatTakes4Arguments) {
394  Foo foo;
395  Action<int(int, int, int, int)> a = Invoke(&foo, &Foo::SumOf4);  // NOLINT
396  EXPECT_EQ(1357, a.Perform(make_tuple(1000, 200, 30, 4)));
397}
398
399// Tests using Invoke() with a 5-argument method.
400TEST(InvokeMethodTest, MethodThatTakes5Arguments) {
401  Foo foo;
402  Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5);  // NOLINT
403  EXPECT_EQ(12345, a.Perform(make_tuple(10000, 2000, 300, 40, 5)));
404}
405
406// Tests using Invoke() with a 6-argument method.
407TEST(InvokeMethodTest, MethodThatTakes6Arguments) {
408  Foo foo;
409  Action<int(int, int, int, int, int, int)> a =  // NOLINT
410      Invoke(&foo, &Foo::SumOf6);
411  EXPECT_EQ(123456, a.Perform(make_tuple(100000, 20000, 3000, 400, 50, 6)));
412}
413
414// Tests using Invoke() with a 7-argument method.
415TEST(InvokeMethodTest, MethodThatTakes7Arguments) {
416  Foo foo;
417  Action<string(const char*, const char*, const char*, const char*,
418                const char*, const char*, const char*)> a =
419      Invoke(&foo, &Foo::Concat7);
420  EXPECT_EQ("1234567",
421            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
422                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
423                                 CharPtr("7"))));
424}
425
426// Tests using Invoke() with a 8-argument method.
427TEST(InvokeMethodTest, MethodThatTakes8Arguments) {
428  Foo foo;
429  Action<string(const char*, const char*, const char*, const char*,
430                const char*, const char*, const char*, const char*)> a =
431      Invoke(&foo, &Foo::Concat8);
432  EXPECT_EQ("12345678",
433            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
434                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
435                                 CharPtr("7"), CharPtr("8"))));
436}
437
438// Tests using Invoke() with a 9-argument method.
439TEST(InvokeMethodTest, MethodThatTakes9Arguments) {
440  Foo foo;
441  Action<string(const char*, const char*, const char*, const char*,
442                const char*, const char*, const char*, const char*,
443                const char*)> a = Invoke(&foo, &Foo::Concat9);
444  EXPECT_EQ("123456789",
445            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
446                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
447                                 CharPtr("7"), CharPtr("8"), CharPtr("9"))));
448}
449
450// Tests using Invoke() with a 10-argument method.
451TEST(InvokeMethodTest, MethodThatTakes10Arguments) {
452  Foo foo;
453  Action<string(const char*, const char*, const char*, const char*,
454                const char*, const char*, const char*, const char*,
455                const char*, const char*)> a = Invoke(&foo, &Foo::Concat10);
456  EXPECT_EQ("1234567890",
457            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
458                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
459                                 CharPtr("7"), CharPtr("8"), CharPtr("9"),
460                                 CharPtr("0"))));
461}
462
463// Tests using Invoke(f) as an action of a compatible type.
464TEST(InvokeMethodTest, MethodWithCompatibleType) {
465  Foo foo;
466  Action<long(int, short, char, bool)> a =  // NOLINT
467      Invoke(&foo, &Foo::SumOf4);
468  EXPECT_EQ(4444, a.Perform(make_tuple(4000, Short(300), Char(20), true)));
469}
470
471// Tests using WithoutArgs with an action that takes no argument.
472TEST(WithoutArgsTest, NoArg) {
473  Action<int(int n)> a = WithoutArgs(Invoke(Nullary));  // NOLINT
474  EXPECT_EQ(1, a.Perform(make_tuple(2)));
475}
476
477// Tests using WithArg with an action that takes 1 argument.
478TEST(WithArgTest, OneArg) {
479  Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary));  // NOLINT
480  EXPECT_TRUE(b.Perform(make_tuple(1.5, -1)));
481  EXPECT_FALSE(b.Perform(make_tuple(1.5, 1)));
482}
483
484TEST(ReturnArgActionTest, WorksForOneArgIntArg0) {
485  const Action<int(int)> a = ReturnArg<0>();
486  EXPECT_EQ(5, a.Perform(make_tuple(5)));
487}
488
489TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) {
490  const Action<bool(bool, bool, bool)> a = ReturnArg<0>();
491  EXPECT_TRUE(a.Perform(make_tuple(true, false, false)));
492}
493
494TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) {
495  const Action<string(int, int, string, int)> a = ReturnArg<2>();
496  EXPECT_EQ("seven", a.Perform(make_tuple(5, 6, string("seven"), 8)));
497}
498
499TEST(SaveArgActionTest, WorksForSameType) {
500  int result = 0;
501  const Action<void(int n)> a1 = SaveArg<0>(&result);
502  a1.Perform(make_tuple(5));
503  EXPECT_EQ(5, result);
504}
505
506TEST(SaveArgActionTest, WorksForCompatibleType) {
507  int result = 0;
508  const Action<void(bool, char)> a1 = SaveArg<1>(&result);
509  a1.Perform(make_tuple(true, 'a'));
510  EXPECT_EQ('a', result);
511}
512
513TEST(SaveArgPointeeActionTest, WorksForSameType) {
514  int result = 0;
515  const int value = 5;
516  const Action<void(const int*)> a1 = SaveArgPointee<0>(&result);
517  a1.Perform(make_tuple(&value));
518  EXPECT_EQ(5, result);
519}
520
521TEST(SaveArgPointeeActionTest, WorksForCompatibleType) {
522  int result = 0;
523  char value = 'a';
524  const Action<void(bool, char*)> a1 = SaveArgPointee<1>(&result);
525  a1.Perform(make_tuple(true, &value));
526  EXPECT_EQ('a', result);
527}
528
529TEST(SaveArgPointeeActionTest, WorksForLinkedPtr) {
530  int result = 0;
531  linked_ptr<int> value(new int(5));
532  const Action<void(linked_ptr<int>)> a1 = SaveArgPointee<0>(&result);
533  a1.Perform(make_tuple(value));
534  EXPECT_EQ(5, result);
535}
536
537TEST(SetArgRefereeActionTest, WorksForSameType) {
538  int value = 0;
539  const Action<void(int&)> a1 = SetArgReferee<0>(1);
540  a1.Perform(tuple<int&>(value));
541  EXPECT_EQ(1, value);
542}
543
544TEST(SetArgRefereeActionTest, WorksForCompatibleType) {
545  int value = 0;
546  const Action<void(int, int&)> a1 = SetArgReferee<1>('a');
547  a1.Perform(tuple<int, int&>(0, value));
548  EXPECT_EQ('a', value);
549}
550
551TEST(SetArgRefereeActionTest, WorksWithExtraArguments) {
552  int value = 0;
553  const Action<void(bool, int, int&, const char*)> a1 = SetArgReferee<2>('a');
554  a1.Perform(tuple<bool, int, int&, const char*>(true, 0, value, "hi"));
555  EXPECT_EQ('a', value);
556}
557
558// A class that can be used to verify that its destructor is called: it will set
559// the bool provided to the constructor to true when destroyed.
560class DeletionTester {
561 public:
562  explicit DeletionTester(bool* is_deleted)
563    : is_deleted_(is_deleted) {
564    // Make sure the bit is set to false.
565    *is_deleted_ = false;
566  }
567
568  ~DeletionTester() {
569    *is_deleted_ = true;
570  }
571
572 private:
573  bool* is_deleted_;
574};
575
576TEST(DeleteArgActionTest, OneArg) {
577  bool is_deleted = false;
578  DeletionTester* t = new DeletionTester(&is_deleted);
579  const Action<void(DeletionTester*)> a1 = DeleteArg<0>();      // NOLINT
580  EXPECT_FALSE(is_deleted);
581  a1.Perform(make_tuple(t));
582  EXPECT_TRUE(is_deleted);
583}
584
585TEST(DeleteArgActionTest, TenArgs) {
586  bool is_deleted = false;
587  DeletionTester* t = new DeletionTester(&is_deleted);
588  const Action<void(bool, int, int, const char*, bool,
589                    int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>();
590  EXPECT_FALSE(is_deleted);
591  a1.Perform(make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t));
592  EXPECT_TRUE(is_deleted);
593}
594
595#if GTEST_HAS_EXCEPTIONS
596
597TEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) {
598  const Action<void(int n)> a = Throw('a');
599  EXPECT_THROW(a.Perform(make_tuple(0)), char);
600}
601
602class MyException {};
603
604TEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) {
605  const Action<double(char ch)> a = Throw(MyException());
606  EXPECT_THROW(a.Perform(make_tuple('0')), MyException);
607}
608
609TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) {
610  const Action<double()> a = Throw(MyException());
611  EXPECT_THROW(a.Perform(make_tuple()), MyException);
612}
613
614#endif  // GTEST_HAS_EXCEPTIONS
615
616// Tests that SetArrayArgument<N>(first, last) sets the elements of the array
617// pointed to by the N-th (0-based) argument to values in range [first, last).
618TEST(SetArrayArgumentTest, SetsTheNthArray) {
619  typedef void MyFunction(bool, int*, char*);
620  int numbers[] = { 1, 2, 3 };
621  Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);
622
623  int n[4] = {};
624  int* pn = n;
625  char ch[4] = {};
626  char* pch = ch;
627  a.Perform(make_tuple(true, pn, pch));
628  EXPECT_EQ(1, n[0]);
629  EXPECT_EQ(2, n[1]);
630  EXPECT_EQ(3, n[2]);
631  EXPECT_EQ(0, n[3]);
632  EXPECT_EQ('\0', ch[0]);
633  EXPECT_EQ('\0', ch[1]);
634  EXPECT_EQ('\0', ch[2]);
635  EXPECT_EQ('\0', ch[3]);
636
637  // Tests first and last are iterators.
638  std::string letters = "abc";
639  a = SetArrayArgument<2>(letters.begin(), letters.end());
640  std::fill_n(n, 4, 0);
641  std::fill_n(ch, 4, '\0');
642  a.Perform(make_tuple(true, pn, pch));
643  EXPECT_EQ(0, n[0]);
644  EXPECT_EQ(0, n[1]);
645  EXPECT_EQ(0, n[2]);
646  EXPECT_EQ(0, n[3]);
647  EXPECT_EQ('a', ch[0]);
648  EXPECT_EQ('b', ch[1]);
649  EXPECT_EQ('c', ch[2]);
650  EXPECT_EQ('\0', ch[3]);
651}
652
653// Tests SetArrayArgument<N>(first, last) where first == last.
654TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
655  typedef void MyFunction(bool, int*);
656  int numbers[] = { 1, 2, 3 };
657  Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);
658
659  int n[4] = {};
660  int* pn = n;
661  a.Perform(make_tuple(true, pn));
662  EXPECT_EQ(0, n[0]);
663  EXPECT_EQ(0, n[1]);
664  EXPECT_EQ(0, n[2]);
665  EXPECT_EQ(0, n[3]);
666}
667
668// Tests SetArrayArgument<N>(first, last) where *first is convertible
669// (but not equal) to the argument type.
670TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
671  typedef void MyFunction(bool, int*);
672  char chars[] = { 97, 98, 99 };
673  Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3);
674
675  int codes[4] = { 111, 222, 333, 444 };
676  int* pcodes = codes;
677  a.Perform(make_tuple(true, pcodes));
678  EXPECT_EQ(97, codes[0]);
679  EXPECT_EQ(98, codes[1]);
680  EXPECT_EQ(99, codes[2]);
681  EXPECT_EQ(444, codes[3]);
682}
683
684// Test SetArrayArgument<N>(first, last) with iterator as argument.
685TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {
686  typedef void MyFunction(bool, std::back_insert_iterator<std::string>);
687  std::string letters = "abc";
688  Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());
689
690  std::string s;
691  a.Perform(make_tuple(true, back_inserter(s)));
692  EXPECT_EQ(letters, s);
693}
694
695TEST(ReturnPointeeTest, Works) {
696  int n = 42;
697  const Action<int()> a = ReturnPointee(&n);
698  EXPECT_EQ(42, a.Perform(make_tuple()));
699
700  n = 43;
701  EXPECT_EQ(43, a.Perform(make_tuple()));
702}
703
704}  // namespace gmock_generated_actions_test
705}  // namespace testing
trunk/3rdparty/googletest/googlemock/test/gmock-nice-strict_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gmock/gmock-generated-nice-strict.h"
33
34#include <string>
35#include "gmock/gmock.h"
36#include "gtest/gtest.h"
37#include "gtest/gtest-spi.h"
38
39// This must not be defined inside the ::testing namespace, or it will
40// clash with ::testing::Mock.
41class Mock {
42 public:
43  Mock() {}
44
45  MOCK_METHOD0(DoThis, void());
46
47 private:
48  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock);
49};
50
51namespace testing {
52namespace gmock_nice_strict_test {
53
54using testing::internal::string;
55using testing::GMOCK_FLAG(verbose);
56using testing::HasSubstr;
57using testing::NaggyMock;
58using testing::NiceMock;
59using testing::StrictMock;
60
61#if GTEST_HAS_STREAM_REDIRECTION
62using testing::internal::CaptureStdout;
63using testing::internal::GetCapturedStdout;
64#endif
65
66// Defines some mock classes needed by the tests.
67
68class Foo {
69 public:
70  virtual ~Foo() {}
71
72  virtual void DoThis() = 0;
73  virtual int DoThat(bool flag) = 0;
74};
75
76class MockFoo : public Foo {
77 public:
78  MockFoo() {}
79  void Delete() { delete this; }
80
81  MOCK_METHOD0(DoThis, void());
82  MOCK_METHOD1(DoThat, int(bool flag));
83
84 private:
85  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
86};
87
88class MockBar {
89 public:
90  explicit MockBar(const string& s) : str_(s) {}
91
92  MockBar(char a1, char a2, string a3, string a4, int a5, int a6,
93          const string& a7, const string& a8, bool a9, bool a10) {
94    str_ = string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) +
95        static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F');
96  }
97
98  virtual ~MockBar() {}
99
100  const string& str() const { return str_; }
101
102  MOCK_METHOD0(This, int());
103  MOCK_METHOD2(That, string(int, bool));
104
105 private:
106  string str_;
107
108  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar);
109};
110
111#if GTEST_HAS_STREAM_REDIRECTION
112
113// Tests that a raw mock generates warnings for uninteresting calls.
114TEST(RawMockTest, WarningForUninterestingCall) {
115  const string saved_flag = GMOCK_FLAG(verbose);
116  GMOCK_FLAG(verbose) = "warning";
117
118  MockFoo raw_foo;
119
120  CaptureStdout();
121  raw_foo.DoThis();
122  raw_foo.DoThat(true);
123  EXPECT_THAT(GetCapturedStdout(),
124              HasSubstr("Uninteresting mock function call"));
125
126  GMOCK_FLAG(verbose) = saved_flag;
127}
128
129// Tests that a raw mock generates warnings for uninteresting calls
130// that delete the mock object.
131TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
132  const string saved_flag = GMOCK_FLAG(verbose);
133  GMOCK_FLAG(verbose) = "warning";
134
135  MockFoo* const raw_foo = new MockFoo;
136
137  ON_CALL(*raw_foo, DoThis())
138      .WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
139
140  CaptureStdout();
141  raw_foo->DoThis();
142  EXPECT_THAT(GetCapturedStdout(),
143              HasSubstr("Uninteresting mock function call"));
144
145  GMOCK_FLAG(verbose) = saved_flag;
146}
147
148// Tests that a raw mock generates informational logs for
149// uninteresting calls.
150TEST(RawMockTest, InfoForUninterestingCall) {
151  MockFoo raw_foo;
152
153  const string saved_flag = GMOCK_FLAG(verbose);
154  GMOCK_FLAG(verbose) = "info";
155  CaptureStdout();
156  raw_foo.DoThis();
157  EXPECT_THAT(GetCapturedStdout(),
158              HasSubstr("Uninteresting mock function call"));
159
160  GMOCK_FLAG(verbose) = saved_flag;
161}
162
163// Tests that a nice mock generates no warning for uninteresting calls.
164TEST(NiceMockTest, NoWarningForUninterestingCall) {
165  NiceMock<MockFoo> nice_foo;
166
167  CaptureStdout();
168  nice_foo.DoThis();
169  nice_foo.DoThat(true);
170  EXPECT_EQ("", GetCapturedStdout());
171}
172
173// Tests that a nice mock generates no warning for uninteresting calls
174// that delete the mock object.
175TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) {
176  NiceMock<MockFoo>* const nice_foo = new NiceMock<MockFoo>;
177
178  ON_CALL(*nice_foo, DoThis())
179      .WillByDefault(Invoke(nice_foo, &MockFoo::Delete));
180
181  CaptureStdout();
182  nice_foo->DoThis();
183  EXPECT_EQ("", GetCapturedStdout());
184}
185
186// Tests that a nice mock generates informational logs for
187// uninteresting calls.
188TEST(NiceMockTest, InfoForUninterestingCall) {
189  NiceMock<MockFoo> nice_foo;
190
191  const string saved_flag = GMOCK_FLAG(verbose);
192  GMOCK_FLAG(verbose) = "info";
193  CaptureStdout();
194  nice_foo.DoThis();
195  EXPECT_THAT(GetCapturedStdout(),
196              HasSubstr("Uninteresting mock function call"));
197
198  GMOCK_FLAG(verbose) = saved_flag;
199}
200
201#endif  // GTEST_HAS_STREAM_REDIRECTION
202
203// Tests that a nice mock allows expected calls.
204TEST(NiceMockTest, AllowsExpectedCall) {
205  NiceMock<MockFoo> nice_foo;
206
207  EXPECT_CALL(nice_foo, DoThis());
208  nice_foo.DoThis();
209}
210
211// Tests that an unexpected call on a nice mock fails.
212TEST(NiceMockTest, UnexpectedCallFails) {
213  NiceMock<MockFoo> nice_foo;
214
215  EXPECT_CALL(nice_foo, DoThis()).Times(0);
216  EXPECT_NONFATAL_FAILURE(nice_foo.DoThis(), "called more times than expected");
217}
218
219// Tests that NiceMock works with a mock class that has a non-default
220// constructor.
221TEST(NiceMockTest, NonDefaultConstructor) {
222  NiceMock<MockBar> nice_bar("hi");
223  EXPECT_EQ("hi", nice_bar.str());
224
225  nice_bar.This();
226  nice_bar.That(5, true);
227}
228
229// Tests that NiceMock works with a mock class that has a 10-ary
230// non-default constructor.
231TEST(NiceMockTest, NonDefaultConstructor10) {
232  NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f',
233                             "g", "h", true, false);
234  EXPECT_EQ("abcdefghTF", nice_bar.str());
235
236  nice_bar.This();
237  nice_bar.That(5, true);
238}
239
240#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
241// Tests that NiceMock<Mock> compiles where Mock is a user-defined
242// class (as opposed to ::testing::Mock).  We had to work around an
243// MSVC 8.0 bug that caused the symbol Mock used in the definition of
244// NiceMock to be looked up in the wrong context, and this test
245// ensures that our fix works.
246//
247// We have to skip this test on Symbian and Windows Mobile, as it
248// causes the program to crash there, for reasons unclear to us yet.
249TEST(NiceMockTest, AcceptsClassNamedMock) {
250  NiceMock< ::Mock> nice;
251  EXPECT_CALL(nice, DoThis());
252  nice.DoThis();
253}
254#endif  // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
255
256#if GTEST_HAS_STREAM_REDIRECTION
257
258// Tests that a naggy mock generates warnings for uninteresting calls.
259TEST(NaggyMockTest, WarningForUninterestingCall) {
260  const string saved_flag = GMOCK_FLAG(verbose);
261  GMOCK_FLAG(verbose) = "warning";
262
263  NaggyMock<MockFoo> naggy_foo;
264
265  CaptureStdout();
266  naggy_foo.DoThis();
267  naggy_foo.DoThat(true);
268  EXPECT_THAT(GetCapturedStdout(),
269              HasSubstr("Uninteresting mock function call"));
270
271  GMOCK_FLAG(verbose) = saved_flag;
272}
273
274// Tests that a naggy mock generates a warning for an uninteresting call
275// that deletes the mock object.
276TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {
277  const string saved_flag = GMOCK_FLAG(verbose);
278  GMOCK_FLAG(verbose) = "warning";
279
280  NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>;
281
282  ON_CALL(*naggy_foo, DoThis())
283      .WillByDefault(Invoke(naggy_foo, &MockFoo::Delete));
284
285  CaptureStdout();
286  naggy_foo->DoThis();
287  EXPECT_THAT(GetCapturedStdout(),
288              HasSubstr("Uninteresting mock function call"));
289
290  GMOCK_FLAG(verbose) = saved_flag;
291}
292
293#endif  // GTEST_HAS_STREAM_REDIRECTION
294
295// Tests that a naggy mock allows expected calls.
296TEST(NaggyMockTest, AllowsExpectedCall) {
297  NaggyMock<MockFoo> naggy_foo;
298
299  EXPECT_CALL(naggy_foo, DoThis());
300  naggy_foo.DoThis();
301}
302
303// Tests that an unexpected call on a naggy mock fails.
304TEST(NaggyMockTest, UnexpectedCallFails) {
305  NaggyMock<MockFoo> naggy_foo;
306
307  EXPECT_CALL(naggy_foo, DoThis()).Times(0);
308  EXPECT_NONFATAL_FAILURE(naggy_foo.DoThis(),
309                          "called more times than expected");
310}
311
312// Tests that NaggyMock works with a mock class that has a non-default
313// constructor.
314TEST(NaggyMockTest, NonDefaultConstructor) {
315  NaggyMock<MockBar> naggy_bar("hi");
316  EXPECT_EQ("hi", naggy_bar.str());
317
318  naggy_bar.This();
319  naggy_bar.That(5, true);
320}
321
322// Tests that NaggyMock works with a mock class that has a 10-ary
323// non-default constructor.
324TEST(NaggyMockTest, NonDefaultConstructor10) {
325  NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5',
326                               "6", "7", true, false);
327  EXPECT_EQ("01234567TF", naggy_bar.str());
328
329  naggy_bar.This();
330  naggy_bar.That(5, true);
331}
332
333#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
334// Tests that NaggyMock<Mock> compiles where Mock is a user-defined
335// class (as opposed to ::testing::Mock).  We had to work around an
336// MSVC 8.0 bug that caused the symbol Mock used in the definition of
337// NaggyMock to be looked up in the wrong context, and this test
338// ensures that our fix works.
339//
340// We have to skip this test on Symbian and Windows Mobile, as it
341// causes the program to crash there, for reasons unclear to us yet.
342TEST(NaggyMockTest, AcceptsClassNamedMock) {
343  NaggyMock< ::Mock> naggy;
344  EXPECT_CALL(naggy, DoThis());
345  naggy.DoThis();
346}
347#endif  // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
348
349// Tests that a strict mock allows expected calls.
350TEST(StrictMockTest, AllowsExpectedCall) {
351  StrictMock<MockFoo> strict_foo;
352
353  EXPECT_CALL(strict_foo, DoThis());
354  strict_foo.DoThis();
355}
356
357// Tests that an unexpected call on a strict mock fails.
358TEST(StrictMockTest, UnexpectedCallFails) {
359  StrictMock<MockFoo> strict_foo;
360
361  EXPECT_CALL(strict_foo, DoThis()).Times(0);
362  EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(),
363                          "called more times than expected");
364}
365
366// Tests that an uninteresting call on a strict mock fails.
367TEST(StrictMockTest, UninterestingCallFails) {
368  StrictMock<MockFoo> strict_foo;
369
370  EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(),
371                          "Uninteresting mock function call");
372}
373
374// Tests that an uninteresting call on a strict mock fails, even if
375// the call deletes the mock object.
376TEST(StrictMockTest, UninterestingCallFailsAfterDeath) {
377  StrictMock<MockFoo>* const strict_foo = new StrictMock<MockFoo>;
378
379  ON_CALL(*strict_foo, DoThis())
380      .WillByDefault(Invoke(strict_foo, &MockFoo::Delete));
381
382  EXPECT_NONFATAL_FAILURE(strict_foo->DoThis(),
383                          "Uninteresting mock function call");
384}
385
386// Tests that StrictMock works with a mock class that has a
387// non-default constructor.
388TEST(StrictMockTest, NonDefaultConstructor) {
389  StrictMock<MockBar> strict_bar("hi");
390  EXPECT_EQ("hi", strict_bar.str());
391
392  EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),
393                          "Uninteresting mock function call");
394}
395
396// Tests that StrictMock works with a mock class that has a 10-ary
397// non-default constructor.
398TEST(StrictMockTest, NonDefaultConstructor10) {
399  StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f',
400                                 "g", "h", true, false);
401  EXPECT_EQ("abcdefghTF", strict_bar.str());
402
403  EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),
404                          "Uninteresting mock function call");
405}
406
407#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
408// Tests that StrictMock<Mock> compiles where Mock is a user-defined
409// class (as opposed to ::testing::Mock).  We had to work around an
410// MSVC 8.0 bug that caused the symbol Mock used in the definition of
411// StrictMock to be looked up in the wrong context, and this test
412// ensures that our fix works.
413//
414// We have to skip this test on Symbian and Windows Mobile, as it
415// causes the program to crash there, for reasons unclear to us yet.
416TEST(StrictMockTest, AcceptsClassNamedMock) {
417  StrictMock< ::Mock> strict;
418  EXPECT_CALL(strict, DoThis());
419  strict.DoThis();
420}
421#endif  // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
422
423}  // namespace gmock_nice_strict_test
424}  // namespace testing
trunk/3rdparty/googletest/googlemock/test/gmock-port_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the internal cross-platform support utilities.
35
36#include "gmock/internal/gmock-port.h"
37#include "gtest/gtest.h"
38
39// NOTE: if this file is left without tests for some reason, put a dummy
40// test here to make references to symbols in the gtest library and avoid
41// 'undefined symbol' linker errors in gmock_main:
42
43TEST(DummyTest, Dummy) {}
trunk/3rdparty/googletest/googlemock/test/gmock-spec-builders_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the spec builder syntax.
35
36#include "gmock/gmock-spec-builders.h"
37
38#include <ostream>  // NOLINT
39#include <sstream>
40#include <string>
41
42#include "gmock/gmock.h"
43#include "gmock/internal/gmock-port.h"
44#include "gtest/gtest.h"
45#include "gtest/gtest-spi.h"
46#include "gtest/internal/gtest-port.h"
47
48namespace testing {
49namespace internal {
50
51// Helper class for testing the Expectation class template.
52class ExpectationTester {
53 public:
54  // Sets the call count of the given expectation to the given number.
55  void SetCallCount(int n, ExpectationBase* exp) {
56    exp->call_count_ = n;
57  }
58};
59
60}  // namespace internal
61}  // namespace testing
62
63namespace {
64
65using testing::_;
66using testing::AnyNumber;
67using testing::AtLeast;
68using testing::AtMost;
69using testing::Between;
70using testing::Cardinality;
71using testing::CardinalityInterface;
72using testing::ContainsRegex;
73using testing::Const;
74using testing::DoAll;
75using testing::DoDefault;
76using testing::Eq;
77using testing::Expectation;
78using testing::ExpectationSet;
79using testing::GMOCK_FLAG(verbose);
80using testing::Gt;
81using testing::InSequence;
82using testing::Invoke;
83using testing::InvokeWithoutArgs;
84using testing::IsNotSubstring;
85using testing::IsSubstring;
86using testing::Lt;
87using testing::Message;
88using testing::Mock;
89using testing::NaggyMock;
90using testing::Ne;
91using testing::Return;
92using testing::Sequence;
93using testing::SetArgPointee;
94using testing::internal::ExpectationTester;
95using testing::internal::FormatFileLocation;
96using testing::internal::kErrorVerbosity;
97using testing::internal::kInfoVerbosity;
98using testing::internal::kWarningVerbosity;
99using testing::internal::linked_ptr;
100using testing::internal::string;
101
102#if GTEST_HAS_STREAM_REDIRECTION
103using testing::HasSubstr;
104using testing::internal::CaptureStdout;
105using testing::internal::GetCapturedStdout;
106#endif
107
108class Incomplete;
109
110class MockIncomplete {
111 public:
112  // This line verifies that a mock method can take a by-reference
113  // argument of an incomplete type.
114  MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
115};
116
117// Tells Google Mock how to print a value of type Incomplete.
118void PrintTo(const Incomplete& x, ::std::ostream* os);
119
120TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
121  // Even though this mock class contains a mock method that takes
122  // by-reference an argument whose type is incomplete, we can still
123  // use the mock, as long as Google Mock knows how to print the
124  // argument.
125  MockIncomplete incomplete;
126  EXPECT_CALL(incomplete, ByRefFunc(_))
127      .Times(AnyNumber());
128}
129
130// The definition of the printer for the argument type doesn't have to
131// be visible where the mock is used.
132void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
133  *os << "incomplete";
134}
135
136class Result {};
137
138// A type that's not default constructible.
139class NonDefaultConstructible {
140 public:
141  explicit NonDefaultConstructible(int /* dummy */) {}
142};
143
144class MockA {
145 public:
146  MockA() {}
147
148  MOCK_METHOD1(DoA, void(int n));
149  MOCK_METHOD1(ReturnResult, Result(int n));
150  MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
151  MOCK_METHOD2(Binary, bool(int x, int y));
152  MOCK_METHOD2(ReturnInt, int(int x, int y));
153
154 private:
155  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
156};
157
158class MockB {
159 public:
160  MockB() {}
161
162  MOCK_CONST_METHOD0(DoB, int());  // NOLINT
163  MOCK_METHOD1(DoB, int(int n));  // NOLINT
164
165 private:
166  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
167};
168
169class ReferenceHoldingMock {
170 public:
171  ReferenceHoldingMock() {}
172
173  MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
174
175 private:
176  GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
177};
178
179// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
180// redefining a mock method name. This could happen, for example, when
181// the tested code #includes Win32 API headers which define many APIs
182// as macros, e.g. #define TextOut TextOutW.
183
184#define Method MethodW
185
186class CC {
187 public:
188  virtual ~CC() {}
189  virtual int Method() = 0;
190};
191class MockCC : public CC {
192 public:
193  MockCC() {}
194
195  MOCK_METHOD0(Method, int());
196
197 private:
198  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
199};
200
201// Tests that a method with expanded name compiles.
202TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
203  MockCC cc;
204  ON_CALL(cc, Method());
205}
206
207// Tests that the method with expanded name not only compiles but runs
208// and returns a correct value, too.
209TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
210  MockCC cc;
211  ON_CALL(cc, Method()).WillByDefault(Return(42));
212  EXPECT_EQ(42, cc.Method());
213}
214
215// Tests that a method with expanded name compiles.
216TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
217  MockCC cc;
218  EXPECT_CALL(cc, Method());
219  cc.Method();
220}
221
222// Tests that it works, too.
223TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
224  MockCC cc;
225  EXPECT_CALL(cc, Method()).WillOnce(Return(42));
226  EXPECT_EQ(42, cc.Method());
227}
228
229#undef Method  // Done with macro redefinition tests.
230
231// Tests that ON_CALL evaluates its arguments exactly once as promised
232// by Google Mock.
233TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
234  MockA a;
235  MockA* pa = &a;
236
237  ON_CALL(*pa++, DoA(_));
238  EXPECT_EQ(&a + 1, pa);
239}
240
241TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
242  MockA a;
243  int n = 0;
244
245  ON_CALL(a, DoA(n++));
246  EXPECT_EQ(1, n);
247}
248
249// Tests that the syntax of ON_CALL() is enforced at run time.
250
251TEST(OnCallSyntaxTest, WithIsOptional) {
252  MockA a;
253
254  ON_CALL(a, DoA(5))
255      .WillByDefault(Return());
256  ON_CALL(a, DoA(_))
257      .With(_)
258      .WillByDefault(Return());
259}
260
261TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
262  MockA a;
263
264  EXPECT_NONFATAL_FAILURE({  // NOLINT
265    ON_CALL(a, ReturnResult(_))
266        .With(_)
267        .With(_)
268        .WillByDefault(Return(Result()));
269  }, ".With() cannot appear more than once in an ON_CALL()");
270}
271
272TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
273  MockA a;
274
275  EXPECT_DEATH_IF_SUPPORTED({
276    ON_CALL(a, DoA(5));
277    a.DoA(5);
278  }, "");
279}
280
281TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
282  MockA a;
283
284  EXPECT_NONFATAL_FAILURE({  // NOLINT
285    ON_CALL(a, DoA(5))
286        .WillByDefault(Return())
287        .WillByDefault(Return());
288  }, ".WillByDefault() must appear exactly once in an ON_CALL()");
289}
290
291// Tests that EXPECT_CALL evaluates its arguments exactly once as
292// promised by Google Mock.
293TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
294  MockA a;
295  MockA* pa = &a;
296
297  EXPECT_CALL(*pa++, DoA(_));
298  a.DoA(0);
299  EXPECT_EQ(&a + 1, pa);
300}
301
302TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
303  MockA a;
304  int n = 0;
305
306  EXPECT_CALL(a, DoA(n++));
307  a.DoA(0);
308  EXPECT_EQ(1, n);
309}
310
311// Tests that the syntax of EXPECT_CALL() is enforced at run time.
312
313TEST(ExpectCallSyntaxTest, WithIsOptional) {
314  MockA a;
315
316  EXPECT_CALL(a, DoA(5))
317      .Times(0);
318  EXPECT_CALL(a, DoA(6))
319      .With(_)
320      .Times(0);
321}
322
323TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
324  MockA a;
325
326  EXPECT_NONFATAL_FAILURE({  // NOLINT
327    EXPECT_CALL(a, DoA(6))
328        .With(_)
329        .With(_);
330  }, ".With() cannot appear more than once in an EXPECT_CALL()");
331
332  a.DoA(6);
333}
334
335TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
336  MockA a;
337
338  EXPECT_NONFATAL_FAILURE({  // NOLINT
339    EXPECT_CALL(a, DoA(1))
340        .Times(1)
341        .With(_);
342  }, ".With() must be the first clause in an EXPECT_CALL()");
343
344  a.DoA(1);
345
346  EXPECT_NONFATAL_FAILURE({  // NOLINT
347    EXPECT_CALL(a, DoA(2))
348        .WillOnce(Return())
349        .With(_);
350  }, ".With() must be the first clause in an EXPECT_CALL()");
351
352  a.DoA(2);
353}
354
355TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
356  MockA a;
357
358  EXPECT_CALL(a, DoA(1))
359      .WillOnce(Return());
360
361  EXPECT_CALL(a, DoA(2))
362      .WillOnce(Return())
363      .WillRepeatedly(Return());
364
365  a.DoA(1);
366  a.DoA(2);
367  a.DoA(2);
368}
369
370TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
371  MockA a;
372
373  EXPECT_NONFATAL_FAILURE({  // NOLINT
374    EXPECT_CALL(a, DoA(1))
375        .Times(1)
376        .Times(2);
377  }, ".Times() cannot appear more than once in an EXPECT_CALL()");
378
379  a.DoA(1);
380  a.DoA(1);
381}
382
383TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
384  MockA a;
385  Sequence s;
386
387  EXPECT_NONFATAL_FAILURE({  // NOLINT
388    EXPECT_CALL(a, DoA(1))
389        .InSequence(s)
390        .Times(1);
391  }, ".Times() cannot appear after ");
392
393  a.DoA(1);
394}
395
396TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
397  MockA a;
398  Sequence s;
399
400  EXPECT_CALL(a, DoA(1));
401  EXPECT_CALL(a, DoA(2))
402      .InSequence(s);
403
404  a.DoA(1);
405  a.DoA(2);
406}
407
408TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
409  MockA a;
410  Sequence s1, s2;
411
412  EXPECT_CALL(a, DoA(1))
413      .InSequence(s1, s2)
414      .InSequence(s1);
415
416  a.DoA(1);
417}
418
419TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
420  MockA a;
421  Sequence s;
422
423  Expectation e = EXPECT_CALL(a, DoA(1))
424      .Times(AnyNumber());
425  EXPECT_NONFATAL_FAILURE({  // NOLINT
426    EXPECT_CALL(a, DoA(2))
427        .After(e)
428        .InSequence(s);
429  }, ".InSequence() cannot appear after ");
430
431  a.DoA(2);
432}
433
434TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
435  MockA a;
436  Sequence s;
437
438  EXPECT_NONFATAL_FAILURE({  // NOLINT
439    EXPECT_CALL(a, DoA(1))
440        .WillOnce(Return())
441        .InSequence(s);
442  }, ".InSequence() cannot appear after ");
443
444  a.DoA(1);
445}
446
447TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
448  MockA a;
449
450  Expectation e = EXPECT_CALL(a, DoA(1));
451  EXPECT_NONFATAL_FAILURE({
452    EXPECT_CALL(a, DoA(2))
453        .WillOnce(Return())
454        .After(e);
455  }, ".After() cannot appear after ");
456
457  a.DoA(1);
458  a.DoA(2);
459}
460
461TEST(ExpectCallSyntaxTest, WillIsOptional) {
462  MockA a;
463
464  EXPECT_CALL(a, DoA(1));
465  EXPECT_CALL(a, DoA(2))
466      .WillOnce(Return());
467
468  a.DoA(1);
469  a.DoA(2);
470}
471
472TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
473  MockA a;
474
475  EXPECT_CALL(a, DoA(1))
476      .Times(AnyNumber())
477      .WillOnce(Return())
478      .WillOnce(Return())
479      .WillOnce(Return());
480}
481
482TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
483  MockA a;
484
485  EXPECT_NONFATAL_FAILURE({  // NOLINT
486    EXPECT_CALL(a, DoA(1))
487        .WillRepeatedly(Return())
488        .WillOnce(Return());
489  }, ".WillOnce() cannot appear after ");
490
491  a.DoA(1);
492}
493
494TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
495  MockA a;
496
497  EXPECT_CALL(a, DoA(1))
498      .WillOnce(Return());
499  EXPECT_CALL(a, DoA(2))
500      .WillOnce(Return())
501      .WillRepeatedly(Return());
502
503  a.DoA(1);
504  a.DoA(2);
505  a.DoA(2);
506}
507
508TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
509  MockA a;
510
511  EXPECT_NONFATAL_FAILURE({  // NOLINT
512    EXPECT_CALL(a, DoA(1))
513        .WillRepeatedly(Return())
514        .WillRepeatedly(Return());
515  }, ".WillRepeatedly() cannot appear more than once in an "
516     "EXPECT_CALL()");
517}
518
519TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
520  MockA a;
521
522  EXPECT_NONFATAL_FAILURE({  // NOLINT
523    EXPECT_CALL(a, DoA(1))
524        .RetiresOnSaturation()
525        .WillRepeatedly(Return());
526  }, ".WillRepeatedly() cannot appear after ");
527}
528
529TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
530  MockA a;
531
532  EXPECT_CALL(a, DoA(1));
533  EXPECT_CALL(a, DoA(1))
534      .RetiresOnSaturation();
535
536  a.DoA(1);
537  a.DoA(1);
538}
539
540TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
541  MockA a;
542
543  EXPECT_NONFATAL_FAILURE({  // NOLINT
544    EXPECT_CALL(a, DoA(1))
545        .RetiresOnSaturation()
546        .RetiresOnSaturation();
547  }, ".RetiresOnSaturation() cannot appear more than once");
548
549  a.DoA(1);
550}
551
552TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
553  {
554    MockA a;
555    EXPECT_CALL(a, DoA(1));
556    a.DoA(1);
557  }
558  EXPECT_NONFATAL_FAILURE({  // NOLINT
559    MockA a;
560    EXPECT_CALL(a, DoA(1));
561  }, "to be called once");
562  EXPECT_NONFATAL_FAILURE({  // NOLINT
563    MockA a;
564    EXPECT_CALL(a, DoA(1));
565    a.DoA(1);
566    a.DoA(1);
567  }, "to be called once");
568}
569
570#if GTEST_HAS_STREAM_REDIRECTION
571
572// Tests that Google Mock doesn't print a warning when the number of
573// WillOnce() is adequate.
574TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
575  CaptureStdout();
576  {
577    MockB b;
578
579    // It's always fine to omit WillOnce() entirely.
580    EXPECT_CALL(b, DoB())
581        .Times(0);
582    EXPECT_CALL(b, DoB(1))
583        .Times(AtMost(1));
584    EXPECT_CALL(b, DoB(2))
585        .Times(1)
586        .WillRepeatedly(Return(1));
587
588    // It's fine for the number of WillOnce()s to equal the upper bound.
589    EXPECT_CALL(b, DoB(3))
590        .Times(Between(1, 2))
591        .WillOnce(Return(1))
592        .WillOnce(Return(2));
593
594    // It's fine for the number of WillOnce()s to be smaller than the
595    // upper bound when there is a WillRepeatedly().
596    EXPECT_CALL(b, DoB(4))
597        .Times(AtMost(3))
598        .WillOnce(Return(1))
599        .WillRepeatedly(Return(2));
600
601    // Satisfies the above expectations.
602    b.DoB(2);
603    b.DoB(3);
604  }
605  EXPECT_STREQ("", GetCapturedStdout().c_str());
606}
607
608// Tests that Google Mock warns on having too many actions in an
609// expectation compared to its cardinality.
610TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
611  CaptureStdout();
612  {
613    MockB b;
614
615    // Warns when the number of WillOnce()s is larger than the upper bound.
616    EXPECT_CALL(b, DoB())
617        .Times(0)
618        .WillOnce(Return(1));  // #1
619    EXPECT_CALL(b, DoB())
620        .Times(AtMost(1))
621        .WillOnce(Return(1))
622        .WillOnce(Return(2));  // #2
623    EXPECT_CALL(b, DoB(1))
624        .Times(1)
625        .WillOnce(Return(1))
626        .WillOnce(Return(2))
627        .RetiresOnSaturation();  // #3
628
629    // Warns when the number of WillOnce()s equals the upper bound and
630    // there is a WillRepeatedly().
631    EXPECT_CALL(b, DoB())
632        .Times(0)
633        .WillRepeatedly(Return(1));  // #4
634    EXPECT_CALL(b, DoB(2))
635        .Times(1)
636        .WillOnce(Return(1))
637        .WillRepeatedly(Return(2));  // #5
638
639    // Satisfies the above expectations.
640    b.DoB(1);
641    b.DoB(2);
642  }
643  const std::string output = GetCapturedStdout();
644  EXPECT_PRED_FORMAT2(
645      IsSubstring,
646      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
647      "Expected to be never called, but has 1 WillOnce().",
648      output);  // #1
649  EXPECT_PRED_FORMAT2(
650      IsSubstring,
651      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
652      "Expected to be called at most once, "
653      "but has 2 WillOnce()s.",
654      output);  // #2
655  EXPECT_PRED_FORMAT2(
656      IsSubstring,
657      "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
658      "Expected to be called once, but has 2 WillOnce()s.",
659      output);  // #3
660  EXPECT_PRED_FORMAT2(
661      IsSubstring,
662      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
663      "Expected to be never called, but has 0 WillOnce()s "
664      "and a WillRepeatedly().",
665      output);  // #4
666  EXPECT_PRED_FORMAT2(
667      IsSubstring,
668      "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
669      "Expected to be called once, but has 1 WillOnce() "
670      "and a WillRepeatedly().",
671      output);  // #5
672}
673
674// Tests that Google Mock warns on having too few actions in an
675// expectation compared to its cardinality.
676TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
677  MockB b;
678
679  EXPECT_CALL(b, DoB())
680      .Times(Between(2, 3))
681      .WillOnce(Return(1));
682
683  CaptureStdout();
684  b.DoB();
685  const std::string output = GetCapturedStdout();
686  EXPECT_PRED_FORMAT2(
687      IsSubstring,
688      "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
689      "Expected to be called between 2 and 3 times, "
690      "but has only 1 WillOnce().",
691      output);
692  b.DoB();
693}
694
695#endif  // GTEST_HAS_STREAM_REDIRECTION
696
697// Tests the semantics of ON_CALL().
698
699// Tests that the built-in default action is taken when no ON_CALL()
700// is specified.
701TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
702  MockB b;
703  EXPECT_CALL(b, DoB());
704
705  EXPECT_EQ(0, b.DoB());
706}
707
708// Tests that the built-in default action is taken when no ON_CALL()
709// matches the invocation.
710TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
711  MockB b;
712  ON_CALL(b, DoB(1))
713      .WillByDefault(Return(1));
714  EXPECT_CALL(b, DoB(_));
715
716  EXPECT_EQ(0, b.DoB(2));
717}
718
719// Tests that the last matching ON_CALL() action is taken.
720TEST(OnCallTest, PicksLastMatchingOnCall) {
721  MockB b;
722  ON_CALL(b, DoB(_))
723      .WillByDefault(Return(3));
724  ON_CALL(b, DoB(2))
725      .WillByDefault(Return(2));
726  ON_CALL(b, DoB(1))
727      .WillByDefault(Return(1));
728  EXPECT_CALL(b, DoB(_));
729
730  EXPECT_EQ(2, b.DoB(2));
731}
732
733// Tests the semantics of EXPECT_CALL().
734
735// Tests that any call is allowed when no EXPECT_CALL() is specified.
736TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
737  MockB b;
738  EXPECT_CALL(b, DoB());
739  // There is no expectation on DoB(int).
740
741  b.DoB();
742
743  // DoB(int) can be called any number of times.
744  b.DoB(1);
745  b.DoB(2);
746}
747
748// Tests that the last matching EXPECT_CALL() fires.
749TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
750  MockB b;
751  EXPECT_CALL(b, DoB(_))
752      .WillRepeatedly(Return(2));
753  EXPECT_CALL(b, DoB(1))
754      .WillRepeatedly(Return(1));
755
756  EXPECT_EQ(1, b.DoB(1));
757}
758
759// Tests lower-bound violation.
760TEST(ExpectCallTest, CatchesTooFewCalls) {
761  EXPECT_NONFATAL_FAILURE({  // NOLINT
762    MockB b;
763    EXPECT_CALL(b, DoB(5))
764        .Times(AtLeast(2));
765
766    b.DoB(5);
767  }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
768     "         Expected: to be called at least twice\n"
769     "           Actual: called once - unsatisfied and active");
770}
771
772// Tests that the cardinality can be inferred when no Times(...) is
773// specified.
774TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
775  {
776    MockB b;
777    EXPECT_CALL(b, DoB())
778        .WillOnce(Return(1))
779        .WillOnce(Return(2));
780
781    EXPECT_EQ(1, b.DoB());
782    EXPECT_EQ(2, b.DoB());
783  }
784
785  EXPECT_NONFATAL_FAILURE({  // NOLINT
786    MockB b;
787    EXPECT_CALL(b, DoB())
788        .WillOnce(Return(1))
789        .WillOnce(Return(2));
790
791    EXPECT_EQ(1, b.DoB());
792  }, "to be called twice");
793
794  {  // NOLINT
795    MockB b;
796    EXPECT_CALL(b, DoB())
797        .WillOnce(Return(1))
798        .WillOnce(Return(2));
799
800    EXPECT_EQ(1, b.DoB());
801    EXPECT_EQ(2, b.DoB());
802    EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
803  }
804}
805
806TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
807  {
808    MockB b;
809    EXPECT_CALL(b, DoB())
810        .WillOnce(Return(1))
811        .WillRepeatedly(Return(2));
812
813    EXPECT_EQ(1, b.DoB());
814  }
815
816  {  // NOLINT
817    MockB b;
818    EXPECT_CALL(b, DoB())
819        .WillOnce(Return(1))
820        .WillRepeatedly(Return(2));
821
822    EXPECT_EQ(1, b.DoB());
823    EXPECT_EQ(2, b.DoB());
824    EXPECT_EQ(2, b.DoB());
825  }
826
827  EXPECT_NONFATAL_FAILURE({  // NOLINT
828    MockB b;
829    EXPECT_CALL(b, DoB())
830        .WillOnce(Return(1))
831        .WillRepeatedly(Return(2));
832  }, "to be called at least once");
833}
834
835// Tests that the n-th action is taken for the n-th matching
836// invocation.
837TEST(ExpectCallTest, NthMatchTakesNthAction) {
838  MockB b;
839  EXPECT_CALL(b, DoB())
840      .WillOnce(Return(1))
841      .WillOnce(Return(2))
842      .WillOnce(Return(3));
843
844  EXPECT_EQ(1, b.DoB());
845  EXPECT_EQ(2, b.DoB());
846  EXPECT_EQ(3, b.DoB());
847}
848
849// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
850// list is exhausted.
851TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
852  MockB b;
853  EXPECT_CALL(b, DoB())
854      .WillOnce(Return(1))
855      .WillRepeatedly(Return(2));
856
857  EXPECT_EQ(1, b.DoB());
858  EXPECT_EQ(2, b.DoB());
859  EXPECT_EQ(2, b.DoB());
860}
861
862#if GTEST_HAS_STREAM_REDIRECTION
863
864// Tests that the default action is taken when the WillOnce(...) list is
865// exhausted and there is no WillRepeatedly().
866TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
867  MockB b;
868  EXPECT_CALL(b, DoB(_))
869      .Times(1);
870  EXPECT_CALL(b, DoB())
871      .Times(AnyNumber())
872      .WillOnce(Return(1))
873      .WillOnce(Return(2));
874
875  CaptureStdout();
876  EXPECT_EQ(0, b.DoB(1));  // Shouldn't generate a warning as the
877                           // expectation has no action clause at all.
878  EXPECT_EQ(1, b.DoB());
879  EXPECT_EQ(2, b.DoB());
880  const std::string output1 = GetCapturedStdout();
881  EXPECT_STREQ("", output1.c_str());
882
883  CaptureStdout();
884  EXPECT_EQ(0, b.DoB());
885  EXPECT_EQ(0, b.DoB());
886  const std::string output2 = GetCapturedStdout();
887  EXPECT_THAT(output2.c_str(),
888              HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
889                        "Called 3 times, but only 2 WillOnce()s are specified"
890                        " - returning default value."));
891  EXPECT_THAT(output2.c_str(),
892              HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
893                        "Called 4 times, but only 2 WillOnce()s are specified"
894                        " - returning default value."));
895}
896
897TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
898  MockB b;
899  std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
900  EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
901
902  EXPECT_EQ(1, b.DoB());
903
904  CaptureStdout();
905  EXPECT_EQ(0, b.DoB());
906  const std::string output = GetCapturedStdout();
907  // The warning message should contain the call location.
908  EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
909}
910
911TEST(FunctionMockerMessageTest,
912     ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
913  std::string on_call_location;
914  CaptureStdout();
915  {
916    NaggyMock<MockB> b;
917    on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
918    ON_CALL(b, DoB(_)).WillByDefault(Return(0));
919    b.DoB(0);
920  }
921  EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
922}
923
924#endif  // GTEST_HAS_STREAM_REDIRECTION
925
926// Tests that an uninteresting call performs the default action.
927TEST(UninterestingCallTest, DoesDefaultAction) {
928  // When there is an ON_CALL() statement, the action specified by it
929  // should be taken.
930  MockA a;
931  ON_CALL(a, Binary(_, _))
932      .WillByDefault(Return(true));
933  EXPECT_TRUE(a.Binary(1, 2));
934
935  // When there is no ON_CALL(), the default value for the return type
936  // should be returned.
937  MockB b;
938  EXPECT_EQ(0, b.DoB());
939}
940
941// Tests that an unexpected call performs the default action.
942TEST(UnexpectedCallTest, DoesDefaultAction) {
943  // When there is an ON_CALL() statement, the action specified by it
944  // should be taken.
945  MockA a;
946  ON_CALL(a, Binary(_, _))
947      .WillByDefault(Return(true));
948  EXPECT_CALL(a, Binary(0, 0));
949  a.Binary(0, 0);
950  bool result = false;
951  EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
952                          "Unexpected mock function call");
953  EXPECT_TRUE(result);
954
955  // When there is no ON_CALL(), the default value for the return type
956  // should be returned.
957  MockB b;
958  EXPECT_CALL(b, DoB(0))
959      .Times(0);
960  int n = -1;
961  EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
962                          "Unexpected mock function call");
963  EXPECT_EQ(0, n);
964}
965
966// Tests that when an unexpected void function generates the right
967// failure message.
968TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
969  // First, tests the message when there is only one EXPECT_CALL().
970  MockA a1;
971  EXPECT_CALL(a1, DoA(1));
972  a1.DoA(1);
973  // Ideally we should match the failure message against a regex, but
974  // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
975  // multiple sub-strings instead.
976  EXPECT_NONFATAL_FAILURE(
977      a1.DoA(9),
978      "Unexpected mock function call - returning directly.\n"
979      "    Function call: DoA(9)\n"
980      "Google Mock tried the following 1 expectation, but it didn't match:");
981  EXPECT_NONFATAL_FAILURE(
982      a1.DoA(9),
983      "  Expected arg #0: is equal to 1\n"
984      "           Actual: 9\n"
985      "         Expected: to be called once\n"
986      "           Actual: called once - saturated and active");
987
988  // Next, tests the message when there are more than one EXPECT_CALL().
989  MockA a2;
990  EXPECT_CALL(a2, DoA(1));
991  EXPECT_CALL(a2, DoA(3));
992  a2.DoA(1);
993  EXPECT_NONFATAL_FAILURE(
994      a2.DoA(2),
995      "Unexpected mock function call - returning directly.\n"
996      "    Function call: DoA(2)\n"
997      "Google Mock tried the following 2 expectations, but none matched:");
998  EXPECT_NONFATAL_FAILURE(
999      a2.DoA(2),
1000      "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1001      "  Expected arg #0: is equal to 1\n"
1002      "           Actual: 2\n"
1003      "         Expected: to be called once\n"
1004      "           Actual: called once - saturated and active");
1005  EXPECT_NONFATAL_FAILURE(
1006      a2.DoA(2),
1007      "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1008      "  Expected arg #0: is equal to 3\n"
1009      "           Actual: 2\n"
1010      "         Expected: to be called once\n"
1011      "           Actual: never called - unsatisfied and active");
1012  a2.DoA(3);
1013}
1014
1015// Tests that an unexpected non-void function generates the right
1016// failure message.
1017TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1018  MockB b1;
1019  EXPECT_CALL(b1, DoB(1));
1020  b1.DoB(1);
1021  EXPECT_NONFATAL_FAILURE(
1022      b1.DoB(2),
1023      "Unexpected mock function call - returning default value.\n"
1024      "    Function call: DoB(2)\n"
1025      "          Returns: 0\n"
1026      "Google Mock tried the following 1 expectation, but it didn't match:");
1027  EXPECT_NONFATAL_FAILURE(
1028      b1.DoB(2),
1029      "  Expected arg #0: is equal to 1\n"
1030      "           Actual: 2\n"
1031      "         Expected: to be called once\n"
1032      "           Actual: called once - saturated and active");
1033}
1034
1035// Tests that Google Mock explains that an retired expectation doesn't
1036// match the call.
1037TEST(UnexpectedCallTest, RetiredExpectation) {
1038  MockB b;
1039  EXPECT_CALL(b, DoB(1))
1040      .RetiresOnSaturation();
1041
1042  b.DoB(1);
1043  EXPECT_NONFATAL_FAILURE(
1044      b.DoB(1),
1045      "         Expected: the expectation is active\n"
1046      "           Actual: it is retired");
1047}
1048
1049// Tests that Google Mock explains that an expectation that doesn't
1050// match the arguments doesn't match the call.
1051TEST(UnexpectedCallTest, UnmatchedArguments) {
1052  MockB b;
1053  EXPECT_CALL(b, DoB(1));
1054
1055  EXPECT_NONFATAL_FAILURE(
1056      b.DoB(2),
1057      "  Expected arg #0: is equal to 1\n"
1058      "           Actual: 2\n");
1059  b.DoB(1);
1060}
1061
1062// Tests that Google Mock explains that an expectation with
1063// unsatisfied pre-requisites doesn't match the call.
1064TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1065  Sequence s1, s2;
1066  MockB b;
1067  EXPECT_CALL(b, DoB(1))
1068      .InSequence(s1);
1069  EXPECT_CALL(b, DoB(2))
1070      .Times(AnyNumber())
1071      .InSequence(s1);
1072  EXPECT_CALL(b, DoB(3))
1073      .InSequence(s2);
1074  EXPECT_CALL(b, DoB(4))
1075      .InSequence(s1, s2);
1076
1077  ::testing::TestPartResultArray failures;
1078  {
1079    ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1080    b.DoB(4);
1081    // Now 'failures' contains the Google Test failures generated by
1082    // the above statement.
1083  }
1084
1085  // There should be one non-fatal failure.
1086  ASSERT_EQ(1, failures.size());
1087  const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
1088  EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1089
1090  // Verifies that the failure message contains the two unsatisfied
1091  // pre-requisites but not the satisfied one.
1092#if GTEST_USES_PCRE
1093  EXPECT_THAT(r.message(), ContainsRegex(
1094      // PCRE has trouble using (.|\n) to match any character, but
1095      // supports the (?s) prefix for using . to match any character.
1096      "(?s)the following immediate pre-requisites are not satisfied:\n"
1097      ".*: pre-requisite #0\n"
1098      ".*: pre-requisite #1"));
1099#elif GTEST_USES_POSIX_RE
1100  EXPECT_THAT(r.message(), ContainsRegex(
1101      // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1102      // with (.|\n).
1103      "the following immediate pre-requisites are not satisfied:\n"
1104      "(.|\n)*: pre-requisite #0\n"
1105      "(.|\n)*: pre-requisite #1"));
1106#else
1107  // We can only use Google Test's own simple regex.
1108  EXPECT_THAT(r.message(), ContainsRegex(
1109      "the following immediate pre-requisites are not satisfied:"));
1110  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1111  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1112#endif  // GTEST_USES_PCRE
1113
1114  b.DoB(1);
1115  b.DoB(3);
1116  b.DoB(4);
1117}
1118
1119TEST(UndefinedReturnValueTest,
1120     ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1121  MockA a;
1122  // TODO(wan@google.com): We should really verify the output message,
1123  // but we cannot yet due to that EXPECT_DEATH only captures stderr
1124  // while Google Mock logs to stdout.
1125#if GTEST_HAS_EXCEPTIONS
1126  EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1127#else
1128  EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1129#endif
1130}
1131
1132// Tests that an excessive call (one whose arguments match the
1133// matchers but is called too many times) performs the default action.
1134TEST(ExcessiveCallTest, DoesDefaultAction) {
1135  // When there is an ON_CALL() statement, the action specified by it
1136  // should be taken.
1137  MockA a;
1138  ON_CALL(a, Binary(_, _))
1139      .WillByDefault(Return(true));
1140  EXPECT_CALL(a, Binary(0, 0));
1141  a.Binary(0, 0);
1142  bool result = false;
1143  EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1144                          "Mock function called more times than expected");
1145  EXPECT_TRUE(result);
1146
1147  // When there is no ON_CALL(), the default value for the return type
1148  // should be returned.
1149  MockB b;
1150  EXPECT_CALL(b, DoB(0))
1151      .Times(0);
1152  int n = -1;
1153  EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1154                          "Mock function called more times than expected");
1155  EXPECT_EQ(0, n);
1156}
1157
1158// Tests that when a void function is called too many times,
1159// the failure message contains the argument values.
1160TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1161  MockA a;
1162  EXPECT_CALL(a, DoA(_))
1163      .Times(0);
1164  EXPECT_NONFATAL_FAILURE(
1165      a.DoA(9),
1166      "Mock function called more times than expected - returning directly.\n"
1167      "    Function call: DoA(9)\n"
1168      "         Expected: to be never called\n"
1169      "           Actual: called once - over-saturated and active");
1170}
1171
1172// Tests that when a non-void function is called too many times, the
1173// failure message contains the argument values and the return value.
1174TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1175  MockB b;
1176  EXPECT_CALL(b, DoB(_));
1177  b.DoB(1);
1178  EXPECT_NONFATAL_FAILURE(
1179      b.DoB(2),
1180      "Mock function called more times than expected - "
1181      "returning default value.\n"
1182      "    Function call: DoB(2)\n"
1183      "          Returns: 0\n"
1184      "         Expected: to be called once\n"
1185      "           Actual: called twice - over-saturated and active");
1186}
1187
1188// Tests using sequences.
1189
1190TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1191  MockA a;
1192  {
1193    InSequence dummy;
1194
1195    EXPECT_CALL(a, DoA(1));
1196    EXPECT_CALL(a, DoA(2));
1197  }
1198
1199  EXPECT_NONFATAL_FAILURE({  // NOLINT
1200    a.DoA(2);
1201  }, "Unexpected mock function call");
1202
1203  a.DoA(1);
1204  a.DoA(2);
1205}
1206
1207TEST(InSequenceTest, NestedInSequence) {
1208  MockA a;
1209  {
1210    InSequence dummy;
1211
1212    EXPECT_CALL(a, DoA(1));
1213    {
1214      InSequence dummy2;
1215
1216      EXPECT_CALL(a, DoA(2));
1217      EXPECT_CALL(a, DoA(3));
1218    }
1219  }
1220
1221  EXPECT_NONFATAL_FAILURE({  // NOLINT
1222    a.DoA(1);
1223    a.DoA(3);
1224  }, "Unexpected mock function call");
1225
1226  a.DoA(2);
1227  a.DoA(3);
1228}
1229
1230TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1231  MockA a;
1232  {
1233    InSequence dummy;
1234
1235    EXPECT_CALL(a, DoA(1));
1236    EXPECT_CALL(a, DoA(2));
1237  }
1238  EXPECT_CALL(a, DoA(3));
1239
1240  EXPECT_NONFATAL_FAILURE({  // NOLINT
1241    a.DoA(2);
1242  }, "Unexpected mock function call");
1243
1244  a.DoA(3);
1245  a.DoA(1);
1246  a.DoA(2);
1247}
1248
1249// Tests that any order is allowed when no sequence is used.
1250TEST(SequenceTest, AnyOrderIsOkByDefault) {
1251  {
1252    MockA a;
1253    MockB b;
1254
1255    EXPECT_CALL(a, DoA(1));
1256    EXPECT_CALL(b, DoB())
1257        .Times(AnyNumber());
1258
1259    a.DoA(1);
1260    b.DoB();
1261  }
1262
1263  {  // NOLINT
1264    MockA a;
1265    MockB b;
1266
1267    EXPECT_CALL(a, DoA(1));
1268    EXPECT_CALL(b, DoB())
1269        .Times(AnyNumber());
1270
1271    b.DoB();
1272    a.DoA(1);
1273  }
1274}
1275
1276// Tests that the calls must be in strict order when a complete order
1277// is specified.
1278TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1279  MockA a;
1280  ON_CALL(a, ReturnResult(_))
1281      .WillByDefault(Return(Result()));
1282
1283  Sequence s;
1284  EXPECT_CALL(a, ReturnResult(1))
1285      .InSequence(s);
1286  EXPECT_CALL(a, ReturnResult(2))
1287      .InSequence(s);
1288  EXPECT_CALL(a, ReturnResult(3))
1289      .InSequence(s);
1290
1291  a.ReturnResult(1);
1292
1293  // May only be called after a.ReturnResult(2).
1294  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1295
1296  a.ReturnResult(2);
1297  a.ReturnResult(3);
1298}
1299
1300// Tests that the calls must be in strict order when a complete order
1301// is specified.
1302TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1303  MockA a;
1304  ON_CALL(a, ReturnResult(_))
1305      .WillByDefault(Return(Result()));
1306
1307  Sequence s;
1308  EXPECT_CALL(a, ReturnResult(1))
1309      .InSequence(s);
1310  EXPECT_CALL(a, ReturnResult(2))
1311      .InSequence(s);
1312
1313  // May only be called after a.ReturnResult(1).
1314  EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1315
1316  a.ReturnResult(1);
1317  a.ReturnResult(2);
1318}
1319
1320// Tests specifying a DAG using multiple sequences.
1321class PartialOrderTest : public testing::Test {
1322 protected:
1323  PartialOrderTest() {
1324    ON_CALL(a_, ReturnResult(_))
1325        .WillByDefault(Return(Result()));
1326
1327    // Specifies this partial ordering:
1328    //
1329    // a.ReturnResult(1) ==>
1330    //                       a.ReturnResult(2) * n  ==>  a.ReturnResult(3)
1331    // b.DoB() * 2       ==>
1332    Sequence x, y;
1333    EXPECT_CALL(a_, ReturnResult(1))
1334        .InSequence(x);
1335    EXPECT_CALL(b_, DoB())
1336        .Times(2)
1337        .InSequence(y);
1338    EXPECT_CALL(a_, ReturnResult(2))
1339        .Times(AnyNumber())
1340        .InSequence(x, y);
1341    EXPECT_CALL(a_, ReturnResult(3))
1342        .InSequence(x);
1343  }
1344
1345  MockA a_;
1346  MockB b_;
1347};
1348
1349TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1350  a_.ReturnResult(1);
1351  b_.DoB();
1352
1353  // May only be called after the second DoB().
1354  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1355
1356  b_.DoB();
1357  a_.ReturnResult(3);
1358}
1359
1360TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1361  // May only be called after ReturnResult(1).
1362  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1363
1364  a_.ReturnResult(1);
1365  b_.DoB();
1366  b_.DoB();
1367  a_.ReturnResult(3);
1368}
1369
1370TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1371  // May only be called last.
1372  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1373
1374  a_.ReturnResult(1);
1375  b_.DoB();
1376  b_.DoB();
1377  a_.ReturnResult(3);
1378}
1379
1380TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1381  a_.ReturnResult(1);
1382  b_.DoB();
1383  b_.DoB();
1384  a_.ReturnResult(3);
1385
1386  // May only be called before ReturnResult(3).
1387  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1388}
1389
1390TEST(SequenceTest, Retirement) {
1391  MockA a;
1392  Sequence s;
1393
1394  EXPECT_CALL(a, DoA(1))
1395      .InSequence(s);
1396  EXPECT_CALL(a, DoA(_))
1397      .InSequence(s)
1398      .RetiresOnSaturation();
1399  EXPECT_CALL(a, DoA(1))
1400      .InSequence(s);
1401
1402  a.DoA(1);
1403  a.DoA(2);
1404  a.DoA(1);
1405}
1406
1407// Tests Expectation.
1408
1409TEST(ExpectationTest, ConstrutorsWork) {
1410  MockA a;
1411  Expectation e1;  // Default ctor.
1412
1413  // Ctor from various forms of EXPECT_CALL.
1414  Expectation e2 = EXPECT_CALL(a, DoA(2));
1415  Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1416  {
1417    Sequence s;
1418    Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1419    Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1420  }
1421  Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1422  Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1423  Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1424  Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1425
1426  Expectation e10 = e2;  // Copy ctor.
1427
1428  EXPECT_THAT(e1, Ne(e2));
1429  EXPECT_THAT(e2, Eq(e10));
1430
1431  a.DoA(2);
1432  a.DoA(3);
1433  a.DoA(4);
1434  a.DoA(5);
1435  a.DoA(6);
1436  a.DoA(7);
1437  a.DoA(8);
1438  a.DoA(9);
1439}
1440
1441TEST(ExpectationTest, AssignmentWorks) {
1442  MockA a;
1443  Expectation e1;
1444  Expectation e2 = EXPECT_CALL(a, DoA(1));
1445
1446  EXPECT_THAT(e1, Ne(e2));
1447
1448  e1 = e2;
1449  EXPECT_THAT(e1, Eq(e2));
1450
1451  a.DoA(1);
1452}
1453
1454// Tests ExpectationSet.
1455
1456TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1457  ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1458}
1459
1460TEST(ExpectationSetTest, ConstructorsWork) {
1461  MockA a;
1462
1463  Expectation e1;
1464  const Expectation e2;
1465  ExpectationSet es1;  // Default ctor.
1466  ExpectationSet es2 = EXPECT_CALL(a, DoA(1));  // Ctor from EXPECT_CALL.
1467  ExpectationSet es3 = e1;  // Ctor from Expectation.
1468  ExpectationSet es4(e1);   // Ctor from Expectation; alternative syntax.
1469  ExpectationSet es5 = e2;  // Ctor from const Expectation.
1470  ExpectationSet es6(e2);   // Ctor from const Expectation; alternative syntax.
1471  ExpectationSet es7 = es2;  // Copy ctor.
1472
1473  EXPECT_EQ(0, es1.size());
1474  EXPECT_EQ(1, es2.size());
1475  EXPECT_EQ(1, es3.size());
1476  EXPECT_EQ(1, es4.size());
1477  EXPECT_EQ(1, es5.size());
1478  EXPECT_EQ(1, es6.size());
1479  EXPECT_EQ(1, es7.size());
1480
1481  EXPECT_THAT(es3, Ne(es2));
1482  EXPECT_THAT(es4, Eq(es3));
1483  EXPECT_THAT(es5, Eq(es4));
1484  EXPECT_THAT(es6, Eq(es5));
1485  EXPECT_THAT(es7, Eq(es2));
1486  a.DoA(1);
1487}
1488
1489TEST(ExpectationSetTest, AssignmentWorks) {
1490  ExpectationSet es1;
1491  ExpectationSet es2 = Expectation();
1492
1493  es1 = es2;
1494  EXPECT_EQ(1, es1.size());
1495  EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1496  EXPECT_THAT(es1, Eq(es2));
1497}
1498
1499TEST(ExpectationSetTest, InsertionWorks) {
1500  ExpectationSet es1;
1501  Expectation e1;
1502  es1 += e1;
1503  EXPECT_EQ(1, es1.size());
1504  EXPECT_THAT(*(es1.begin()), Eq(e1));
1505
1506  MockA a;
1507  Expectation e2 = EXPECT_CALL(a, DoA(1));
1508  es1 += e2;
1509  EXPECT_EQ(2, es1.size());
1510
1511  ExpectationSet::const_iterator it1 = es1.begin();
1512  ExpectationSet::const_iterator it2 = it1;
1513  ++it2;
1514  EXPECT_TRUE(*it1 == e1 || *it2 == e1);  // e1 must be in the set.
1515  EXPECT_TRUE(*it1 == e2 || *it2 == e2);  // e2 must be in the set too.
1516  a.DoA(1);
1517}
1518
1519TEST(ExpectationSetTest, SizeWorks) {
1520  ExpectationSet es;
1521  EXPECT_EQ(0, es.size());
1522
1523  es += Expectation();
1524  EXPECT_EQ(1, es.size());
1525
1526  MockA a;
1527  es += EXPECT_CALL(a, DoA(1));
1528  EXPECT_EQ(2, es.size());
1529
1530  a.DoA(1);
1531}
1532
1533TEST(ExpectationSetTest, IsEnumerable) {
1534  ExpectationSet es;
1535  EXPECT_TRUE(es.begin() == es.end());
1536
1537  es += Expectation();
1538  ExpectationSet::const_iterator it = es.begin();
1539  EXPECT_TRUE(it != es.end());
1540  EXPECT_THAT(*it, Eq(Expectation()));
1541  ++it;
1542  EXPECT_TRUE(it== es.end());
1543}
1544
1545// Tests the .After() clause.
1546
1547TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1548  MockA a;
1549  ExpectationSet es;
1550  es += EXPECT_CALL(a, DoA(1));
1551  es += EXPECT_CALL(a, DoA(2));
1552  EXPECT_CALL(a, DoA(3))
1553      .After(es);
1554
1555  a.DoA(1);
1556  a.DoA(2);
1557  a.DoA(3);
1558}
1559
1560TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1561  MockA a;
1562  MockB b;
1563  // The following also verifies that const Expectation objects work
1564  // too.  Do not remove the const modifiers.
1565  const Expectation e1 = EXPECT_CALL(a, DoA(1));
1566  const Expectation e2 = EXPECT_CALL(b, DoB())
1567      .Times(2)
1568      .After(e1);
1569  EXPECT_CALL(a, DoA(2)).After(e2);
1570
1571  a.DoA(1);
1572  b.DoB();
1573  b.DoB();
1574  a.DoA(2);
1575}
1576
1577// Calls must be in strict order when specified so using .After().
1578TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1579  MockA a;
1580  MockB b;
1581
1582  // Define ordering:
1583  //   a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1584  Expectation e1 = EXPECT_CALL(a, DoA(1));
1585  Expectation e2 = EXPECT_CALL(b, DoB())
1586      .After(e1);
1587  EXPECT_CALL(a, DoA(2))
1588      .After(e2);
1589
1590  a.DoA(1);
1591
1592  // May only be called after DoB().
1593  EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1594
1595  b.DoB();
1596  a.DoA(2);
1597}
1598
1599// Calls must be in strict order when specified so using .After().
1600TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
1601  MockA a;
1602  MockB b;
1603
1604  // Define ordering:
1605  //   a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
1606  Expectation e1 = EXPECT_CALL(a, DoA(1));
1607  Expectation e2 = EXPECT_CALL(b, DoB())
1608      .Times(2)
1609      .After(e1);
1610  EXPECT_CALL(a, DoA(2))
1611      .After(e2);
1612
1613  a.DoA(1);
1614  b.DoB();
1615
1616  // May only be called after the second DoB().
1617  EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1618
1619  b.DoB();
1620  a.DoA(2);
1621}
1622
1623// Calls must satisfy the partial order when specified so.
1624TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1625  MockA a;
1626  ON_CALL(a, ReturnResult(_))
1627      .WillByDefault(Return(Result()));
1628
1629  // Define ordering:
1630  //   a.DoA(1) ==>
1631  //   a.DoA(2) ==> a.ReturnResult(3)
1632  Expectation e = EXPECT_CALL(a, DoA(1));
1633  const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1634  EXPECT_CALL(a, ReturnResult(3))
1635      .After(e, es);
1636
1637  // May only be called last.
1638  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1639
1640  a.DoA(2);
1641  a.DoA(1);
1642  a.ReturnResult(3);
1643}
1644
1645// Calls must satisfy the partial order when specified so.
1646TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
1647  MockA a;
1648
1649  // Define ordering:
1650  //   a.DoA(1) ==>
1651  //   a.DoA(2) ==> a.DoA(3)
1652  Expectation e = EXPECT_CALL(a, DoA(1));
1653  const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1654  EXPECT_CALL(a, DoA(3))
1655      .After(e, es);
1656
1657  a.DoA(2);
1658
1659  // May only be called last.
1660  EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1661
1662  a.DoA(1);
1663  a.DoA(3);
1664}
1665
1666// .After() can be combined with .InSequence().
1667TEST(AfterTest, CanBeUsedWithInSequence) {
1668  MockA a;
1669  Sequence s;
1670  Expectation e = EXPECT_CALL(a, DoA(1));
1671  EXPECT_CALL(a, DoA(2)).InSequence(s);
1672  EXPECT_CALL(a, DoA(3))
1673      .InSequence(s)
1674      .After(e);
1675
1676  a.DoA(1);
1677
1678  // May only be after DoA(2).
1679  EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1680
1681  a.DoA(2);
1682  a.DoA(3);
1683}
1684
1685// .After() can be called multiple times.
1686TEST(AfterTest, CanBeCalledManyTimes) {
1687  MockA a;
1688  Expectation e1 = EXPECT_CALL(a, DoA(1));
1689  Expectation e2 = EXPECT_CALL(a, DoA(2));
1690  Expectation e3 = EXPECT_CALL(a, DoA(3));
1691  EXPECT_CALL(a, DoA(4))
1692      .After(e1)
1693      .After(e2)
1694      .After(e3);
1695
1696  a.DoA(3);
1697  a.DoA(1);
1698  a.DoA(2);
1699  a.DoA(4);
1700}
1701
1702// .After() accepts up to 5 arguments.
1703TEST(AfterTest, AcceptsUpToFiveArguments) {
1704  MockA a;
1705  Expectation e1 = EXPECT_CALL(a, DoA(1));
1706  Expectation e2 = EXPECT_CALL(a, DoA(2));
1707  Expectation e3 = EXPECT_CALL(a, DoA(3));
1708  ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1709  ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1710  EXPECT_CALL(a, DoA(6))
1711      .After(e1, e2, e3, es1, es2);
1712
1713  a.DoA(5);
1714  a.DoA(2);
1715  a.DoA(4);
1716  a.DoA(1);
1717  a.DoA(3);
1718  a.DoA(6);
1719}
1720
1721// .After() allows input to contain duplicated Expectations.
1722TEST(AfterTest, AcceptsDuplicatedInput) {
1723  MockA a;
1724  ON_CALL(a, ReturnResult(_))
1725      .WillByDefault(Return(Result()));
1726
1727  // Define ordering:
1728  //   DoA(1) ==>
1729  //   DoA(2) ==> ReturnResult(3)
1730  Expectation e1 = EXPECT_CALL(a, DoA(1));
1731  Expectation e2 = EXPECT_CALL(a, DoA(2));
1732  ExpectationSet es;
1733  es += e1;
1734  es += e2;
1735  EXPECT_CALL(a, ReturnResult(3))
1736      .After(e1, e2, es, e1);
1737
1738  a.DoA(1);
1739
1740  // May only be after DoA(2).
1741  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1742
1743  a.DoA(2);
1744  a.ReturnResult(3);
1745}
1746
1747// An Expectation added to an ExpectationSet after it has been used in
1748// an .After() has no effect.
1749TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1750  MockA a;
1751  ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1752  Expectation e2 = EXPECT_CALL(a, DoA(2));
1753  EXPECT_CALL(a, DoA(3))
1754      .After(es1);
1755  es1 += e2;
1756
1757  a.DoA(1);
1758  a.DoA(3);
1759  a.DoA(2);
1760}
1761
1762// Tests that Google Mock correctly handles calls to mock functions
1763// after a mock object owning one of their pre-requisites has died.
1764
1765// Tests that calls that satisfy the original spec are successful.
1766TEST(DeletingMockEarlyTest, Success1) {
1767  MockB* const b1 = new MockB;
1768  MockA* const a = new MockA;
1769  MockB* const b2 = new MockB;
1770
1771  {
1772    InSequence dummy;
1773    EXPECT_CALL(*b1, DoB(_))
1774        .WillOnce(Return(1));
1775    EXPECT_CALL(*a, Binary(_, _))
1776        .Times(AnyNumber())
1777        .WillRepeatedly(Return(true));
1778    EXPECT_CALL(*b2, DoB(_))
1779        .Times(AnyNumber())
1780        .WillRepeatedly(Return(2));
1781  }
1782
1783  EXPECT_EQ(1, b1->DoB(1));
1784  delete b1;
1785  // a's pre-requisite has died.
1786  EXPECT_TRUE(a->Binary(0, 1));
1787  delete b2;
1788  // a's successor has died.
1789  EXPECT_TRUE(a->Binary(1, 2));
1790  delete a;
1791}
1792
1793// Tests that calls that satisfy the original spec are successful.
1794TEST(DeletingMockEarlyTest, Success2) {
1795  MockB* const b1 = new MockB;
1796  MockA* const a = new MockA;
1797  MockB* const b2 = new MockB;
1798
1799  {
1800    InSequence dummy;
1801    EXPECT_CALL(*b1, DoB(_))
1802        .WillOnce(Return(1));
1803    EXPECT_CALL(*a, Binary(_, _))
1804        .Times(AnyNumber());
1805    EXPECT_CALL(*b2, DoB(_))
1806        .Times(AnyNumber())
1807        .WillRepeatedly(Return(2));
1808  }
1809
1810  delete a;  // a is trivially satisfied.
1811  EXPECT_EQ(1, b1->DoB(1));
1812  EXPECT_EQ(2, b2->DoB(2));
1813  delete b1;
1814  delete b2;
1815}
1816
1817// Tests that it's OK to delete a mock object itself in its action.
1818
1819// Suppresses warning on unreferenced formal parameter in MSVC with
1820// -W4.
1821#ifdef _MSC_VER
1822# pragma warning(push)
1823# pragma warning(disable:4100)
1824#endif
1825
1826ACTION_P(Delete, ptr) { delete ptr; }
1827
1828#ifdef _MSC_VER
1829# pragma warning(pop)
1830#endif
1831
1832TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1833  MockA* const a = new MockA;
1834  EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1835  a->DoA(42);  // This will cause a to be deleted.
1836}
1837
1838TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1839  MockA* const a = new MockA;
1840  EXPECT_CALL(*a, ReturnResult(_))
1841      .WillOnce(DoAll(Delete(a), Return(Result())));
1842  a->ReturnResult(42);  // This will cause a to be deleted.
1843}
1844
1845// Tests that calls that violate the original spec yield failures.
1846TEST(DeletingMockEarlyTest, Failure1) {
1847  MockB* const b1 = new MockB;
1848  MockA* const a = new MockA;
1849  MockB* const b2 = new MockB;
1850
1851  {
1852    InSequence dummy;
1853    EXPECT_CALL(*b1, DoB(_))
1854        .WillOnce(Return(1));
1855    EXPECT_CALL(*a, Binary(_, _))
1856        .Times(AnyNumber());
1857    EXPECT_CALL(*b2, DoB(_))
1858        .Times(AnyNumber())
1859        .WillRepeatedly(Return(2));
1860  }
1861
1862  delete a;  // a is trivially satisfied.
1863  EXPECT_NONFATAL_FAILURE({
1864    b2->DoB(2);
1865  }, "Unexpected mock function call");
1866  EXPECT_EQ(1, b1->DoB(1));
1867  delete b1;
1868  delete b2;
1869}
1870
1871// Tests that calls that violate the original spec yield failures.
1872TEST(DeletingMockEarlyTest, Failure2) {
1873  MockB* const b1 = new MockB;
1874  MockA* const a = new MockA;
1875  MockB* const b2 = new MockB;
1876
1877  {
1878    InSequence dummy;
1879    EXPECT_CALL(*b1, DoB(_));
1880    EXPECT_CALL(*a, Binary(_, _))
1881        .Times(AnyNumber());
1882    EXPECT_CALL(*b2, DoB(_))
1883        .Times(AnyNumber());
1884  }
1885
1886  EXPECT_NONFATAL_FAILURE(delete b1,
1887                          "Actual: never called");
1888  EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1889                          "Unexpected mock function call");
1890  EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1891                          "Unexpected mock function call");
1892  delete a;
1893  delete b2;
1894}
1895
1896class EvenNumberCardinality : public CardinalityInterface {
1897 public:
1898  // Returns true iff call_count calls will satisfy this cardinality.
1899  virtual bool IsSatisfiedByCallCount(int call_count) const {
1900    return call_count % 2 == 0;
1901  }
1902
1903  // Returns true iff call_count calls will saturate this cardinality.
1904  virtual bool IsSaturatedByCallCount(int /* call_count */) const {
1905    return false;
1906  }
1907
1908  // Describes self to an ostream.
1909  virtual void DescribeTo(::std::ostream* os) const {
1910    *os << "called even number of times";
1911  }
1912};
1913
1914Cardinality EvenNumber() {
1915  return Cardinality(new EvenNumberCardinality);
1916}
1917
1918TEST(ExpectationBaseTest,
1919     AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1920  MockA* a = new MockA;
1921  Sequence s;
1922
1923  EXPECT_CALL(*a, DoA(1))
1924      .Times(EvenNumber())
1925      .InSequence(s);
1926  EXPECT_CALL(*a, DoA(2))
1927      .Times(AnyNumber())
1928      .InSequence(s);
1929  EXPECT_CALL(*a, DoA(3))
1930      .Times(AnyNumber());
1931
1932  a->DoA(3);
1933  a->DoA(1);
1934  EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1935  EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1936}
1937
1938// The following tests verify the message generated when a mock
1939// function is called.
1940
1941struct Printable {
1942};
1943
1944inline void operator<<(::std::ostream& os, const Printable&) {
1945  os << "Printable";
1946}
1947
1948struct Unprintable {
1949  Unprintable() : value(0) {}
1950  int value;
1951};
1952
1953class MockC {
1954 public:
1955  MockC() {}
1956
1957  MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1958                                const Printable& x, Unprintable y));
1959  MOCK_METHOD0(NonVoidMethod, int());  // NOLINT
1960
1961 private:
1962  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
1963};
1964
1965class VerboseFlagPreservingFixture : public testing::Test {
1966 protected:
1967  VerboseFlagPreservingFixture()
1968      : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
1969
1970  ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
1971
1972 private:
1973  const string saved_verbose_flag_;
1974
1975  GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
1976};
1977
1978#if GTEST_HAS_STREAM_REDIRECTION
1979
1980// Tests that an uninteresting mock function call on a naggy mock
1981// generates a warning without the stack trace when
1982// --gmock_verbose=warning is specified.
1983TEST(FunctionCallMessageTest,
1984     UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
1985  GMOCK_FLAG(verbose) = kWarningVerbosity;
1986  NaggyMock<MockC> c;
1987  CaptureStdout();
1988  c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1989  const std::string output = GetCapturedStdout();
1990  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1991  EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
1992}
1993
1994// Tests that an uninteresting mock function call on a naggy mock
1995// generates a warning containing the stack trace when
1996// --gmock_verbose=info is specified.
1997TEST(FunctionCallMessageTest,
1998     UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
1999  GMOCK_FLAG(verbose) = kInfoVerbosity;
2000  NaggyMock<MockC> c;
2001  CaptureStdout();
2002  c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2003  const std::string output = GetCapturedStdout();
2004  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2005  EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
2006
2007# ifndef NDEBUG
2008
2009  // We check the stack trace content in dbg-mode only, as opt-mode
2010  // may inline the call we are interested in seeing.
2011
2012  // Verifies that a void mock function's name appears in the stack
2013  // trace.
2014  EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2015
2016  // Verifies that a non-void mock function's name appears in the
2017  // stack trace.
2018  CaptureStdout();
2019  c.NonVoidMethod();
2020  const std::string output2 = GetCapturedStdout();
2021  EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2022
2023# endif  // NDEBUG
2024}
2025
2026// Tests that an uninteresting mock function call on a naggy mock
2027// causes the function arguments and return value to be printed.
2028TEST(FunctionCallMessageTest,
2029     UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2030  // A non-void mock function.
2031  NaggyMock<MockB> b;
2032  CaptureStdout();
2033  b.DoB();
2034  const std::string output1 = GetCapturedStdout();
2035  EXPECT_PRED_FORMAT2(
2036      IsSubstring,
2037      "Uninteresting mock function call - returning default value.\n"
2038      "    Function call: DoB()\n"
2039      "          Returns: 0\n", output1.c_str());
2040  // Makes sure the return value is printed.
2041
2042  // A void mock function.
2043  NaggyMock<MockC> c;
2044  CaptureStdout();
2045  c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2046  const std::string output2 = GetCapturedStdout();
2047  EXPECT_THAT(output2.c_str(),
2048              ContainsRegex(
2049                  "Uninteresting mock function call - returning directly\\.\n"
2050                  "    Function call: VoidMethod"
2051                  "\\(false, 5, \"Hi\", NULL, @.+ "
2052                  "Printable, 4-byte object <00-00 00-00>\\)"));
2053  // A void function has no return value to print.
2054}
2055
2056// Tests how the --gmock_verbose flag affects Google Mock's output.
2057
2058class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2059 public:
2060  // Verifies that the given Google Mock output is correct.  (When
2061  // should_print is true, the output should match the given regex and
2062  // contain the given function name in the stack trace.  When it's
2063  // false, the output should be empty.)
2064  void VerifyOutput(const std::string& output, bool should_print,
2065                    const string& expected_substring,
2066                    const string& function_name) {
2067    if (should_print) {
2068      EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2069# ifndef NDEBUG
2070      // We check the stack trace content in dbg-mode only, as opt-mode
2071      // may inline the call we are interested in seeing.
2072      EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2073# else
2074      // Suppresses 'unused function parameter' warnings.
2075      static_cast<void>(function_name);
2076# endif  // NDEBUG
2077    } else {
2078      EXPECT_STREQ("", output.c_str());
2079    }
2080  }
2081
2082  // Tests how the flag affects expected calls.
2083  void TestExpectedCall(bool should_print) {
2084    MockA a;
2085    EXPECT_CALL(a, DoA(5));
2086    EXPECT_CALL(a, Binary(_, 1))
2087        .WillOnce(Return(true));
2088
2089    // A void-returning function.
2090    CaptureStdout();
2091    a.DoA(5);
2092    VerifyOutput(
2093        GetCapturedStdout(),
2094        should_print,
2095        "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2096        "    Function call: DoA(5)\n"
2097        "Stack trace:\n",
2098        "DoA");
2099
2100    // A non-void-returning function.
2101    CaptureStdout();
2102    a.Binary(2, 1);
2103    VerifyOutput(
2104        GetCapturedStdout(),
2105        should_print,
2106        "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2107        "    Function call: Binary(2, 1)\n"
2108        "          Returns: true\n"
2109        "Stack trace:\n",
2110        "Binary");
2111  }
2112
2113  // Tests how the flag affects uninteresting calls on a naggy mock.
2114  void TestUninterestingCallOnNaggyMock(bool should_print) {
2115    NaggyMock<MockA> a;
2116    const string note =
2117        "NOTE: You can safely ignore the above warning unless this "
2118        "call should not happen.  Do not suppress it by blindly adding "
2119        "an EXPECT_CALL() if you don't mean to enforce the call.  "
2120        "See http://code.google.com/p/googlemock/wiki/CookBook#"
2121        "Knowing_When_to_Expect for details.";
2122
2123    // A void-returning function.
2124    CaptureStdout();
2125    a.DoA(5);
2126    VerifyOutput(
2127        GetCapturedStdout(),
2128        should_print,
2129        "\nGMOCK WARNING:\n"
2130        "Uninteresting mock function call - returning directly.\n"
2131        "    Function call: DoA(5)\n" +
2132        note,
2133        "DoA");
2134
2135    // A non-void-returning function.
2136    CaptureStdout();
2137    a.Binary(2, 1);
2138    VerifyOutput(
2139        GetCapturedStdout(),
2140        should_print,
2141        "\nGMOCK WARNING:\n"
2142        "Uninteresting mock function call - returning default value.\n"
2143        "    Function call: Binary(2, 1)\n"
2144        "          Returns: false\n" +
2145        note,
2146        "Binary");
2147  }
2148};
2149
2150// Tests that --gmock_verbose=info causes both expected and
2151// uninteresting calls to be reported.
2152TEST_F(GMockVerboseFlagTest, Info) {
2153  GMOCK_FLAG(verbose) = kInfoVerbosity;
2154  TestExpectedCall(true);
2155  TestUninterestingCallOnNaggyMock(true);
2156}
2157
2158// Tests that --gmock_verbose=warning causes uninteresting calls to be
2159// reported.
2160TEST_F(GMockVerboseFlagTest, Warning) {
2161  GMOCK_FLAG(verbose) = kWarningVerbosity;
2162  TestExpectedCall(false);
2163  TestUninterestingCallOnNaggyMock(true);
2164}
2165
2166// Tests that --gmock_verbose=warning causes neither expected nor
2167// uninteresting calls to be reported.
2168TEST_F(GMockVerboseFlagTest, Error) {
2169  GMOCK_FLAG(verbose) = kErrorVerbosity;
2170  TestExpectedCall(false);
2171  TestUninterestingCallOnNaggyMock(false);
2172}
2173
2174// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2175// as --gmock_verbose=warning.
2176TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2177  GMOCK_FLAG(verbose) = "invalid";  // Treated as "warning".
2178  TestExpectedCall(false);
2179  TestUninterestingCallOnNaggyMock(true);
2180}
2181
2182#endif  // GTEST_HAS_STREAM_REDIRECTION
2183
2184// A helper class that generates a failure when printed.  We use it to
2185// ensure that Google Mock doesn't print a value (even to an internal
2186// buffer) when it is not supposed to do so.
2187class PrintMeNot {};
2188
2189void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2190  ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2191                << "printed even to an internal buffer.";
2192}
2193
2194class LogTestHelper {
2195 public:
2196  LogTestHelper() {}
2197
2198  MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2199
2200 private:
2201  GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2202};
2203
2204class GMockLogTest : public VerboseFlagPreservingFixture {
2205 protected:
2206  LogTestHelper helper_;
2207};
2208
2209TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2210  GMOCK_FLAG(verbose) = kWarningVerbosity;
2211  EXPECT_CALL(helper_, Foo(_))
2212      .WillOnce(Return(PrintMeNot()));
2213  helper_.Foo(PrintMeNot());  // This is an expected call.
2214}
2215
2216TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2217  GMOCK_FLAG(verbose) = kErrorVerbosity;
2218  EXPECT_CALL(helper_, Foo(_))
2219      .WillOnce(Return(PrintMeNot()));
2220  helper_.Foo(PrintMeNot());  // This is an expected call.
2221}
2222
2223TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2224  GMOCK_FLAG(verbose) = kErrorVerbosity;
2225  ON_CALL(helper_, Foo(_))
2226      .WillByDefault(Return(PrintMeNot()));
2227  helper_.Foo(PrintMeNot());  // This should generate a warning.
2228}
2229
2230// Tests Mock::AllowLeak().
2231
2232TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2233  MockA* a = new MockA;
2234  Mock::AllowLeak(a);
2235}
2236
2237TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2238  MockA* a = new MockA;
2239  Mock::AllowLeak(a);
2240  ON_CALL(*a, DoA(_)).WillByDefault(Return());
2241  a->DoA(0);
2242}
2243
2244TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2245  MockA* a = new MockA;
2246  ON_CALL(*a, DoA(_)).WillByDefault(Return());
2247  Mock::AllowLeak(a);
2248}
2249
2250TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2251  MockA* a = new MockA;
2252  Mock::AllowLeak(a);
2253  EXPECT_CALL(*a, DoA(_));
2254  a->DoA(0);
2255}
2256
2257TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2258  MockA* a = new MockA;
2259  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2260  Mock::AllowLeak(a);
2261}
2262
2263TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2264  MockA* a = new MockA;
2265  ON_CALL(*a, DoA(_)).WillByDefault(Return());
2266  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2267  Mock::AllowLeak(a);
2268}
2269
2270// Tests that we can verify and clear a mock object's expectations
2271// when none of its methods has expectations.
2272TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2273  MockB b;
2274  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2275
2276  // There should be no expectations on the methods now, so we can
2277  // freely call them.
2278  EXPECT_EQ(0, b.DoB());
2279  EXPECT_EQ(0, b.DoB(1));
2280}
2281
2282// Tests that we can verify and clear a mock object's expectations
2283// when some, but not all, of its methods have expectations *and* the
2284// verification succeeds.
2285TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2286  MockB b;
2287  EXPECT_CALL(b, DoB())
2288      .WillOnce(Return(1));
2289  b.DoB();
2290  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2291
2292  // There should be no expectations on the methods now, so we can
2293  // freely call them.
2294  EXPECT_EQ(0, b.DoB());
2295  EXPECT_EQ(0, b.DoB(1));
2296}
2297
2298// Tests that we can verify and clear a mock object's expectations
2299// when some, but not all, of its methods have expectations *and* the
2300// verification fails.
2301TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2302  MockB b;
2303  EXPECT_CALL(b, DoB())
2304      .WillOnce(Return(1));
2305  bool result = true;
2306  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2307                          "Actual: never called");
2308  ASSERT_FALSE(result);
2309
2310  // There should be no expectations on the methods now, so we can
2311  // freely call them.
2312  EXPECT_EQ(0, b.DoB());
2313  EXPECT_EQ(0, b.DoB(1));
2314}
2315
2316// Tests that we can verify and clear a mock object's expectations
2317// when all of its methods have expectations.
2318TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2319  MockB b;
2320  EXPECT_CALL(b, DoB())
2321      .WillOnce(Return(1));
2322  EXPECT_CALL(b, DoB(_))
2323      .WillOnce(Return(2));
2324  b.DoB();
2325  b.DoB(1);
2326  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2327
2328  // There should be no expectations on the methods now, so we can
2329  // freely call them.
2330  EXPECT_EQ(0, b.DoB());
2331  EXPECT_EQ(0, b.DoB(1));
2332}
2333
2334// Tests that we can verify and clear a mock object's expectations
2335// when a method has more than one expectation.
2336TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2337  MockB b;
2338  EXPECT_CALL(b, DoB(0))
2339      .WillOnce(Return(1));
2340  EXPECT_CALL(b, DoB(_))
2341      .WillOnce(Return(2));
2342  b.DoB(1);
2343  bool result = true;
2344  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2345                          "Actual: never called");
2346  ASSERT_FALSE(result);
2347
2348  // There should be no expectations on the methods now, so we can
2349  // freely call them.
2350  EXPECT_EQ(0, b.DoB());
2351  EXPECT_EQ(0, b.DoB(1));
2352}
2353
2354// Tests that we can call VerifyAndClearExpectations() on the same
2355// mock object multiple times.
2356TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2357  MockB b;
2358  EXPECT_CALL(b, DoB());
2359  b.DoB();
2360  Mock::VerifyAndClearExpectations(&b);
2361
2362  EXPECT_CALL(b, DoB(_))
2363      .WillOnce(Return(1));
2364  b.DoB(1);
2365  Mock::VerifyAndClearExpectations(&b);
2366  Mock::VerifyAndClearExpectations(&b);
2367
2368  // There should be no expectations on the methods now, so we can
2369  // freely call them.
2370  EXPECT_EQ(0, b.DoB());
2371  EXPECT_EQ(0, b.DoB(1));
2372}
2373
2374// Tests that we can clear a mock object's default actions when none
2375// of its methods has default actions.
2376TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2377  MockB b;
2378  // If this crashes or generates a failure, the test will catch it.
2379  Mock::VerifyAndClear(&b);
2380  EXPECT_EQ(0, b.DoB());
2381}
2382
2383// Tests that we can clear a mock object's default actions when some,
2384// but not all of its methods have default actions.
2385TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2386  MockB b;
2387  ON_CALL(b, DoB())
2388      .WillByDefault(Return(1));
2389
2390  Mock::VerifyAndClear(&b);
2391
2392  // Verifies that the default action of int DoB() was removed.
2393  EXPECT_EQ(0, b.DoB());
2394}
2395
2396// Tests that we can clear a mock object's default actions when all of
2397// its methods have default actions.
2398TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2399  MockB b;
2400  ON_CALL(b, DoB())
2401      .WillByDefault(Return(1));
2402  ON_CALL(b, DoB(_))
2403      .WillByDefault(Return(2));
2404
2405  Mock::VerifyAndClear(&b);
2406
2407  // Verifies that the default action of int DoB() was removed.
2408  EXPECT_EQ(0, b.DoB());
2409
2410  // Verifies that the default action of int DoB(int) was removed.
2411  EXPECT_EQ(0, b.DoB(0));
2412}
2413
2414// Tests that we can clear a mock object's default actions when a
2415// method has more than one ON_CALL() set on it.
2416TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2417  MockB b;
2418  ON_CALL(b, DoB(0))
2419      .WillByDefault(Return(1));
2420  ON_CALL(b, DoB(_))
2421      .WillByDefault(Return(2));
2422
2423  Mock::VerifyAndClear(&b);
2424
2425  // Verifies that the default actions (there are two) of int DoB(int)
2426  // were removed.
2427  EXPECT_EQ(0, b.DoB(0));
2428  EXPECT_EQ(0, b.DoB(1));
2429}
2430
2431// Tests that we can call VerifyAndClear() on a mock object multiple
2432// times.
2433TEST(VerifyAndClearTest, CanCallManyTimes) {
2434  MockB b;
2435  ON_CALL(b, DoB())
2436      .WillByDefault(Return(1));
2437  Mock::VerifyAndClear(&b);
2438  Mock::VerifyAndClear(&b);
2439
2440  ON_CALL(b, DoB(_))
2441      .WillByDefault(Return(1));
2442  Mock::VerifyAndClear(&b);
2443
2444  EXPECT_EQ(0, b.DoB());
2445  EXPECT_EQ(0, b.DoB(1));
2446}
2447
2448// Tests that VerifyAndClear() works when the verification succeeds.
2449TEST(VerifyAndClearTest, Success) {
2450  MockB b;
2451  ON_CALL(b, DoB())
2452      .WillByDefault(Return(1));
2453  EXPECT_CALL(b, DoB(1))
2454      .WillOnce(Return(2));
2455
2456  b.DoB();
2457  b.DoB(1);
2458  ASSERT_TRUE(Mock::VerifyAndClear(&b));
2459
2460  // There should be no expectations on the methods now, so we can
2461  // freely call them.
2462  EXPECT_EQ(0, b.DoB());
2463  EXPECT_EQ(0, b.DoB(1));
2464}
2465
2466// Tests that VerifyAndClear() works when the verification fails.
2467TEST(VerifyAndClearTest, Failure) {
2468  MockB b;
2469  ON_CALL(b, DoB(_))
2470      .WillByDefault(Return(1));
2471  EXPECT_CALL(b, DoB())
2472      .WillOnce(Return(2));
2473
2474  b.DoB(1);
2475  bool result = true;
2476  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2477                          "Actual: never called");
2478  ASSERT_FALSE(result);
2479
2480  // There should be no expectations on the methods now, so we can
2481  // freely call them.
2482  EXPECT_EQ(0, b.DoB());
2483  EXPECT_EQ(0, b.DoB(1));
2484}
2485
2486// Tests that VerifyAndClear() works when the default actions and
2487// expectations are set on a const mock object.
2488TEST(VerifyAndClearTest, Const) {
2489  MockB b;
2490  ON_CALL(Const(b), DoB())
2491      .WillByDefault(Return(1));
2492
2493  EXPECT_CALL(Const(b), DoB())
2494      .WillOnce(DoDefault())
2495      .WillOnce(Return(2));
2496
2497  b.DoB();
2498  b.DoB();
2499  ASSERT_TRUE(Mock::VerifyAndClear(&b));
2500
2501  // There should be no expectations on the methods now, so we can
2502  // freely call them.
2503  EXPECT_EQ(0, b.DoB());
2504  EXPECT_EQ(0, b.DoB(1));
2505}
2506
2507// Tests that we can set default actions and expectations on a mock
2508// object after VerifyAndClear() has been called on it.
2509TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2510  MockB b;
2511  ON_CALL(b, DoB())
2512      .WillByDefault(Return(1));
2513  EXPECT_CALL(b, DoB(_))
2514      .WillOnce(Return(2));
2515  b.DoB(1);
2516
2517  Mock::VerifyAndClear(&b);
2518
2519  EXPECT_CALL(b, DoB())
2520      .WillOnce(Return(3));
2521  ON_CALL(b, DoB(_))
2522      .WillByDefault(Return(4));
2523
2524  EXPECT_EQ(3, b.DoB());
2525  EXPECT_EQ(4, b.DoB(1));
2526}
2527
2528// Tests that calling VerifyAndClear() on one mock object does not
2529// affect other mock objects (either of the same type or not).
2530TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2531  MockA a;
2532  MockB b1;
2533  MockB b2;
2534
2535  ON_CALL(a, Binary(_, _))
2536      .WillByDefault(Return(true));
2537  EXPECT_CALL(a, Binary(_, _))
2538      .WillOnce(DoDefault())
2539      .WillOnce(Return(false));
2540
2541  ON_CALL(b1, DoB())
2542      .WillByDefault(Return(1));
2543  EXPECT_CALL(b1, DoB(_))
2544      .WillOnce(Return(2));
2545
2546  ON_CALL(b2, DoB())
2547      .WillByDefault(Return(3));
2548  EXPECT_CALL(b2, DoB(_));
2549
2550  b2.DoB(0);
2551  Mock::VerifyAndClear(&b2);
2552
2553  // Verifies that the default actions and expectations of a and b1
2554  // are still in effect.
2555  EXPECT_TRUE(a.Binary(0, 0));
2556  EXPECT_FALSE(a.Binary(0, 0));
2557
2558  EXPECT_EQ(1, b1.DoB());
2559  EXPECT_EQ(2, b1.DoB(0));
2560}
2561
2562TEST(VerifyAndClearTest,
2563     DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2564  linked_ptr<MockA> a(new MockA);
2565  ReferenceHoldingMock test_mock;
2566
2567  // EXPECT_CALL stores a reference to a inside test_mock.
2568  EXPECT_CALL(test_mock, AcceptReference(_))
2569      .WillRepeatedly(SetArgPointee<0>(a));
2570
2571  // Throw away the reference to the mock that we have in a. After this, the
2572  // only reference to it is stored by test_mock.
2573  a.reset();
2574
2575  // When test_mock goes out of scope, it destroys the last remaining reference
2576  // to the mock object originally pointed to by a. This will cause the MockA
2577  // destructor to be called from inside the ReferenceHoldingMock destructor.
2578  // The state of all mocks is protected by a single global lock, but there
2579  // should be no deadlock.
2580}
2581
2582TEST(VerifyAndClearTest,
2583     DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2584  linked_ptr<MockA> a(new MockA);
2585  ReferenceHoldingMock test_mock;
2586
2587  // ON_CALL stores a reference to a inside test_mock.
2588  ON_CALL(test_mock, AcceptReference(_))
2589      .WillByDefault(SetArgPointee<0>(a));
2590
2591  // Throw away the reference to the mock that we have in a. After this, the
2592  // only reference to it is stored by test_mock.
2593  a.reset();
2594
2595  // When test_mock goes out of scope, it destroys the last remaining reference
2596  // to the mock object originally pointed to by a. This will cause the MockA
2597  // destructor to be called from inside the ReferenceHoldingMock destructor.
2598  // The state of all mocks is protected by a single global lock, but there
2599  // should be no deadlock.
2600}
2601
2602// Tests that a mock function's action can call a mock function
2603// (either the same function or a different one) either as an explicit
2604// action or as a default action without causing a dead lock.  It
2605// verifies that the action is not performed inside the critical
2606// section.
2607TEST(SynchronizationTest, CanCallMockMethodInAction) {
2608  MockA a;
2609  MockC c;
2610  ON_CALL(a, DoA(_))
2611      .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2612                                                    &MockC::NonVoidMethod)));
2613  EXPECT_CALL(a, DoA(1));
2614  EXPECT_CALL(a, DoA(1))
2615      .WillOnce(Invoke(&a, &MockA::DoA))
2616      .RetiresOnSaturation();
2617  EXPECT_CALL(c, NonVoidMethod());
2618
2619  a.DoA(1);
2620  // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2621  // which will in turn match the first EXPECT_CALL() and trigger a call to
2622  // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2623  // EXPECT_CALL() did not specify an action.
2624}
2625
2626}  // namespace
2627
2628// Allows the user to define his own main and then invoke gmock_main
2629// from it. This might be necessary on some platforms which require
2630// specific setup and teardown.
2631#if GMOCK_RENAME_MAIN
2632int gmock_main(int argc, char **argv) {
2633#else
2634int main(int argc, char **argv) {
2635#endif  // GMOCK_RENAME_MAIN
2636  testing::InitGoogleMock(&argc, argv);
2637
2638  // Ensures that the tests pass no matter what value of
2639  // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2640  testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2641  testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2642
2643  return RUN_ALL_TESTS();
2644}
trunk/3rdparty/googletest/googlemock/test/gmock_all_test.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for Google C++ Mocking Framework (Google Mock)
33//
34// Some users use a build system that Google Mock doesn't support directly,
35// yet they still want to build and run Google Mock's own tests.  This file
36// includes most such tests, making it easier for these users to maintain
37// their build scripts (they just need to build this file, even though the
38// below list of actual *_test.cc files might change).
39#include "test/gmock-actions_test.cc"
40#include "test/gmock-cardinalities_test.cc"
41#include "test/gmock-generated-actions_test.cc"
42#include "test/gmock-generated-function-mockers_test.cc"
43#include "test/gmock-generated-internal-utils_test.cc"
44#include "test/gmock-generated-matchers_test.cc"
45#include "test/gmock-internal-utils_test.cc"
46#include "test/gmock-matchers_test.cc"
47#include "test/gmock-more-actions_test.cc"
48#include "test/gmock-nice-strict_test.cc"
49#include "test/gmock-port_test.cc"
50#include "test/gmock-spec-builders_test.cc"
51#include "test/gmock_test.cc"
trunk/3rdparty/googletest/googlemock/test/gmock_ex_test.cc
r0r249096
1// Copyright 2013, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Tests Google Mock's functionality that depends on exceptions.
33
34#include "gmock/gmock.h"
35#include "gtest/gtest.h"
36
37namespace {
38
39using testing::HasSubstr;
40using testing::internal::GoogleTestFailureException;
41
42// A type that cannot be default constructed.
43class NonDefaultConstructible {
44 public:
45  explicit NonDefaultConstructible(int /* dummy */) {}
46};
47
48class MockFoo {
49 public:
50  // A mock method that returns a user-defined type.  Google Mock
51  // doesn't know what the default value for this type is.
52  MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible());
53};
54
55#if GTEST_HAS_EXCEPTIONS
56
57TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
58  MockFoo mock;
59  try {
60    // No expectation is set on this method, so Google Mock must
61    // return the default value.  However, since Google Mock knows
62    // nothing about the return type, it doesn't know what to return,
63    // and has to throw (when exceptions are enabled) or abort
64    // (otherwise).
65    mock.GetNonDefaultConstructible();
66    FAIL() << "GetNonDefaultConstructible()'s return type has no default "
67           << "value, so Google Mock should have thrown.";
68  } catch (const GoogleTestFailureException& /* unused */) {
69    FAIL() << "Google Test does not try to catch an exception of type "
70           << "GoogleTestFailureException, which is used for reporting "
71           << "a failure to other testing frameworks.  Google Mock should "
72           << "not throw a GoogleTestFailureException as it will kill the "
73           << "entire test program instead of just the current TEST.";
74  } catch (const std::exception& ex) {
75    EXPECT_THAT(ex.what(), HasSubstr("has no default value"));
76  }
77}
78
79#endif
80
81}  // unnamed namespace
trunk/3rdparty/googletest/googlemock/test/gmock_leak_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Tests that leaked mock objects can be caught be Google Mock."""
33
34__author__ = 'wan@google.com (Zhanyong Wan)'
35
36
37import gmock_test_utils
38
39
40PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')
41TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']
42TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*']
43TEST_MULTIPLE_LEAKS = [PROGRAM_PATH, '--gtest_filter=*MultipleLeaked*']
44
45environ = gmock_test_utils.environ
46SetEnvVar = gmock_test_utils.SetEnvVar
47
48# Tests in this file run a Google-Test-based test program and expect it
49# to terminate prematurely.  Therefore they are incompatible with
50# the premature-exit-file protocol by design.  Unset the
51# premature-exit filepath to prevent Google Test from creating
52# the file.
53SetEnvVar(gmock_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
54
55
56class GMockLeakTest(gmock_test_utils.TestCase):
57
58  def testCatchesLeakedMockByDefault(self):
59    self.assertNotEqual(
60        0,
61        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL,
62                                    env=environ).exit_code)
63    self.assertNotEqual(
64        0,
65        gmock_test_utils.Subprocess(TEST_WITH_ON_CALL,
66                                    env=environ).exit_code)
67
68  def testDoesNotCatchLeakedMockWhenDisabled(self):
69    self.assertEquals(
70        0,
71        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
72                                    ['--gmock_catch_leaked_mocks=0'],
73                                    env=environ).exit_code)
74    self.assertEquals(
75        0,
76        gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
77                                    ['--gmock_catch_leaked_mocks=0'],
78                                    env=environ).exit_code)
79
80  def testCatchesLeakedMockWhenEnabled(self):
81    self.assertNotEqual(
82        0,
83        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
84                                    ['--gmock_catch_leaked_mocks'],
85                                    env=environ).exit_code)
86    self.assertNotEqual(
87        0,
88        gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
89                                    ['--gmock_catch_leaked_mocks'],
90                                    env=environ).exit_code)
91
92  def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):
93    self.assertNotEqual(
94        0,
95        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
96                                    ['--gmock_catch_leaked_mocks=1'],
97                                    env=environ).exit_code)
98
99  def testCatchesMultipleLeakedMocks(self):
100    self.assertNotEqual(
101        0,
102        gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS +
103                                    ['--gmock_catch_leaked_mocks'],
104                                    env=environ).exit_code)
105
106
107if __name__ == '__main__':
108  gmock_test_utils.Main()
trunk/3rdparty/googletest/googlemock/test/gmock_leak_test_.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This program is for verifying that a leaked mock object can be
35// caught by Google Mock's leak detector.
36
37#include "gmock/gmock.h"
38
39namespace {
40
41using ::testing::Return;
42
43class FooInterface {
44 public:
45  virtual ~FooInterface() {}
46  virtual void DoThis() = 0;
47};
48
49class MockFoo : public FooInterface {
50 public:
51  MockFoo() {}
52
53  MOCK_METHOD0(DoThis, void());
54
55 private:
56  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
57};
58
59TEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) {
60  MockFoo* foo = new MockFoo;
61
62  EXPECT_CALL(*foo, DoThis());
63  foo->DoThis();
64
65  // In order to test the leak detector, we deliberately leak foo.
66
67  // Makes sure Google Mock's leak detector can change the exit code
68  // to 1 even when the code is already exiting with 0.
69  exit(0);
70}
71
72TEST(LeakTest, LeakedMockWithOnCallCausesFailureWhenLeakCheckingIsEnabled) {
73  MockFoo* foo = new MockFoo;
74
75  ON_CALL(*foo, DoThis()).WillByDefault(Return());
76
77  // In order to test the leak detector, we deliberately leak foo.
78
79  // Makes sure Google Mock's leak detector can change the exit code
80  // to 1 even when the code is already exiting with 0.
81  exit(0);
82}
83
84TEST(LeakTest, CatchesMultipleLeakedMockObjects) {
85  MockFoo* foo1 = new MockFoo;
86  MockFoo* foo2 = new MockFoo;
87
88  ON_CALL(*foo1, DoThis()).WillByDefault(Return());
89  EXPECT_CALL(*foo2, DoThis());
90  foo2->DoThis();
91
92  // In order to test the leak detector, we deliberately leak foo1 and
93  // foo2.
94
95  // Makes sure Google Mock's leak detector can change the exit code
96  // to 1 even when the code is already exiting with 0.
97  exit(0);
98}
99
100}  // namespace
trunk/3rdparty/googletest/googlemock/test/gmock_link2_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file is for verifying that various Google Mock constructs do not
35// produce linker errors when instantiated in different translation units.
36// Please see gmock_link_test.h for details.
37
38#define LinkTest LinkTest2
39
40#include  "test/gmock_link_test.h"
trunk/3rdparty/googletest/googlemock/test/gmock_link_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file is for verifying that various Google Mock constructs do not
35// produce linker errors when instantiated in different translation units.
36// Please see gmock_link_test.h for details.
37
38#define LinkTest LinkTest1
39
40#include  "test/gmock_link_test.h"
trunk/3rdparty/googletest/googlemock/test/gmock_link_test.h
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests that:
35// a. A header file defining a mock class can be included in multiple
36//    translation units without causing a link error.
37// b. Actions and matchers can be instantiated with identical template
38//    arguments in different translation units without causing link
39//    errors.
40//    The following constructs are currently tested:
41//    Actions:
42//      Return()
43//      Return(value)
44//      ReturnNull
45//      ReturnRef
46//      Assign
47//      SetArgPointee
48//      SetArrayArgument
49//      SetErrnoAndReturn
50//      Invoke(function)
51//      Invoke(object, method)
52//      InvokeWithoutArgs(function)
53//      InvokeWithoutArgs(object, method)
54//      InvokeArgument
55//      WithArg
56//      WithArgs
57//      WithoutArgs
58//      DoAll
59//      DoDefault
60//      IgnoreResult
61//      Throw
62//      ACTION()-generated
63//      ACTION_P()-generated
64//      ACTION_P2()-generated
65//    Matchers:
66//      _
67//      A
68//      An
69//      Eq
70//      Gt, Lt, Ge, Le, Ne
71//      NotNull
72//      Ref
73//      TypedEq
74//      DoubleEq
75//      FloatEq
76//      NanSensitiveDoubleEq
77//      NanSensitiveFloatEq
78//      ContainsRegex
79//      MatchesRegex
80//      EndsWith
81//      HasSubstr
82//      StartsWith
83//      StrCaseEq
84//      StrCaseNe
85//      StrEq
86//      StrNe
87//      ElementsAre
88//      ElementsAreArray
89//      ContainerEq
90//      Field
91//      Property
92//      ResultOf(function)
93//      Pointee
94//      Truly(predicate)
95//      AllOf
96//      AnyOf
97//      Not
98//      MatcherCast<T>
99//
100//  Please note: this test does not verify the functioning of these
101//  constructs, only that the programs using them will link successfully.
102//
103// Implementation note:
104// This test requires identical definitions of Interface and Mock to be
105// included in different translation units.  We achieve this by writing
106// them in this header and #including it in gmock_link_test.cc and
107// gmock_link2_test.cc.  Because the symbols generated by the compiler for
108// those constructs must be identical in both translation units,
109// definitions of Interface and Mock tests MUST be kept in the SAME
110// NON-ANONYMOUS namespace in this file.  The test fixture class LinkTest
111// is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in
112// gmock_link2_test.cc to avoid producing linker errors.
113
114#ifndef GMOCK_TEST_GMOCK_LINK_TEST_H_
115#define GMOCK_TEST_GMOCK_LINK_TEST_H_
116
117#include "gmock/gmock.h"
118
119#if !GTEST_OS_WINDOWS_MOBILE
120# include <errno.h>
121#endif
122
123#include "gmock/internal/gmock-port.h"
124#include "gtest/gtest.h"
125#include <iostream>
126#include <vector>
127
128using testing::_;
129using testing::A;
130using testing::AllOf;
131using testing::AnyOf;
132using testing::Assign;
133using testing::ContainerEq;
134using testing::DoAll;
135using testing::DoDefault;
136using testing::DoubleEq;
137using testing::ElementsAre;
138using testing::ElementsAreArray;
139using testing::EndsWith;
140using testing::Eq;
141using testing::Field;
142using testing::FloatEq;
143using testing::Ge;
144using testing::Gt;
145using testing::HasSubstr;
146using testing::IgnoreResult;
147using testing::Invoke;
148using testing::InvokeArgument;
149using testing::InvokeWithoutArgs;
150using testing::IsNull;
151using testing::Le;
152using testing::Lt;
153using testing::Matcher;
154using testing::MatcherCast;
155using testing::NanSensitiveDoubleEq;
156using testing::NanSensitiveFloatEq;
157using testing::Ne;
158using testing::Not;
159using testing::NotNull;
160using testing::Pointee;
161using testing::Property;
162using testing::Ref;
163using testing::ResultOf;
164using testing::Return;
165using testing::ReturnNull;
166using testing::ReturnRef;
167using testing::SetArgPointee;
168using testing::SetArrayArgument;
169using testing::StartsWith;
170using testing::StrCaseEq;
171using testing::StrCaseNe;
172using testing::StrEq;
173using testing::StrNe;
174using testing::Truly;
175using testing::TypedEq;
176using testing::WithArg;
177using testing::WithArgs;
178using testing::WithoutArgs;
179
180#if !GTEST_OS_WINDOWS_MOBILE
181using testing::SetErrnoAndReturn;
182#endif
183
184#if GTEST_HAS_EXCEPTIONS
185using testing::Throw;
186#endif
187
188using testing::ContainsRegex;
189using testing::MatchesRegex;
190
191class Interface {
192 public:
193  virtual ~Interface() {}
194  virtual void VoidFromString(char* str) = 0;
195  virtual char* StringFromString(char* str) = 0;
196  virtual int IntFromString(char* str) = 0;
197  virtual int& IntRefFromString(char* str) = 0;
198  virtual void VoidFromFunc(void(*func)(char* str)) = 0;
199  virtual void VoidFromIntRef(int& n) = 0;  // NOLINT
200  virtual void VoidFromFloat(float n) = 0;
201  virtual void VoidFromDouble(double n) = 0;
202  virtual void VoidFromVector(const std::vector<int>& v) = 0;
203};
204
205class Mock: public Interface {
206 public:
207  Mock() {}
208
209  MOCK_METHOD1(VoidFromString, void(char* str));
210  MOCK_METHOD1(StringFromString, char*(char* str));
211  MOCK_METHOD1(IntFromString, int(char* str));
212  MOCK_METHOD1(IntRefFromString, int&(char* str));
213  MOCK_METHOD1(VoidFromFunc, void(void(*func)(char* str)));
214  MOCK_METHOD1(VoidFromIntRef, void(int& n));  // NOLINT
215  MOCK_METHOD1(VoidFromFloat, void(float n));
216  MOCK_METHOD1(VoidFromDouble, void(double n));
217  MOCK_METHOD1(VoidFromVector, void(const std::vector<int>& v));
218
219 private:
220  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock);
221};
222
223class InvokeHelper {
224 public:
225  static void StaticVoidFromVoid() {}
226  void VoidFromVoid() {}
227  static void StaticVoidFromString(char* /* str */) {}
228  void VoidFromString(char* /* str */) {}
229  static int StaticIntFromString(char* /* str */) { return 1; }
230  static bool StaticBoolFromString(const char* /* str */) { return true; }
231};
232
233class FieldHelper {
234 public:
235  explicit FieldHelper(int a_field) : field_(a_field) {}
236  int field() const { return field_; }
237  int field_;  // NOLINT -- need external access to field_ to test
238               //           the Field matcher.
239};
240
241// Tests the linkage of the ReturnVoid action.
242TEST(LinkTest, TestReturnVoid) {
243  Mock mock;
244
245  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return());
246  mock.VoidFromString(NULL);
247}
248
249// Tests the linkage of the Return action.
250TEST(LinkTest, TestReturn) {
251  Mock mock;
252  char ch = 'x';
253
254  EXPECT_CALL(mock, StringFromString(_)).WillOnce(Return(&ch));
255  mock.StringFromString(NULL);
256}
257
258// Tests the linkage of the ReturnNull action.
259TEST(LinkTest, TestReturnNull) {
260  Mock mock;
261
262  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return());
263  mock.VoidFromString(NULL);
264}
265
266// Tests the linkage of the ReturnRef action.
267TEST(LinkTest, TestReturnRef) {
268  Mock mock;
269  int n = 42;
270
271  EXPECT_CALL(mock, IntRefFromString(_)).WillOnce(ReturnRef(n));
272  mock.IntRefFromString(NULL);
273}
274
275// Tests the linkage of the Assign action.
276TEST(LinkTest, TestAssign) {
277  Mock mock;
278  char ch = 'x';
279
280  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Assign(&ch, 'y'));
281  mock.VoidFromString(NULL);
282}
283
284// Tests the linkage of the SetArgPointee action.
285TEST(LinkTest, TestSetArgPointee) {
286  Mock mock;
287  char ch = 'x';
288
289  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArgPointee<0>('y'));
290  mock.VoidFromString(&ch);
291}
292
293// Tests the linkage of the SetArrayArgument action.
294TEST(LinkTest, TestSetArrayArgument) {
295  Mock mock;
296  char ch = 'x';
297  char ch2 = 'y';
298
299  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2,
300                                                                    &ch2 + 1));
301  mock.VoidFromString(&ch);
302}
303
304#if !GTEST_OS_WINDOWS_MOBILE
305
306// Tests the linkage of the SetErrnoAndReturn action.
307TEST(LinkTest, TestSetErrnoAndReturn) {
308  Mock mock;
309
310  int saved_errno = errno;
311  EXPECT_CALL(mock, IntFromString(_)).WillOnce(SetErrnoAndReturn(1, -1));
312  mock.IntFromString(NULL);
313  errno = saved_errno;
314}
315
316#endif  // !GTEST_OS_WINDOWS_MOBILE
317
318// Tests the linkage of the Invoke(function) and Invoke(object, method) actions.
319TEST(LinkTest, TestInvoke) {
320  Mock mock;
321  InvokeHelper test_invoke_helper;
322
323  EXPECT_CALL(mock, VoidFromString(_))
324      .WillOnce(Invoke(&InvokeHelper::StaticVoidFromString))
325      .WillOnce(Invoke(&test_invoke_helper, &InvokeHelper::VoidFromString));
326  mock.VoidFromString(NULL);
327  mock.VoidFromString(NULL);
328}
329
330// Tests the linkage of the InvokeWithoutArgs action.
331TEST(LinkTest, TestInvokeWithoutArgs) {
332  Mock mock;
333  InvokeHelper test_invoke_helper;
334
335  EXPECT_CALL(mock, VoidFromString(_))
336      .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid))
337      .WillOnce(InvokeWithoutArgs(&test_invoke_helper,
338                                  &InvokeHelper::VoidFromVoid));
339  mock.VoidFromString(NULL);
340  mock.VoidFromString(NULL);
341}
342
343// Tests the linkage of the InvokeArgument action.
344TEST(LinkTest, TestInvokeArgument) {
345  Mock mock;
346  char ch = 'x';
347
348  EXPECT_CALL(mock, VoidFromFunc(_)).WillOnce(InvokeArgument<0>(&ch));
349  mock.VoidFromFunc(InvokeHelper::StaticVoidFromString);
350}
351
352// Tests the linkage of the WithArg action.
353TEST(LinkTest, TestWithArg) {
354  Mock mock;
355
356  EXPECT_CALL(mock, VoidFromString(_))
357      .WillOnce(WithArg<0>(Invoke(&InvokeHelper::StaticVoidFromString)));
358  mock.VoidFromString(NULL);
359}
360
361// Tests the linkage of the WithArgs action.
362TEST(LinkTest, TestWithArgs) {
363  Mock mock;
364
365  EXPECT_CALL(mock, VoidFromString(_))
366      .WillOnce(WithArgs<0>(Invoke(&InvokeHelper::StaticVoidFromString)));
367  mock.VoidFromString(NULL);
368}
369
370// Tests the linkage of the WithoutArgs action.
371TEST(LinkTest, TestWithoutArgs) {
372  Mock mock;
373
374  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(WithoutArgs(Return()));
375  mock.VoidFromString(NULL);
376}
377
378// Tests the linkage of the DoAll action.
379TEST(LinkTest, TestDoAll) {
380  Mock mock;
381  char ch = 'x';
382
383  EXPECT_CALL(mock, VoidFromString(_))
384      .WillOnce(DoAll(SetArgPointee<0>('y'), Return()));
385  mock.VoidFromString(&ch);
386}
387
388// Tests the linkage of the DoDefault action.
389TEST(LinkTest, TestDoDefault) {
390  Mock mock;
391  char ch = 'x';
392
393  ON_CALL(mock, VoidFromString(_)).WillByDefault(Return());
394  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(DoDefault());
395  mock.VoidFromString(&ch);
396}
397
398// Tests the linkage of the IgnoreResult action.
399TEST(LinkTest, TestIgnoreResult) {
400  Mock mock;
401
402  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(IgnoreResult(Return(42)));
403  mock.VoidFromString(NULL);
404}
405
406#if GTEST_HAS_EXCEPTIONS
407// Tests the linkage of the Throw action.
408TEST(LinkTest, TestThrow) {
409  Mock mock;
410
411  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42));
412  EXPECT_THROW(mock.VoidFromString(NULL), int);
413}
414#endif  // GTEST_HAS_EXCEPTIONS
415
416// The ACTION*() macros trigger warning C4100 (unreferenced formal
417// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
418// the macro definition, as the warnings are generated when the macro
419// is expanded and macro expansion cannot contain #pragma.  Therefore
420// we suppress them here.
421#ifdef _MSC_VER
422# pragma warning(push)
423# pragma warning(disable:4100)
424#endif
425
426// Tests the linkage of actions created using ACTION macro.
427namespace {
428ACTION(Return1) { return 1; }
429}
430
431TEST(LinkTest, TestActionMacro) {
432  Mock mock;
433
434  EXPECT_CALL(mock, IntFromString(_)).WillOnce(Return1());
435  mock.IntFromString(NULL);
436}
437
438// Tests the linkage of actions created using ACTION_P macro.
439namespace {
440ACTION_P(ReturnArgument, ret_value) { return ret_value; }
441}
442
443TEST(LinkTest, TestActionPMacro) {
444  Mock mock;
445
446  EXPECT_CALL(mock, IntFromString(_)).WillOnce(ReturnArgument(42));
447  mock.IntFromString(NULL);
448}
449
450// Tests the linkage of actions created using ACTION_P2 macro.
451namespace {
452ACTION_P2(ReturnEqualsEitherOf, first, second) {
453  return arg0 == first || arg0 == second;
454}
455}
456
457#ifdef _MSC_VER
458# pragma warning(pop)
459#endif
460
461TEST(LinkTest, TestActionP2Macro) {
462  Mock mock;
463  char ch = 'x';
464
465  EXPECT_CALL(mock, IntFromString(_))
466      .WillOnce(ReturnEqualsEitherOf("one", "two"));
467  mock.IntFromString(&ch);
468}
469
470// Tests the linkage of the "_" matcher.
471TEST(LinkTest, TestMatcherAnything) {
472  Mock mock;
473
474  ON_CALL(mock, VoidFromString(_)).WillByDefault(Return());
475}
476
477// Tests the linkage of the A matcher.
478TEST(LinkTest, TestMatcherA) {
479  Mock mock;
480
481  ON_CALL(mock, VoidFromString(A<char*>())).WillByDefault(Return());
482}
483
484// Tests the linkage of the Eq and the "bare value" matcher.
485TEST(LinkTest, TestMatchersEq) {
486  Mock mock;
487  const char* p = "x";
488
489  ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return());
490  ON_CALL(mock, VoidFromString(const_cast<char*>("y")))
491      .WillByDefault(Return());
492}
493
494// Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers.
495TEST(LinkTest, TestMatchersRelations) {
496  Mock mock;
497
498  ON_CALL(mock, VoidFromFloat(Lt(1.0f))).WillByDefault(Return());
499  ON_CALL(mock, VoidFromFloat(Gt(1.0f))).WillByDefault(Return());
500  ON_CALL(mock, VoidFromFloat(Le(1.0f))).WillByDefault(Return());
501  ON_CALL(mock, VoidFromFloat(Ge(1.0f))).WillByDefault(Return());
502  ON_CALL(mock, VoidFromFloat(Ne(1.0f))).WillByDefault(Return());
503}
504
505// Tests the linkage of the NotNull matcher.
506TEST(LinkTest, TestMatcherNotNull) {
507  Mock mock;
508
509  ON_CALL(mock, VoidFromString(NotNull())).WillByDefault(Return());
510}
511
512// Tests the linkage of the IsNull matcher.
513TEST(LinkTest, TestMatcherIsNull) {
514  Mock mock;
515
516  ON_CALL(mock, VoidFromString(IsNull())).WillByDefault(Return());
517}
518
519// Tests the linkage of the Ref matcher.
520TEST(LinkTest, TestMatcherRef) {
521  Mock mock;
522  int a = 0;
523
524  ON_CALL(mock, VoidFromIntRef(Ref(a))).WillByDefault(Return());
525}
526
527// Tests the linkage of the TypedEq matcher.
528TEST(LinkTest, TestMatcherTypedEq) {
529  Mock mock;
530  long a = 0;
531
532  ON_CALL(mock, VoidFromIntRef(TypedEq<int&>(a))).WillByDefault(Return());
533}
534
535// Tests the linkage of the FloatEq, DoubleEq, NanSensitiveFloatEq and
536// NanSensitiveDoubleEq matchers.
537TEST(LinkTest, TestMatchersFloatingPoint) {
538  Mock mock;
539  float a = 0;
540
541  ON_CALL(mock, VoidFromFloat(FloatEq(a))).WillByDefault(Return());
542  ON_CALL(mock, VoidFromDouble(DoubleEq(a))).WillByDefault(Return());
543  ON_CALL(mock, VoidFromFloat(NanSensitiveFloatEq(a))).WillByDefault(Return());
544  ON_CALL(mock, VoidFromDouble(NanSensitiveDoubleEq(a)))
545      .WillByDefault(Return());
546}
547
548// Tests the linkage of the ContainsRegex matcher.
549TEST(LinkTest, TestMatcherContainsRegex) {
550  Mock mock;
551
552  ON_CALL(mock, VoidFromString(ContainsRegex(".*"))).WillByDefault(Return());
553}
554
555// Tests the linkage of the MatchesRegex matcher.
556TEST(LinkTest, TestMatcherMatchesRegex) {
557  Mock mock;
558
559  ON_CALL(mock, VoidFromString(MatchesRegex(".*"))).WillByDefault(Return());
560}
561
562// Tests the linkage of the StartsWith, EndsWith, and HasSubstr matchers.
563TEST(LinkTest, TestMatchersSubstrings) {
564  Mock mock;
565
566  ON_CALL(mock, VoidFromString(StartsWith("a"))).WillByDefault(Return());
567  ON_CALL(mock, VoidFromString(EndsWith("c"))).WillByDefault(Return());
568  ON_CALL(mock, VoidFromString(HasSubstr("b"))).WillByDefault(Return());
569}
570
571// Tests the linkage of the StrEq, StrNe, StrCaseEq, and StrCaseNe matchers.
572TEST(LinkTest, TestMatchersStringEquality) {
573  Mock mock;
574  ON_CALL(mock, VoidFromString(StrEq("a"))).WillByDefault(Return());
575  ON_CALL(mock, VoidFromString(StrNe("a"))).WillByDefault(Return());
576  ON_CALL(mock, VoidFromString(StrCaseEq("a"))).WillByDefault(Return());
577  ON_CALL(mock, VoidFromString(StrCaseNe("a"))).WillByDefault(Return());
578}
579
580// Tests the linkage of the ElementsAre matcher.
581TEST(LinkTest, TestMatcherElementsAre) {
582  Mock mock;
583
584  ON_CALL(mock, VoidFromVector(ElementsAre('a', _))).WillByDefault(Return());
585}
586
587// Tests the linkage of the ElementsAreArray matcher.
588TEST(LinkTest, TestMatcherElementsAreArray) {
589  Mock mock;
590  char arr[] = { 'a', 'b' };
591
592  ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return());
593}
594
595// Tests the linkage of the ContainerEq matcher.
596TEST(LinkTest, TestMatcherContainerEq) {
597  Mock mock;
598  std::vector<int> v;
599
600  ON_CALL(mock, VoidFromVector(ContainerEq(v))).WillByDefault(Return());
601}
602
603// Tests the linkage of the Field matcher.
604TEST(LinkTest, TestMatcherField) {
605  FieldHelper helper(0);
606
607  Matcher<const FieldHelper&> m = Field(&FieldHelper::field_, Eq(0));
608  EXPECT_TRUE(m.Matches(helper));
609
610  Matcher<const FieldHelper*> m2 = Field(&FieldHelper::field_, Eq(0));
611  EXPECT_TRUE(m2.Matches(&helper));
612}
613
614// Tests the linkage of the Property matcher.
615TEST(LinkTest, TestMatcherProperty) {
616  FieldHelper helper(0);
617
618  Matcher<const FieldHelper&> m = Property(&FieldHelper::field, Eq(0));
619  EXPECT_TRUE(m.Matches(helper));
620
621  Matcher<const FieldHelper*> m2 = Property(&FieldHelper::field, Eq(0));
622  EXPECT_TRUE(m2.Matches(&helper));
623}
624
625// Tests the linkage of the ResultOf matcher.
626TEST(LinkTest, TestMatcherResultOf) {
627  Matcher<char*> m = ResultOf(&InvokeHelper::StaticIntFromString, Eq(1));
628  EXPECT_TRUE(m.Matches(NULL));
629}
630
631// Tests the linkage of the ResultOf matcher.
632TEST(LinkTest, TestMatcherPointee) {
633  int n = 1;
634
635  Matcher<int*> m = Pointee(Eq(1));
636  EXPECT_TRUE(m.Matches(&n));
637}
638
639// Tests the linkage of the Truly matcher.
640TEST(LinkTest, TestMatcherTruly) {
641  Matcher<const char*> m = Truly(&InvokeHelper::StaticBoolFromString);
642  EXPECT_TRUE(m.Matches(NULL));
643}
644
645// Tests the linkage of the AllOf matcher.
646TEST(LinkTest, TestMatcherAllOf) {
647  Matcher<int> m = AllOf(_, Eq(1));
648  EXPECT_TRUE(m.Matches(1));
649}
650
651// Tests the linkage of the AnyOf matcher.
652TEST(LinkTest, TestMatcherAnyOf) {
653  Matcher<int> m = AnyOf(_, Eq(1));
654  EXPECT_TRUE(m.Matches(1));
655}
656
657// Tests the linkage of the Not matcher.
658TEST(LinkTest, TestMatcherNot) {
659  Matcher<int> m = Not(_);
660  EXPECT_FALSE(m.Matches(1));
661}
662
663// Tests the linkage of the MatcherCast<T>() function.
664TEST(LinkTest, TestMatcherCast) {
665  Matcher<const char*> m = MatcherCast<const char*>(_);
666  EXPECT_TRUE(m.Matches(NULL));
667}
668
669#endif  // GMOCK_TEST_GMOCK_LINK_TEST_H_
trunk/3rdparty/googletest/googlemock/test/gmock_output_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Tests the text output of Google C++ Mocking Framework.
33
34SYNOPSIS
35       gmock_output_test.py --build_dir=BUILD/DIR --gengolden
36         # where BUILD/DIR contains the built gmock_output_test_ file.
37       gmock_output_test.py --gengolden
38       gmock_output_test.py
39"""
40
41__author__ = 'wan@google.com (Zhanyong Wan)'
42
43import os
44import re
45import sys
46
47import gmock_test_utils
48
49
50# The flag for generating the golden file
51GENGOLDEN_FLAG = '--gengolden'
52
53PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_output_test_')
54COMMAND = [PROGRAM_PATH, '--gtest_stack_trace_depth=0', '--gtest_print_time=0']
55GOLDEN_NAME = 'gmock_output_test_golden.txt'
56GOLDEN_PATH = os.path.join(gmock_test_utils.GetSourceDir(), GOLDEN_NAME)
57
58
59def ToUnixLineEnding(s):
60  """Changes all Windows/Mac line endings in s to UNIX line endings."""
61
62  return s.replace('\r\n', '\n').replace('\r', '\n')
63
64
65def RemoveReportHeaderAndFooter(output):
66  """Removes Google Test result report's header and footer from the output."""
67
68  output = re.sub(r'.*gtest_main.*\n', '', output)
69  output = re.sub(r'\[.*\d+ tests.*\n', '', output)
70  output = re.sub(r'\[.* test environment .*\n', '', output)
71  output = re.sub(r'\[=+\] \d+ tests .* ran.*', '', output)
72  output = re.sub(r'.* FAILED TESTS\n', '', output)
73  return output
74
75
76def RemoveLocations(output):
77  """Removes all file location info from a Google Test program's output.
78
79  Args:
80       output:  the output of a Google Test program.
81
82  Returns:
83       output with all file location info (in the form of
84       'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
85       'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
86       'FILE:#: '.
87  """
88
89  return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\:', 'FILE:#:', output)
90
91
92def NormalizeErrorMarker(output):
93  """Normalizes the error marker, which is different on Windows vs on Linux."""
94
95  return re.sub(r' error: ', ' Failure\n', output)
96
97
98def RemoveMemoryAddresses(output):
99  """Removes memory addresses from the test output."""
100
101  return re.sub(r'@\w+', '@0x#', output)
102
103
104def RemoveTestNamesOfLeakedMocks(output):
105  """Removes the test names of leaked mock objects from the test output."""
106
107  return re.sub(r'\(used in test .+\) ', '', output)
108
109
110def GetLeakyTests(output):
111  """Returns a list of test names that leak mock objects."""
112
113  # findall() returns a list of all matches of the regex in output.
114  # For example, if '(used in test FooTest.Bar)' is in output, the
115  # list will contain 'FooTest.Bar'.
116  return re.findall(r'\(used in test (.+)\)', output)
117
118
119def GetNormalizedOutputAndLeakyTests(output):
120  """Normalizes the output of gmock_output_test_.
121
122  Args:
123    output: The test output.
124
125  Returns:
126    A tuple (the normalized test output, the list of test names that have
127    leaked mocks).
128  """
129
130  output = ToUnixLineEnding(output)
131  output = RemoveReportHeaderAndFooter(output)
132  output = NormalizeErrorMarker(output)
133  output = RemoveLocations(output)
134  output = RemoveMemoryAddresses(output)
135  return (RemoveTestNamesOfLeakedMocks(output), GetLeakyTests(output))
136
137
138def GetShellCommandOutput(cmd):
139  """Runs a command in a sub-process, and returns its STDOUT in a string."""
140
141  return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output
142
143
144def GetNormalizedCommandOutputAndLeakyTests(cmd):
145  """Runs a command and returns its normalized output and a list of leaky tests.
146
147  Args:
148    cmd:  the shell command.
149  """
150
151  # Disables exception pop-ups on Windows.
152  os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'
153  return GetNormalizedOutputAndLeakyTests(GetShellCommandOutput(cmd))
154
155
156class GMockOutputTest(gmock_test_utils.TestCase):
157  def testOutput(self):
158    (output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
159    golden_file = open(GOLDEN_PATH, 'rb')
160    golden = golden_file.read()
161    golden_file.close()
162
163    # The normalized output should match the golden file.
164    self.assertEquals(golden, output)
165
166    # The raw output should contain 2 leaked mock object errors for
167    # test GMockOutputTest.CatchesLeakedMocks.
168    self.assertEquals(['GMockOutputTest.CatchesLeakedMocks',
169                       'GMockOutputTest.CatchesLeakedMocks'],
170                      leaky_tests)
171
172
173if __name__ == '__main__':
174  if sys.argv[1:] == [GENGOLDEN_FLAG]:
175    (output, _) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
176    golden_file = open(GOLDEN_PATH, 'wb')
177    golden_file.write(output)
178    golden_file.close()
179  else:
180    gmock_test_utils.Main()
trunk/3rdparty/googletest/googlemock/test/gmock_output_test_.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Tests Google Mock's output in various scenarios.  This ensures that
33// Google Mock's messages are readable and useful.
34
35#include "gmock/gmock.h"
36
37#include <stdio.h>
38#include <string>
39
40#include "gtest/gtest.h"
41
42using testing::_;
43using testing::AnyNumber;
44using testing::Ge;
45using testing::InSequence;
46using testing::NaggyMock;
47using testing::Ref;
48using testing::Return;
49using testing::Sequence;
50
51class MockFoo {
52 public:
53  MockFoo() {}
54
55  MOCK_METHOD3(Bar, char(const std::string& s, int i, double x));
56  MOCK_METHOD2(Bar2, bool(int x, int y));
57  MOCK_METHOD2(Bar3, void(int x, int y));
58
59 private:
60  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
61};
62
63class GMockOutputTest : public testing::Test {
64 protected:
65  NaggyMock<MockFoo> foo_;
66};
67
68TEST_F(GMockOutputTest, ExpectedCall) {
69  testing::GMOCK_FLAG(verbose) = "info";
70
71  EXPECT_CALL(foo_, Bar2(0, _));
72  foo_.Bar2(0, 0);  // Expected call
73
74  testing::GMOCK_FLAG(verbose) = "warning";
75}
76
77TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) {
78  testing::GMOCK_FLAG(verbose) = "info";
79
80  EXPECT_CALL(foo_, Bar3(0, _));
81  foo_.Bar3(0, 0);  // Expected call
82
83  testing::GMOCK_FLAG(verbose) = "warning";
84}
85
86TEST_F(GMockOutputTest, ExplicitActionsRunOut) {
87  EXPECT_CALL(foo_, Bar2(_, _))
88      .Times(2)
89      .WillOnce(Return(false));
90  foo_.Bar2(2, 2);
91  foo_.Bar2(1, 1);  // Explicit actions in EXPECT_CALL run out.
92}
93
94TEST_F(GMockOutputTest, UnexpectedCall) {
95  EXPECT_CALL(foo_, Bar2(0, _));
96
97  foo_.Bar2(1, 0);  // Unexpected call
98  foo_.Bar2(0, 0);  // Expected call
99}
100
101TEST_F(GMockOutputTest, UnexpectedCallToVoidFunction) {
102  EXPECT_CALL(foo_, Bar3(0, _));
103
104  foo_.Bar3(1, 0);  // Unexpected call
105  foo_.Bar3(0, 0);  // Expected call
106}
107
108TEST_F(GMockOutputTest, ExcessiveCall) {
109  EXPECT_CALL(foo_, Bar2(0, _));
110
111  foo_.Bar2(0, 0);  // Expected call
112  foo_.Bar2(0, 1);  // Excessive call
113}
114
115TEST_F(GMockOutputTest, ExcessiveCallToVoidFunction) {
116  EXPECT_CALL(foo_, Bar3(0, _));
117
118  foo_.Bar3(0, 0);  // Expected call
119  foo_.Bar3(0, 1);  // Excessive call
120}
121
122TEST_F(GMockOutputTest, UninterestingCall) {
123  foo_.Bar2(0, 1);  // Uninteresting call
124}
125
126TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) {
127  foo_.Bar3(0, 1);  // Uninteresting call
128}
129
130TEST_F(GMockOutputTest, RetiredExpectation) {
131  EXPECT_CALL(foo_, Bar2(_, _))
132      .RetiresOnSaturation();
133  EXPECT_CALL(foo_, Bar2(0, 0));
134
135  foo_.Bar2(1, 1);
136  foo_.Bar2(1, 1);  // Matches a retired expectation
137  foo_.Bar2(0, 0);
138}
139
140TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) {
141  {
142    InSequence s;
143    EXPECT_CALL(foo_, Bar(_, 0, _));
144    EXPECT_CALL(foo_, Bar2(0, 0));
145    EXPECT_CALL(foo_, Bar2(1, _));
146  }
147
148  foo_.Bar2(1, 0);  // Has one immediate unsatisfied pre-requisite
149  foo_.Bar("Hi", 0, 0);
150  foo_.Bar2(0, 0);
151  foo_.Bar2(1, 0);
152}
153
154TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) {
155  Sequence s1, s2;
156
157  EXPECT_CALL(foo_, Bar(_, 0, _))
158      .InSequence(s1);
159  EXPECT_CALL(foo_, Bar2(0, 0))
160      .InSequence(s2);
161  EXPECT_CALL(foo_, Bar2(1, _))
162      .InSequence(s1, s2);
163
164  foo_.Bar2(1, 0);  // Has two immediate unsatisfied pre-requisites
165  foo_.Bar("Hi", 0, 0);
166  foo_.Bar2(0, 0);
167  foo_.Bar2(1, 0);
168}
169
170TEST_F(GMockOutputTest, UnsatisfiedWith) {
171  EXPECT_CALL(foo_, Bar2(_, _)).With(Ge());
172}
173
174TEST_F(GMockOutputTest, UnsatisfiedExpectation) {
175  EXPECT_CALL(foo_, Bar(_, _, _));
176  EXPECT_CALL(foo_, Bar2(0, _))
177      .Times(2);
178
179  foo_.Bar2(0, 1);
180}
181
182TEST_F(GMockOutputTest, MismatchArguments) {
183  const std::string s = "Hi";
184  EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)));
185
186  foo_.Bar("Ho", 0, -0.1);  // Mismatch arguments
187  foo_.Bar(s, 0, 0);
188}
189
190TEST_F(GMockOutputTest, MismatchWith) {
191  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
192      .With(Ge());
193
194  foo_.Bar2(2, 3);  // Mismatch With()
195  foo_.Bar2(2, 1);
196}
197
198TEST_F(GMockOutputTest, MismatchArgumentsAndWith) {
199  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
200      .With(Ge());
201
202  foo_.Bar2(1, 3);  // Mismatch arguments and mismatch With()
203  foo_.Bar2(2, 1);
204}
205
206TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
207  ON_CALL(foo_, Bar2(_, _))
208      .WillByDefault(Return(true));   // Default action #1
209  ON_CALL(foo_, Bar2(1, _))
210      .WillByDefault(Return(false));  // Default action #2
211
212  EXPECT_CALL(foo_, Bar2(2, 2));
213  foo_.Bar2(1, 0);  // Unexpected call, takes default action #2.
214  foo_.Bar2(0, 0);  // Unexpected call, takes default action #1.
215  foo_.Bar2(2, 2);  // Expected call.
216}
217
218TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
219  ON_CALL(foo_, Bar2(_, _))
220      .WillByDefault(Return(true));   // Default action #1
221  ON_CALL(foo_, Bar2(1, _))
222      .WillByDefault(Return(false));  // Default action #2
223
224  EXPECT_CALL(foo_, Bar2(2, 2));
225  EXPECT_CALL(foo_, Bar2(1, 1));
226
227  foo_.Bar2(2, 2);  // Expected call.
228  foo_.Bar2(2, 2);  // Excessive call, takes default action #1.
229  foo_.Bar2(1, 1);  // Expected call.
230  foo_.Bar2(1, 1);  // Excessive call, takes default action #2.
231}
232
233TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) {
234  ON_CALL(foo_, Bar2(_, _))
235      .WillByDefault(Return(true));   // Default action #1
236  ON_CALL(foo_, Bar2(1, _))
237      .WillByDefault(Return(false));  // Default action #2
238
239  foo_.Bar2(2, 2);  // Uninteresting call, takes default action #1.
240  foo_.Bar2(1, 1);  // Uninteresting call, takes default action #2.
241}
242
243TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) {
244  ON_CALL(foo_, Bar2(_, _))
245      .WillByDefault(Return(true));   // Default action #1
246
247  EXPECT_CALL(foo_, Bar2(_, _))
248      .Times(2)
249      .WillOnce(Return(false));
250  foo_.Bar2(2, 2);
251  foo_.Bar2(1, 1);  // Explicit actions in EXPECT_CALL run out.
252}
253
254TEST_F(GMockOutputTest, CatchesLeakedMocks) {
255  MockFoo* foo1 = new MockFoo;
256  MockFoo* foo2 = new MockFoo;
257
258  // Invokes ON_CALL on foo1.
259  ON_CALL(*foo1, Bar(_, _, _)).WillByDefault(Return('a'));
260
261  // Invokes EXPECT_CALL on foo2.
262  EXPECT_CALL(*foo2, Bar2(_, _));
263  EXPECT_CALL(*foo2, Bar2(1, _));
264  EXPECT_CALL(*foo2, Bar3(_, _)).Times(AnyNumber());
265  foo2->Bar2(2, 1);
266  foo2->Bar2(1, 1);
267
268  // Both foo1 and foo2 are deliberately leaked.
269}
270
271void TestCatchesLeakedMocksInAdHocTests() {
272  MockFoo* foo = new MockFoo;
273
274  // Invokes EXPECT_CALL on foo.
275  EXPECT_CALL(*foo, Bar2(_, _));
276  foo->Bar2(2, 1);
277
278  // foo is deliberately leaked.
279}
280
281int main(int argc, char **argv) {
282  testing::InitGoogleMock(&argc, argv);
283
284  // Ensures that the tests pass no matter what value of
285  // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
286  testing::GMOCK_FLAG(catch_leaked_mocks) = true;
287  testing::GMOCK_FLAG(verbose) = "warning";
288
289  TestCatchesLeakedMocksInAdHocTests();
290  return RUN_ALL_TESTS();
291}
trunk/3rdparty/googletest/googlemock/test/gmock_output_test_golden.txt
r0r249096
1[ RUN      ] GMockOutputTest.ExpectedCall
2
3FILE:#: EXPECT_CALL(foo_, Bar2(0, _)) invoked
4Stack trace:
5
6FILE:#: Mock function call matches EXPECT_CALL(foo_, Bar2(0, _))...
7    Function call: Bar2(0, 0)
8          Returns: false
9Stack trace:
10[       OK ] GMockOutputTest.ExpectedCall
11[ RUN      ] GMockOutputTest.ExpectedCallToVoidFunction
12
13FILE:#: EXPECT_CALL(foo_, Bar3(0, _)) invoked
14Stack trace:
15
16FILE:#: Mock function call matches EXPECT_CALL(foo_, Bar3(0, _))...
17    Function call: Bar3(0, 0)
18Stack trace:
19[       OK ] GMockOutputTest.ExpectedCallToVoidFunction
20[ RUN      ] GMockOutputTest.ExplicitActionsRunOut
21
22GMOCK WARNING:
23FILE:#: Too few actions specified in EXPECT_CALL(foo_, Bar2(_, _))...
24Expected to be called twice, but has only 1 WillOnce().
25GMOCK WARNING:
26FILE:#: Actions ran out in EXPECT_CALL(foo_, Bar2(_, _))...
27Called 2 times, but only 1 WillOnce() is specified - returning default value.
28Stack trace:
29[       OK ] GMockOutputTest.ExplicitActionsRunOut
30[ RUN      ] GMockOutputTest.UnexpectedCall
31unknown file: Failure
32
33Unexpected mock function call - returning default value.
34    Function call: Bar2(1, 0)
35          Returns: false
36Google Mock tried the following 1 expectation, but it didn't match:
37
38FILE:#: EXPECT_CALL(foo_, Bar2(0, _))...
39  Expected arg #0: is equal to 0
40           Actual: 1
41         Expected: to be called once
42           Actual: never called - unsatisfied and active
43[  FAILED  ] GMockOutputTest.UnexpectedCall
44[ RUN      ] GMockOutputTest.UnexpectedCallToVoidFunction
45unknown file: Failure
46
47Unexpected mock function call - returning directly.
48    Function call: Bar3(1, 0)
49Google Mock tried the following 1 expectation, but it didn't match:
50
51FILE:#: EXPECT_CALL(foo_, Bar3(0, _))...
52  Expected arg #0: is equal to 0
53           Actual: 1
54         Expected: to be called once
55           Actual: never called - unsatisfied and active
56[  FAILED  ] GMockOutputTest.UnexpectedCallToVoidFunction
57[ RUN      ] GMockOutputTest.ExcessiveCall
58FILE:#: Failure
59Mock function called more times than expected - returning default value.
60    Function call: Bar2(0, 1)
61          Returns: false
62         Expected: to be called once
63           Actual: called twice - over-saturated and active
64[  FAILED  ] GMockOutputTest.ExcessiveCall
65[ RUN      ] GMockOutputTest.ExcessiveCallToVoidFunction
66FILE:#: Failure
67Mock function called more times than expected - returning directly.
68    Function call: Bar3(0, 1)
69         Expected: to be called once
70           Actual: called twice - over-saturated and active
71[  FAILED  ] GMockOutputTest.ExcessiveCallToVoidFunction
72[ RUN      ] GMockOutputTest.UninterestingCall
73
74GMOCK WARNING:
75Uninteresting mock function call - returning default value.
76    Function call: Bar2(0, 1)
77          Returns: false
78NOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See http://code.google.com/p/googlemock/wiki/CookBook#Knowing_When_to_Expect for details.
79[       OK ] GMockOutputTest.UninterestingCall
80[ RUN      ] GMockOutputTest.UninterestingCallToVoidFunction
81
82GMOCK WARNING:
83Uninteresting mock function call - returning directly.
84    Function call: Bar3(0, 1)
85NOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See http://code.google.com/p/googlemock/wiki/CookBook#Knowing_When_to_Expect for details.
86[       OK ] GMockOutputTest.UninterestingCallToVoidFunction
87[ RUN      ] GMockOutputTest.RetiredExpectation
88unknown file: Failure
89
90Unexpected mock function call - returning default value.
91    Function call: Bar2(1, 1)
92          Returns: false
93Google Mock tried the following 2 expectations, but none matched:
94
95FILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(_, _))...
96         Expected: the expectation is active
97           Actual: it is retired
98         Expected: to be called once
99           Actual: called once - saturated and retired
100FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(0, 0))...
101  Expected arg #0: is equal to 0
102           Actual: 1
103  Expected arg #1: is equal to 0
104           Actual: 1
105         Expected: to be called once
106           Actual: never called - unsatisfied and active
107[  FAILED  ] GMockOutputTest.RetiredExpectation
108[ RUN      ] GMockOutputTest.UnsatisfiedPrerequisite
109unknown file: Failure
110
111Unexpected mock function call - returning default value.
112    Function call: Bar2(1, 0)
113          Returns: false
114Google Mock tried the following 2 expectations, but none matched:
115
116FILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(0, 0))...
117  Expected arg #0: is equal to 0
118           Actual: 1
119         Expected: to be called once
120           Actual: never called - unsatisfied and active
121FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(1, _))...
122         Expected: all pre-requisites are satisfied
123           Actual: the following immediate pre-requisites are not satisfied:
124FILE:#: pre-requisite #0
125                   (end of pre-requisites)
126         Expected: to be called once
127           Actual: never called - unsatisfied and active
128[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisite
129[ RUN      ] GMockOutputTest.UnsatisfiedPrerequisites
130unknown file: Failure
131
132Unexpected mock function call - returning default value.
133    Function call: Bar2(1, 0)
134          Returns: false
135Google Mock tried the following 2 expectations, but none matched:
136
137FILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(0, 0))...
138  Expected arg #0: is equal to 0
139           Actual: 1
140         Expected: to be called once
141           Actual: never called - unsatisfied and active
142FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(1, _))...
143         Expected: all pre-requisites are satisfied
144           Actual: the following immediate pre-requisites are not satisfied:
145FILE:#: pre-requisite #0
146FILE:#: pre-requisite #1
147                   (end of pre-requisites)
148         Expected: to be called once
149           Actual: never called - unsatisfied and active
150[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisites
151[ RUN      ] GMockOutputTest.UnsatisfiedWith
152FILE:#: Failure
153Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))...
154    Expected args: are a pair where the first >= the second
155         Expected: to be called once
156           Actual: never called - unsatisfied and active
157[  FAILED  ] GMockOutputTest.UnsatisfiedWith
158[ RUN      ] GMockOutputTest.UnsatisfiedExpectation
159FILE:#: Failure
160Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(0, _))...
161         Expected: to be called twice
162           Actual: called once - unsatisfied and active
163FILE:#: Failure
164Actual function call count doesn't match EXPECT_CALL(foo_, Bar(_, _, _))...
165         Expected: to be called once
166           Actual: never called - unsatisfied and active
167[  FAILED  ] GMockOutputTest.UnsatisfiedExpectation
168[ RUN      ] GMockOutputTest.MismatchArguments
169unknown file: Failure
170
171Unexpected mock function call - returning default value.
172    Function call: Bar(@0x# "Ho", 0, -0.1)
173          Returns: '\0'
174Google Mock tried the following 1 expectation, but it didn't match:
175
176FILE:#: EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)))...
177  Expected arg #0: references the variable @0x# "Hi"
178           Actual: "Ho", which is located @0x#
179  Expected arg #2: is >= 0
180           Actual: -0.1
181         Expected: to be called once
182           Actual: never called - unsatisfied and active
183[  FAILED  ] GMockOutputTest.MismatchArguments
184[ RUN      ] GMockOutputTest.MismatchWith
185unknown file: Failure
186
187Unexpected mock function call - returning default value.
188    Function call: Bar2(2, 3)
189          Returns: false
190Google Mock tried the following 1 expectation, but it didn't match:
191
192FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
193    Expected args: are a pair where the first >= the second
194           Actual: don't match
195         Expected: to be called once
196           Actual: never called - unsatisfied and active
197[  FAILED  ] GMockOutputTest.MismatchWith
198[ RUN      ] GMockOutputTest.MismatchArgumentsAndWith
199unknown file: Failure
200
201Unexpected mock function call - returning default value.
202    Function call: Bar2(1, 3)
203          Returns: false
204Google Mock tried the following 1 expectation, but it didn't match:
205
206FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
207  Expected arg #0: is >= 2
208           Actual: 1
209    Expected args: are a pair where the first >= the second
210           Actual: don't match
211         Expected: to be called once
212           Actual: never called - unsatisfied and active
213[  FAILED  ] GMockOutputTest.MismatchArgumentsAndWith
214[ RUN      ] GMockOutputTest.UnexpectedCallWithDefaultAction
215unknown file: Failure
216
217Unexpected mock function call - taking default action specified at:
218FILE:#:
219    Function call: Bar2(1, 0)
220          Returns: false
221Google Mock tried the following 1 expectation, but it didn't match:
222
223FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
224  Expected arg #0: is equal to 2
225           Actual: 1
226  Expected arg #1: is equal to 2
227           Actual: 0
228         Expected: to be called once
229           Actual: never called - unsatisfied and active
230unknown file: Failure
231
232Unexpected mock function call - taking default action specified at:
233FILE:#:
234    Function call: Bar2(0, 0)
235          Returns: true
236Google Mock tried the following 1 expectation, but it didn't match:
237
238FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
239  Expected arg #0: is equal to 2
240           Actual: 0
241  Expected arg #1: is equal to 2
242           Actual: 0
243         Expected: to be called once
244           Actual: never called - unsatisfied and active
245[  FAILED  ] GMockOutputTest.UnexpectedCallWithDefaultAction
246[ RUN      ] GMockOutputTest.ExcessiveCallWithDefaultAction
247FILE:#: Failure
248Mock function called more times than expected - taking default action specified at:
249FILE:#:
250    Function call: Bar2(2, 2)
251          Returns: true
252         Expected: to be called once
253           Actual: called twice - over-saturated and active
254FILE:#: Failure
255Mock function called more times than expected - taking default action specified at:
256FILE:#:
257    Function call: Bar2(1, 1)
258          Returns: false
259         Expected: to be called once
260           Actual: called twice - over-saturated and active
261[  FAILED  ] GMockOutputTest.ExcessiveCallWithDefaultAction
262[ RUN      ] GMockOutputTest.UninterestingCallWithDefaultAction
263
264GMOCK WARNING:
265Uninteresting mock function call - taking default action specified at:
266FILE:#:
267    Function call: Bar2(2, 2)
268          Returns: true
269NOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See http://code.google.com/p/googlemock/wiki/CookBook#Knowing_When_to_Expect for details.
270
271GMOCK WARNING:
272Uninteresting mock function call - taking default action specified at:
273FILE:#:
274    Function call: Bar2(1, 1)
275          Returns: false
276NOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See http://code.google.com/p/googlemock/wiki/CookBook#Knowing_When_to_Expect for details.
277[       OK ] GMockOutputTest.UninterestingCallWithDefaultAction
278[ RUN      ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
279
280GMOCK WARNING:
281FILE:#: Too few actions specified in EXPECT_CALL(foo_, Bar2(_, _))...
282Expected to be called twice, but has only 1 WillOnce().
283GMOCK WARNING:
284FILE:#: Actions ran out in EXPECT_CALL(foo_, Bar2(_, _))...
285Called 2 times, but only 1 WillOnce() is specified - taking default action specified at:
286FILE:#:
287Stack trace:
288[       OK ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
289[ RUN      ] GMockOutputTest.CatchesLeakedMocks
290[       OK ] GMockOutputTest.CatchesLeakedMocks
291[  FAILED  ] GMockOutputTest.UnexpectedCall
292[  FAILED  ] GMockOutputTest.UnexpectedCallToVoidFunction
293[  FAILED  ] GMockOutputTest.ExcessiveCall
294[  FAILED  ] GMockOutputTest.ExcessiveCallToVoidFunction
295[  FAILED  ] GMockOutputTest.RetiredExpectation
296[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisite
297[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisites
298[  FAILED  ] GMockOutputTest.UnsatisfiedWith
299[  FAILED  ] GMockOutputTest.UnsatisfiedExpectation
300[  FAILED  ] GMockOutputTest.MismatchArguments
301[  FAILED  ] GMockOutputTest.MismatchWith
302[  FAILED  ] GMockOutputTest.MismatchArgumentsAndWith
303[  FAILED  ] GMockOutputTest.UnexpectedCallWithDefaultAction
304[  FAILED  ] GMockOutputTest.ExcessiveCallWithDefaultAction
305
306
307FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
308FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
309FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
310ERROR: 3 leaked mock objects found at program exit.
trunk/3rdparty/googletest/googlemock/test/gmock_stress_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Tests that Google Mock constructs can be used in a large number of
33// threads concurrently.
34
35#include "gmock/gmock.h"
36#include "gtest/gtest.h"
37
38namespace testing {
39namespace {
40
41// From <gtest/internal/gtest-port.h>.
42using ::testing::internal::ThreadWithParam;
43
44// The maximum number of test threads (not including helper threads)
45// to create.
46const int kMaxTestThreads = 50;
47
48// How many times to repeat a task in a test thread.
49const int kRepeat = 50;
50
51class MockFoo {
52 public:
53  MOCK_METHOD1(Bar, int(int n));  // NOLINT
54  MOCK_METHOD2(Baz, char(const char* s1, const internal::string& s2));  // NOLINT
55};
56
57// Helper for waiting for the given thread to finish and then deleting it.
58template <typename T>
59void JoinAndDelete(ThreadWithParam<T>* t) {
60  t->Join();
61  delete t;
62}
63
64using internal::linked_ptr;
65
66// Helper classes for testing using linked_ptr concurrently.
67
68class Base {
69 public:
70  explicit Base(int a_x) : x_(a_x) {}
71  virtual ~Base() {}
72  int x() const { return x_; }
73 private:
74  int x_;
75};
76
77class Derived1 : public Base {
78 public:
79  Derived1(int a_x, int a_y) : Base(a_x), y_(a_y) {}
80  int y() const { return y_; }
81 private:
82  int y_;
83};
84
85class Derived2 : public Base {
86 public:
87  Derived2(int a_x, int a_z) : Base(a_x), z_(a_z) {}
88  int z() const { return z_; }
89 private:
90  int z_;
91};
92
93linked_ptr<Derived1> pointer1(new Derived1(1, 2));
94linked_ptr<Derived2> pointer2(new Derived2(3, 4));
95
96struct Dummy {};
97
98// Tests that we can copy from a linked_ptr and read it concurrently.
99void TestConcurrentCopyAndReadLinkedPtr(Dummy /* dummy */) {
100  // Reads pointer1 and pointer2 while they are being copied from in
101  // another thread.
102  EXPECT_EQ(1, pointer1->x());
103  EXPECT_EQ(2, pointer1->y());
104  EXPECT_EQ(3, pointer2->x());
105  EXPECT_EQ(4, pointer2->z());
106
107  // Copies from pointer1.
108  linked_ptr<Derived1> p1(pointer1);
109  EXPECT_EQ(1, p1->x());
110  EXPECT_EQ(2, p1->y());
111
112  // Assigns from pointer2 where the LHS was empty.
113  linked_ptr<Base> p2;
114  p2 = pointer1;
115  EXPECT_EQ(1, p2->x());
116
117  // Assigns from pointer2 where the LHS was not empty.
118  p2 = pointer2;
119  EXPECT_EQ(3, p2->x());
120}
121
122const linked_ptr<Derived1> p0(new Derived1(1, 2));
123
124// Tests that we can concurrently modify two linked_ptrs that point to
125// the same object.
126void TestConcurrentWriteToEqualLinkedPtr(Dummy /* dummy */) {
127  // p1 and p2 point to the same, shared thing.  One thread resets p1.
128  // Another thread assigns to p2.  This will cause the same
129  // underlying "ring" to be updated concurrently.
130  linked_ptr<Derived1> p1(p0);
131  linked_ptr<Derived1> p2(p0);
132
133  EXPECT_EQ(1, p1->x());
134  EXPECT_EQ(2, p1->y());
135
136  EXPECT_EQ(1, p2->x());
137  EXPECT_EQ(2, p2->y());
138
139  p1.reset();
140  p2 = p0;
141
142  EXPECT_EQ(1, p2->x());
143  EXPECT_EQ(2, p2->y());
144}
145
146// Tests that different mock objects can be used in their respective
147// threads.  This should generate no Google Test failure.
148void TestConcurrentMockObjects(Dummy /* dummy */) {
149  // Creates a mock and does some typical operations on it.
150  MockFoo foo;
151  ON_CALL(foo, Bar(_))
152      .WillByDefault(Return(1));
153  ON_CALL(foo, Baz(_, _))
154      .WillByDefault(Return('b'));
155  ON_CALL(foo, Baz(_, "you"))
156      .WillByDefault(Return('a'));
157
158  EXPECT_CALL(foo, Bar(0))
159      .Times(AtMost(3));
160  EXPECT_CALL(foo, Baz(_, _));
161  EXPECT_CALL(foo, Baz("hi", "you"))
162      .WillOnce(Return('z'))
163      .WillRepeatedly(DoDefault());
164
165  EXPECT_EQ(1, foo.Bar(0));
166  EXPECT_EQ(1, foo.Bar(0));
167  EXPECT_EQ('z', foo.Baz("hi", "you"));
168  EXPECT_EQ('a', foo.Baz("hi", "you"));
169  EXPECT_EQ('b', foo.Baz("hi", "me"));
170}
171
172// Tests invoking methods of the same mock object in multiple threads.
173
174struct Helper1Param {
175  MockFoo* mock_foo;
176  int* count;
177};
178
179void Helper1(Helper1Param param) {
180  for (int i = 0; i < kRepeat; i++) {
181    const char ch = param.mock_foo->Baz("a", "b");
182    if (ch == 'a') {
183      // It was an expected call.
184      (*param.count)++;
185    } else {
186      // It was an excessive call.
187      EXPECT_EQ('\0', ch);
188    }
189
190    // An unexpected call.
191    EXPECT_EQ('\0', param.mock_foo->Baz("x", "y")) << "Expected failure.";
192
193    // An uninteresting call.
194    EXPECT_EQ(1, param.mock_foo->Bar(5));
195  }
196}
197
198// This should generate 3*kRepeat + 1 failures in total.
199void TestConcurrentCallsOnSameObject(Dummy /* dummy */) {
200  MockFoo foo;
201
202  ON_CALL(foo, Bar(_))
203      .WillByDefault(Return(1));
204  EXPECT_CALL(foo, Baz(_, "b"))
205      .Times(kRepeat)
206      .WillRepeatedly(Return('a'));
207  EXPECT_CALL(foo, Baz(_, "c"));  // Expected to be unsatisfied.
208
209  // This chunk of code should generate kRepeat failures about
210  // excessive calls, and 2*kRepeat failures about unexpected calls.
211  int count1 = 0;
212  const Helper1Param param = { &foo, &count1 };
213  ThreadWithParam<Helper1Param>* const t =
214      new ThreadWithParam<Helper1Param>(Helper1, param, NULL);
215
216  int count2 = 0;
217  const Helper1Param param2 = { &foo, &count2 };
218  Helper1(param2);
219  JoinAndDelete(t);
220
221  EXPECT_EQ(kRepeat, count1 + count2);
222
223  // foo's destructor should generate one failure about unsatisfied
224  // expectation.
225}
226
227// Tests using the same mock object in multiple threads when the
228// expectations are partially ordered.
229
230void Helper2(MockFoo* foo) {
231  for (int i = 0; i < kRepeat; i++) {
232    foo->Bar(2);
233    foo->Bar(3);
234  }
235}
236
237// This should generate no Google Test failures.
238void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
239  MockFoo foo;
240  Sequence s1, s2;
241
242  {
243    InSequence dummy;
244    EXPECT_CALL(foo, Bar(0));
245    EXPECT_CALL(foo, Bar(1))
246        .InSequence(s1, s2);
247  }
248
249  EXPECT_CALL(foo, Bar(2))
250      .Times(2*kRepeat)
251      .InSequence(s1)
252      .RetiresOnSaturation();
253  EXPECT_CALL(foo, Bar(3))
254      .Times(2*kRepeat)
255      .InSequence(s2);
256
257  {
258    InSequence dummy;
259    EXPECT_CALL(foo, Bar(2))
260        .InSequence(s1, s2);
261    EXPECT_CALL(foo, Bar(4));
262  }
263
264  foo.Bar(0);
265  foo.Bar(1);
266
267  ThreadWithParam<MockFoo*>* const t =
268      new ThreadWithParam<MockFoo*>(Helper2, &foo, NULL);
269  Helper2(&foo);
270  JoinAndDelete(t);
271
272  foo.Bar(2);
273  foo.Bar(4);
274}
275
276// Tests using Google Mock constructs in many threads concurrently.
277TEST(StressTest, CanUseGMockWithThreads) {
278  void (*test_routines[])(Dummy dummy) = {
279    &TestConcurrentCopyAndReadLinkedPtr,
280    &TestConcurrentWriteToEqualLinkedPtr,
281    &TestConcurrentMockObjects,
282    &TestConcurrentCallsOnSameObject,
283    &TestPartiallyOrderedExpectationsWithThreads,
284  };
285
286  const int kRoutines = sizeof(test_routines)/sizeof(test_routines[0]);
287  const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;
288  const int kTestThreads = kCopiesOfEachRoutine * kRoutines;
289  ThreadWithParam<Dummy>* threads[kTestThreads] = {};
290  for (int i = 0; i < kTestThreads; i++) {
291    // Creates a thread to run the test function.
292    threads[i] =
293        new ThreadWithParam<Dummy>(test_routines[i % kRoutines], Dummy(), NULL);
294    GTEST_LOG_(INFO) << "Thread #" << i << " running . . .";
295  }
296
297  // At this point, we have many threads running.
298  for (int i = 0; i < kTestThreads; i++) {
299    JoinAndDelete(threads[i]);
300  }
301
302  // Ensures that the correct number of failures have been reported.
303  const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
304  const TestResult& result = *info->result();
305  const int kExpectedFailures = (3*kRepeat + 1)*kCopiesOfEachRoutine;
306  GTEST_CHECK_(kExpectedFailures == result.total_part_count())
307      << "Expected " << kExpectedFailures << " failures, but got "
308      << result.total_part_count();
309}
310
311}  // namespace
312}  // namespace testing
313
314int main(int argc, char **argv) {
315  testing::InitGoogleMock(&argc, argv);
316
317  const int exit_code = RUN_ALL_TESTS();  // Expected to fail.
318  GTEST_CHECK_(exit_code != 0) << "RUN_ALL_TESTS() did not fail as expected";
319
320  printf("\nPASS\n");
321  return 0;
322}
trunk/3rdparty/googletest/googlemock/test/gmock_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests code in gmock.cc.
35
36#include "gmock/gmock.h"
37
38#include <string>
39#include "gtest/gtest.h"
40#include "gtest/internal/custom/gtest.h"
41
42#if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
43
44using testing::GMOCK_FLAG(verbose);
45using testing::InitGoogleMock;
46
47// Verifies that calling InitGoogleMock() on argv results in new_argv,
48// and the gmock_verbose flag's value is set to expected_gmock_verbose.
49template <typename Char, int M, int N>
50void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
51                        const ::std::string& expected_gmock_verbose) {
52  const ::std::string old_verbose = GMOCK_FLAG(verbose);
53
54  int argc = M;
55  InitGoogleMock(&argc, const_cast<Char**>(argv));
56  ASSERT_EQ(N, argc) << "The new argv has wrong number of elements.";
57
58  for (int i = 0; i < N; i++) {
59    EXPECT_STREQ(new_argv[i], argv[i]);
60  }
61
62  EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str());
63  GMOCK_FLAG(verbose) = old_verbose;  // Restores the gmock_verbose flag.
64}
65
66TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
67  const char* argv[] = {
68    NULL
69  };
70
71  const char* new_argv[] = {
72    NULL
73  };
74
75  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
76}
77
78TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
79  const char* argv[] = {
80    "foo.exe",
81    NULL
82  };
83
84  const char* new_argv[] = {
85    "foo.exe",
86    NULL
87  };
88
89  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
90}
91
92TEST(InitGoogleMockTest, ParsesSingleFlag) {
93  const char* argv[] = {
94    "foo.exe",
95    "--gmock_verbose=info",
96    NULL
97  };
98
99  const char* new_argv[] = {
100    "foo.exe",
101    NULL
102  };
103
104  TestInitGoogleMock(argv, new_argv, "info");
105}
106
107TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
108  const char* argv[] = {
109    "foo.exe",
110    "--non_gmock_flag=blah",
111    NULL
112  };
113
114  const char* new_argv[] = {
115    "foo.exe",
116    "--non_gmock_flag=blah",
117    NULL
118  };
119
120  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
121}
122
123TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
124  const char* argv[] = {
125    "foo.exe",
126    "--non_gmock_flag=blah",
127    "--gmock_verbose=error",
128    NULL
129  };
130
131  const char* new_argv[] = {
132    "foo.exe",
133    "--non_gmock_flag=blah",
134    NULL
135  };
136
137  TestInitGoogleMock(argv, new_argv, "error");
138}
139
140TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
141  const wchar_t* argv[] = {
142    NULL
143  };
144
145  const wchar_t* new_argv[] = {
146    NULL
147  };
148
149  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
150}
151
152TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
153  const wchar_t* argv[] = {
154    L"foo.exe",
155    NULL
156  };
157
158  const wchar_t* new_argv[] = {
159    L"foo.exe",
160    NULL
161  };
162
163  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
164}
165
166TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
167  const wchar_t* argv[] = {
168    L"foo.exe",
169    L"--gmock_verbose=info",
170    NULL
171  };
172
173  const wchar_t* new_argv[] = {
174    L"foo.exe",
175    NULL
176  };
177
178  TestInitGoogleMock(argv, new_argv, "info");
179}
180
181TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
182  const wchar_t* argv[] = {
183    L"foo.exe",
184    L"--non_gmock_flag=blah",
185    NULL
186  };
187
188  const wchar_t* new_argv[] = {
189    L"foo.exe",
190    L"--non_gmock_flag=blah",
191    NULL
192  };
193
194  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
195}
196
197TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
198  const wchar_t* argv[] = {
199    L"foo.exe",
200    L"--non_gmock_flag=blah",
201    L"--gmock_verbose=error",
202    NULL
203  };
204
205  const wchar_t* new_argv[] = {
206    L"foo.exe",
207    L"--non_gmock_flag=blah",
208    NULL
209  };
210
211  TestInitGoogleMock(argv, new_argv, "error");
212}
213
214#endif  // !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
215
216// Makes sure Google Mock flags can be accessed in code.
217TEST(FlagTest, IsAccessibleInCode) {
218  bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) &&
219      testing::GMOCK_FLAG(verbose) == "";
220  (void)dummy;  // Avoids the "unused local variable" warning.
221}
trunk/3rdparty/googletest/googlemock/test/gmock_test_utils.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2006, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Unit test utilities for Google C++ Mocking Framework."""
33
34__author__ = 'wan@google.com (Zhanyong Wan)'
35
36import os
37import sys
38
39
40# Determines path to gtest_test_utils and imports it.
41SCRIPT_DIR = os.path.dirname(__file__) or '.'
42
43# isdir resolves symbolic links.
44gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test')
45if os.path.isdir(gtest_tests_util_dir):
46  GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
47else:
48  GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../gtest/test')
49
50sys.path.append(GTEST_TESTS_UTIL_DIR)
51import gtest_test_utils  # pylint: disable-msg=C6204
52
53
54def GetSourceDir():
55  """Returns the absolute path of the directory where the .py files are."""
56
57  return gtest_test_utils.GetSourceDir()
58
59
60def GetTestExecutablePath(executable_name):
61  """Returns the absolute path of the test binary given its name.
62
63  The function will print a message and abort the program if the resulting file
64  doesn't exist.
65
66  Args:
67    executable_name: name of the test binary that the test script runs.
68
69  Returns:
70    The absolute path of the test binary.
71  """
72
73  return gtest_test_utils.GetTestExecutablePath(executable_name)
74
75
76def GetExitStatus(exit_code):
77  """Returns the argument to exit(), or -1 if exit() wasn't called.
78
79  Args:
80    exit_code: the result value of os.system(command).
81  """
82
83  if os.name == 'nt':
84    # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
85    # the argument to exit() directly.
86    return exit_code
87  else:
88    # On Unix, os.WEXITSTATUS() must be used to extract the exit status
89    # from the result of os.system().
90    if os.WIFEXITED(exit_code):
91      return os.WEXITSTATUS(exit_code)
92    else:
93      return -1
94
95
96# Suppresses the "Invalid const name" lint complaint
97# pylint: disable-msg=C6409
98
99# Exposes utilities from gtest_test_utils.
100Subprocess = gtest_test_utils.Subprocess
101TestCase = gtest_test_utils.TestCase
102environ = gtest_test_utils.environ
103SetEnvVar = gtest_test_utils.SetEnvVar
104PREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR
105
106# pylint: enable-msg=C6409
107
108
109def Main():
110  """Runs the unit test."""
111
112  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/CHANGES
r0r249096
1Changes for 1.7.0:
2
3* New feature: death tests are supported on OpenBSD and in iOS
4  simulator now.
5* New feature: Google Test now implements a protocol to allow
6  a test runner to detect that a test program has exited
7  prematurely and report it as a failure (before it would be
8  falsely reported as a success if the exit code is 0).
9* New feature: Test::RecordProperty() can now be used outside of the
10  lifespan of a test method, in which case it will be attributed to
11  the current test case or the test program in the XML report.
12* New feature (potentially breaking): --gtest_list_tests now prints
13  the type parameters and value parameters for each test.
14* Improvement: char pointers and char arrays are now escaped properly
15  in failure messages.
16* Improvement: failure summary in XML reports now includes file and
17  line information.
18* Improvement: the <testsuites> XML element now has a timestamp attribute.
19* Improvement: When --gtest_filter is specified, XML report now doesn't
20  contain information about tests that are filtered out.
21* Fixed the bug where long --gtest_filter flag values are truncated in
22  death tests.
23* Potentially breaking change: RUN_ALL_TESTS() is now implemented as a
24  function instead of a macro in order to work better with Clang.
25* Compatibility fixes with C++ 11 and various platforms.
26* Bug/warning fixes.
27
28Changes for 1.6.0:
29
30* New feature: ADD_FAILURE_AT() for reporting a test failure at the
31  given source location -- useful for writing testing utilities.
32* New feature: the universal value printer is moved from Google Mock
33  to Google Test.
34* New feature: type parameters and value parameters are reported in
35  the XML report now.
36* A gtest_disable_pthreads CMake option.
37* Colored output works in GNU Screen sessions now.
38* Parameters of value-parameterized tests are now printed in the
39  textual output.
40* Failures from ad hoc test assertions run before RUN_ALL_TESTS() are
41  now correctly reported.
42* Arguments of ASSERT_XY and EXPECT_XY no longer need to support << to
43  ostream.
44* More complete handling of exceptions.
45* GTEST_ASSERT_XY can be used instead of ASSERT_XY in case the latter
46  name is already used by another library.
47* --gtest_catch_exceptions is now true by default, allowing a test
48  program to continue after an exception is thrown.
49* Value-parameterized test fixtures can now derive from Test and
50  WithParamInterface<T> separately, easing conversion of legacy tests.
51* Death test messages are clearly marked to make them more
52  distinguishable from other messages.
53* Compatibility fixes for Android, Google Native Client, MinGW, HP UX,
54  PowerPC, Lucid autotools, libCStd, Sun C++, Borland C++ Builder (Code Gear),
55  IBM XL C++ (Visual Age C++), and C++0x.
56* Bug fixes and implementation clean-ups.
57* Potentially incompatible changes: disables the harmful 'make install'
58  command in autotools.
59
60Changes for 1.5.0:
61
62 * New feature: assertions can be safely called in multiple threads
63   where the pthreads library is available.
64 * New feature: predicates used inside EXPECT_TRUE() and friends
65   can now generate custom failure messages.
66 * New feature: Google Test can now be compiled as a DLL.
67 * New feature: fused source files are included.
68 * New feature: prints help when encountering unrecognized Google Test flags.
69 * Experimental feature: CMake build script (requires CMake 2.6.4+).
70 * Experimental feature: the Pump script for meta programming.
71 * double values streamed to an assertion are printed with enough precision
72   to differentiate any two different values.
73 * Google Test now works on Solaris and AIX.
74 * Build and test script improvements.
75 * Bug fixes and implementation clean-ups.
76
77 Potentially breaking changes:
78
79 * Stopped supporting VC++ 7.1 with exceptions disabled.
80 * Dropped support for 'make install'.
81
82Changes for 1.4.0:
83
84 * New feature: the event listener API
85 * New feature: test shuffling
86 * New feature: the XML report format is closer to junitreport and can
87   be parsed by Hudson now.
88 * New feature: when a test runs under Visual Studio, its failures are
89   integrated in the IDE.
90 * New feature: /MD(d) versions of VC++ projects.
91 * New feature: elapsed time for the tests is printed by default.
92 * New feature: comes with a TR1 tuple implementation such that Boost
93   is no longer needed for Combine().
94 * New feature: EXPECT_DEATH_IF_SUPPORTED macro and friends.
95 * New feature: the Xcode project can now produce static gtest
96   libraries in addition to a framework.
97 * Compatibility fixes for Solaris, Cygwin, minGW, Windows Mobile,
98   Symbian, gcc, and C++Builder.
99 * Bug fixes and implementation clean-ups.
100
101Changes for 1.3.0:
102
103 * New feature: death tests on Windows, Cygwin, and Mac.
104 * New feature: ability to use Google Test assertions in other testing
105   frameworks.
106 * New feature: ability to run disabled test via
107   --gtest_also_run_disabled_tests.
108 * New feature: the --help flag for printing the usage.
109 * New feature: access to Google Test flag values in user code.
110 * New feature: a script that packs Google Test into one .h and one
111   .cc file for easy deployment.
112 * New feature: support for distributing test functions to multiple
113   machines (requires support from the test runner).
114 * Bug fixes and implementation clean-ups.
115
116Changes for 1.2.1:
117
118 * Compatibility fixes for Linux IA-64 and IBM z/OS.
119 * Added support for using Boost and other TR1 implementations.
120 * Changes to the build scripts to support upcoming release of Google C++
121   Mocking Framework.
122 * Added Makefile to the distribution package.
123 * Improved build instructions in README.
124
125Changes for 1.2.0:
126
127 * New feature: value-parameterized tests.
128 * New feature: the ASSERT/EXPECT_(NON)FATAL_FAILURE(_ON_ALL_THREADS)
129   macros.
130 * Changed the XML report format to match JUnit/Ant's.
131 * Added tests to the Xcode project.
132 * Added scons/SConscript for building with SCons.
133 * Added src/gtest-all.cc for building Google Test from a single file.
134 * Fixed compatibility with Solaris and z/OS.
135 * Enabled running Python tests on systems with python 2.3 installed,
136   e.g. Mac OS X 10.4.
137 * Bug fixes.
138
139Changes for 1.1.0:
140
141 * New feature: type-parameterized tests.
142 * New feature: exception assertions.
143 * New feature: printing elapsed time of tests.
144 * Improved the robustness of death tests.
145 * Added an Xcode project and samples.
146 * Adjusted the output format on Windows to be understandable by Visual Studio.
147 * Minor bug fixes.
148
149Changes for 1.0.1:
150
151 * Added project files for Visual Studio 7.1.
152 * Fixed issues with compiling on Mac OS X.
153 * Fixed issues with compiling on Cygwin.
154
155Changes for 1.0.0:
156
157 * Initial Open Source release of Google Test
trunk/3rdparty/googletest/googletest/CMakeLists.txt
r0r249096
1########################################################################
2# CMake build script for Google Test.
3#
4# To run the tests for Google Test itself on Linux, use 'make test' or
5# ctest.  You can select which tests to run using 'ctest -R regex'.
6# For more options, run 'ctest --help'.
7
8# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
9# make it prominent in the GUI.
10option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
11
12# When other libraries are using a shared version of runtime libraries,
13# Google Test also has to use one.
14option(
15  gtest_force_shared_crt
16  "Use shared (DLL) run-time lib even when Google Test is built as static lib."
17  OFF)
18
19option(gtest_build_tests "Build all of gtest's own tests." OFF)
20
21option(gtest_build_samples "Build gtest's sample programs." OFF)
22
23option(gtest_disable_pthreads "Disable uses of pthreads in gtest." OFF)
24
25# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().
26include(cmake/hermetic_build.cmake OPTIONAL)
27
28if (COMMAND pre_project_set_up_hermetic_build)
29  pre_project_set_up_hermetic_build()
30endif()
31
32########################################################################
33#
34# Project-wide settings
35
36# Name of the project.
37#
38# CMake files in this project can refer to the root source directory
39# as ${gtest_SOURCE_DIR} and to the root binary directory as
40# ${gtest_BINARY_DIR}.
41# Language "C" is required for find_package(Threads).
42project(gtest CXX C)
43cmake_minimum_required(VERSION 2.6.2)
44
45if (COMMAND set_up_hermetic_build)
46  set_up_hermetic_build()
47endif()
48
49# Define helper functions and macros used by Google Test.
50include(cmake/internal_utils.cmake)
51
52config_compiler_and_linker()  # Defined in internal_utils.cmake.
53
54# Where Google Test's .h files can be found.
55include_directories(
56  ${gtest_SOURCE_DIR}/include
57  ${gtest_SOURCE_DIR})
58
59# Where Google Test's libraries can be found.
60link_directories(${gtest_BINARY_DIR}/src)
61
62# Summary of tuple support for Microsoft Visual Studio:
63# Compiler    version(MS)  version(cmake)  Support
64# ----------  -----------  --------------  -----------------------------
65# <= VS 2010  <= 10        <= 1600         Use Google Tests's own tuple.
66# VS 2012     11           1700            std::tr1::tuple + _VARIADIC_MAX=10
67# VS 2013     12           1800            std::tr1::tuple
68if (MSVC AND MSVC_VERSION EQUAL 1700)
69  add_definitions(/D _VARIADIC_MAX=10)
70endif()
71
72########################################################################
73#
74# Defines the gtest & gtest_main libraries.  User tests should link
75# with one of them.
76
77# Google Test libraries.  We build them using more strict warnings than what
78# are used for other targets, to ensure that gtest can be compiled by a user
79# aggressive about warnings.
80cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
81cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
82target_link_libraries(gtest_main gtest)
83
84########################################################################
85#
86# Samples on how to link user tests with gtest or gtest_main.
87#
88# They are not built by default.  To build them, set the
89# gtest_build_samples option to ON.  You can do it by running ccmake
90# or specifying the -Dgtest_build_samples=ON flag when running cmake.
91
92if (gtest_build_samples)
93  cxx_executable(sample1_unittest samples gtest_main samples/sample1.cc)
94  cxx_executable(sample2_unittest samples gtest_main samples/sample2.cc)
95  cxx_executable(sample3_unittest samples gtest_main)
96  cxx_executable(sample4_unittest samples gtest_main samples/sample4.cc)
97  cxx_executable(sample5_unittest samples gtest_main samples/sample1.cc)
98  cxx_executable(sample6_unittest samples gtest_main)
99  cxx_executable(sample7_unittest samples gtest_main)
100  cxx_executable(sample8_unittest samples gtest_main)
101  cxx_executable(sample9_unittest samples gtest)
102  cxx_executable(sample10_unittest samples gtest)
103endif()
104
105########################################################################
106#
107# Google Test's own tests.
108#
109# You can skip this section if you aren't interested in testing
110# Google Test itself.
111#
112# The tests are not built by default.  To build them, set the
113# gtest_build_tests option to ON.  You can do it by running ccmake
114# or specifying the -Dgtest_build_tests=ON flag when running cmake.
115
116if (gtest_build_tests)
117  # This must be set in the root directory for the tests to be run by
118  # 'make test' or ctest.
119  enable_testing()
120
121  ############################################################
122  # C++ tests built with standard compiler flags.
123
124  cxx_test(gtest-death-test_test gtest_main)
125  cxx_test(gtest_environment_test gtest)
126  cxx_test(gtest-filepath_test gtest_main)
127  cxx_test(gtest-linked_ptr_test gtest_main)
128  cxx_test(gtest-listener_test gtest_main)
129  cxx_test(gtest_main_unittest gtest_main)
130  cxx_test(gtest-message_test gtest_main)
131  cxx_test(gtest_no_test_unittest gtest)
132  cxx_test(gtest-options_test gtest_main)
133  cxx_test(gtest-param-test_test gtest
134    test/gtest-param-test2_test.cc)
135  cxx_test(gtest-port_test gtest_main)
136  cxx_test(gtest_pred_impl_unittest gtest_main)
137  cxx_test(gtest_premature_exit_test gtest
138    test/gtest_premature_exit_test.cc)
139  cxx_test(gtest-printers_test gtest_main)
140  cxx_test(gtest_prod_test gtest_main
141    test/production.cc)
142  cxx_test(gtest_repeat_test gtest)
143  cxx_test(gtest_sole_header_test gtest_main)
144  cxx_test(gtest_stress_test gtest)
145  cxx_test(gtest-test-part_test gtest_main)
146  cxx_test(gtest_throw_on_failure_ex_test gtest)
147  cxx_test(gtest-typed-test_test gtest_main
148    test/gtest-typed-test2_test.cc)
149  cxx_test(gtest_unittest gtest_main)
150  cxx_test(gtest-unittest-api_test gtest)
151
152  ############################################################
153  # C++ tests built with non-standard compiler flags.
154
155  # MSVC 7.1 does not support STL with exceptions disabled.
156  if (NOT MSVC OR MSVC_VERSION GREATER 1310)
157    cxx_library(gtest_no_exception "${cxx_no_exception}"
158      src/gtest-all.cc)
159    cxx_library(gtest_main_no_exception "${cxx_no_exception}"
160      src/gtest-all.cc src/gtest_main.cc)
161  endif()
162  cxx_library(gtest_main_no_rtti "${cxx_no_rtti}"
163    src/gtest-all.cc src/gtest_main.cc)
164
165  cxx_test_with_flags(gtest-death-test_ex_nocatch_test
166    "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0"
167    gtest test/gtest-death-test_ex_test.cc)
168  cxx_test_with_flags(gtest-death-test_ex_catch_test
169    "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1"
170    gtest test/gtest-death-test_ex_test.cc)
171
172  cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}"
173    gtest_main_no_rtti test/gtest_unittest.cc)
174
175  cxx_shared_library(gtest_dll "${cxx_default}"
176    src/gtest-all.cc src/gtest_main.cc)
177
178  cxx_executable_with_flags(gtest_dll_test_ "${cxx_default}"
179    gtest_dll test/gtest_all_test.cc)
180  set_target_properties(gtest_dll_test_
181                        PROPERTIES
182                        COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
183
184  if (NOT MSVC OR MSVC_VERSION LESS 1600)  # 1600 is Visual Studio 2010.
185    # Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that
186    # conflict with our own definitions. Therefore using our own tuple does not
187    # work on those compilers.
188    cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}"
189      src/gtest-all.cc src/gtest_main.cc)
190
191    cxx_test_with_flags(gtest-tuple_test "${cxx_use_own_tuple}"
192      gtest_main_use_own_tuple test/gtest-tuple_test.cc)
193
194    cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}"
195      gtest_main_use_own_tuple
196      test/gtest-param-test_test.cc test/gtest-param-test2_test.cc)
197  endif()
198
199  ############################################################
200  # Python tests.
201
202  cxx_executable(gtest_break_on_failure_unittest_ test gtest)
203  py_test(gtest_break_on_failure_unittest)
204
205  # Visual Studio .NET 2003 does not support STL with exceptions disabled.
206  if (NOT MSVC OR MSVC_VERSION GREATER 1310)  # 1310 is Visual Studio .NET 2003
207    cxx_executable_with_flags(
208      gtest_catch_exceptions_no_ex_test_
209      "${cxx_no_exception}"
210      gtest_main_no_exception
211      test/gtest_catch_exceptions_test_.cc)
212  endif()
213
214  cxx_executable_with_flags(
215    gtest_catch_exceptions_ex_test_
216    "${cxx_exception}"
217    gtest_main
218    test/gtest_catch_exceptions_test_.cc)
219  py_test(gtest_catch_exceptions_test)
220
221  cxx_executable(gtest_color_test_ test gtest)
222  py_test(gtest_color_test)
223
224  cxx_executable(gtest_env_var_test_ test gtest)
225  py_test(gtest_env_var_test)
226
227  cxx_executable(gtest_filter_unittest_ test gtest)
228  py_test(gtest_filter_unittest)
229
230  cxx_executable(gtest_help_test_ test gtest_main)
231  py_test(gtest_help_test)
232
233  cxx_executable(gtest_list_tests_unittest_ test gtest)
234  py_test(gtest_list_tests_unittest)
235
236  cxx_executable(gtest_output_test_ test gtest)
237  py_test(gtest_output_test)
238
239  cxx_executable(gtest_shuffle_test_ test gtest)
240  py_test(gtest_shuffle_test)
241
242  # MSVC 7.1 does not support STL with exceptions disabled.
243  if (NOT MSVC OR MSVC_VERSION GREATER 1310)
244    cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception)
245    set_target_properties(gtest_throw_on_failure_test_
246      PROPERTIES
247      COMPILE_FLAGS "${cxx_no_exception}")
248    py_test(gtest_throw_on_failure_test)
249  endif()
250
251  cxx_executable(gtest_uninitialized_test_ test gtest)
252  py_test(gtest_uninitialized_test)
253
254  cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
255  cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
256  py_test(gtest_xml_outfiles_test)
257
258  cxx_executable(gtest_xml_output_unittest_ test gtest)
259  py_test(gtest_xml_output_unittest)
260endif()
trunk/3rdparty/googletest/googletest/CONTRIBUTORS
r0r249096
1# This file contains a list of people who've made non-trivial
2# contribution to the Google C++ Testing Framework project.  People
3# who commit code to the project are encouraged to add their names
4# here.  Please keep the list sorted by first names.
5
6Ajay Joshi <jaj@google.com>
7Balázs Dán <balazs.dan@gmail.com>
8Bharat Mediratta <bharat@menalto.com>
9Chandler Carruth <chandlerc@google.com>
10Chris Prince <cprince@google.com>
11Chris Taylor <taylorc@google.com>
12Dan Egnor <egnor@google.com>
13Eric Roman <eroman@chromium.org>
14Hady Zalek <hady.zalek@gmail.com>
15Jeffrey Yasskin <jyasskin@google.com>
16Jói Sigurðsson <joi@google.com>
17Keir Mierle <mierle@gmail.com>
18Keith Ray <keith.ray@gmail.com>
19Kenton Varda <kenton@google.com>
20Manuel Klimek <klimek@google.com>
21Markus Heule <markus.heule@gmail.com>
22Mika Raento <mikie@iki.fi>
23Miklós Fazekas <mfazekas@szemafor.com>
24Pasi Valminen <pasi.valminen@gmail.com>
25Patrick Hanna <phanna@google.com>
26Patrick Riley <pfr@google.com>
27Peter Kaminski <piotrk@google.com>
28Preston Jackson <preston.a.jackson@gmail.com>
29Rainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>
30Russ Cox <rsc@google.com>
31Russ Rufer <russ@pentad.com>
32Sean Mcafee <eefacm@gmail.com>
33Sigurður Ásgeirsson <siggi@google.com>
34Tracy Bialik <tracy@pentad.com>
35Vadim Berman <vadimb@google.com>
36Vlad Losev <vladl@google.com>
37Zhanyong Wan <wan@google.com>
trunk/3rdparty/googletest/googletest/LICENSE
r0r249096
1Copyright 2008, Google Inc.
2All rights reserved.
3
4Redistribution and use in source and binary forms, with or without
5modification, are permitted provided that the following conditions are
6met:
7
8    * Redistributions of source code must retain the above copyright
9notice, this list of conditions and the following disclaimer.
10    * Redistributions in binary form must reproduce the above
11copyright notice, this list of conditions and the following disclaimer
12in the documentation and/or other materials provided with the
13distribution.
14    * Neither the name of Google Inc. nor the names of its
15contributors may be used to endorse or promote products derived from
16this software without specific prior written permission.
17
18THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
trunk/3rdparty/googletest/googletest/Makefile.am
r0r249096
1# Automake file
2
3ACLOCAL_AMFLAGS = -I m4
4
5# Nonstandard package files for distribution
6EXTRA_DIST = \
7  CHANGES \
8  CONTRIBUTORS \
9  LICENSE \
10  include/gtest/gtest-param-test.h.pump \
11  include/gtest/internal/gtest-param-util-generated.h.pump \
12  include/gtest/internal/gtest-tuple.h.pump \
13  include/gtest/internal/gtest-type-util.h.pump \
14  make/Makefile \
15  scripts/fuse_gtest_files.py \
16  scripts/gen_gtest_pred_impl.py \
17  scripts/pump.py \
18  scripts/test/Makefile
19
20# gtest source files that we don't compile directly.  They are
21# #included by gtest-all.cc.
22GTEST_SRC = \
23  src/gtest-death-test.cc \
24  src/gtest-filepath.cc \
25  src/gtest-internal-inl.h \
26  src/gtest-port.cc \
27  src/gtest-printers.cc \
28  src/gtest-test-part.cc \
29  src/gtest-typed-test.cc \
30  src/gtest.cc
31
32EXTRA_DIST += $(GTEST_SRC)
33
34# Sample files that we don't compile.
35EXTRA_DIST += \
36  samples/prime_tables.h \
37  samples/sample2_unittest.cc \
38  samples/sample3_unittest.cc \
39  samples/sample4_unittest.cc \
40  samples/sample5_unittest.cc \
41  samples/sample6_unittest.cc \
42  samples/sample7_unittest.cc \
43  samples/sample8_unittest.cc \
44  samples/sample9_unittest.cc
45
46# C++ test files that we don't compile directly.
47EXTRA_DIST += \
48  test/gtest-death-test_ex_test.cc \
49  test/gtest-death-test_test.cc \
50  test/gtest-filepath_test.cc \
51  test/gtest-linked_ptr_test.cc \
52  test/gtest-listener_test.cc \
53  test/gtest-message_test.cc \
54  test/gtest-options_test.cc \
55  test/gtest-param-test2_test.cc \
56  test/gtest-param-test2_test.cc \
57  test/gtest-param-test_test.cc \
58  test/gtest-param-test_test.cc \
59  test/gtest-param-test_test.h \
60  test/gtest-port_test.cc \
61  test/gtest_premature_exit_test.cc \
62  test/gtest-printers_test.cc \
63  test/gtest-test-part_test.cc \
64  test/gtest-tuple_test.cc \
65  test/gtest-typed-test2_test.cc \
66  test/gtest-typed-test_test.cc \
67  test/gtest-typed-test_test.h \
68  test/gtest-unittest-api_test.cc \
69  test/gtest_break_on_failure_unittest_.cc \
70  test/gtest_catch_exceptions_test_.cc \
71  test/gtest_color_test_.cc \
72  test/gtest_env_var_test_.cc \
73  test/gtest_environment_test.cc \
74  test/gtest_filter_unittest_.cc \
75  test/gtest_help_test_.cc \
76  test/gtest_list_tests_unittest_.cc \
77  test/gtest_main_unittest.cc \
78  test/gtest_no_test_unittest.cc \
79  test/gtest_output_test_.cc \
80  test/gtest_pred_impl_unittest.cc \
81  test/gtest_prod_test.cc \
82  test/gtest_repeat_test.cc \
83  test/gtest_shuffle_test_.cc \
84  test/gtest_sole_header_test.cc \
85  test/gtest_stress_test.cc \
86  test/gtest_throw_on_failure_ex_test.cc \
87  test/gtest_throw_on_failure_test_.cc \
88  test/gtest_uninitialized_test_.cc \
89  test/gtest_unittest.cc \
90  test/gtest_unittest.cc \
91  test/gtest_xml_outfile1_test_.cc \
92  test/gtest_xml_outfile2_test_.cc \
93  test/gtest_xml_output_unittest_.cc \
94  test/production.cc \
95  test/production.h
96
97# Python tests that we don't run.
98EXTRA_DIST += \
99  test/gtest_break_on_failure_unittest.py \
100  test/gtest_catch_exceptions_test.py \
101  test/gtest_color_test.py \
102  test/gtest_env_var_test.py \
103  test/gtest_filter_unittest.py \
104  test/gtest_help_test.py \
105  test/gtest_list_tests_unittest.py \
106  test/gtest_output_test.py \
107  test/gtest_output_test_golden_lin.txt \
108  test/gtest_shuffle_test.py \
109  test/gtest_test_utils.py \
110  test/gtest_throw_on_failure_test.py \
111  test/gtest_uninitialized_test.py \
112  test/gtest_xml_outfiles_test.py \
113  test/gtest_xml_output_unittest.py \
114  test/gtest_xml_test_utils.py
115
116# CMake script
117EXTRA_DIST += \
118  CMakeLists.txt \
119  cmake/internal_utils.cmake
120
121# MSVC project files
122EXTRA_DIST += \
123  msvc/gtest-md.sln \
124  msvc/gtest-md.vcproj \
125  msvc/gtest.sln \
126  msvc/gtest.vcproj \
127  msvc/gtest_main-md.vcproj \
128  msvc/gtest_main.vcproj \
129  msvc/gtest_prod_test-md.vcproj \
130  msvc/gtest_prod_test.vcproj \
131  msvc/gtest_unittest-md.vcproj \
132  msvc/gtest_unittest.vcproj
133
134# xcode project files
135EXTRA_DIST += \
136  xcode/Config/DebugProject.xcconfig \
137  xcode/Config/FrameworkTarget.xcconfig \
138  xcode/Config/General.xcconfig \
139  xcode/Config/ReleaseProject.xcconfig \
140  xcode/Config/StaticLibraryTarget.xcconfig \
141  xcode/Config/TestTarget.xcconfig \
142  xcode/Resources/Info.plist \
143  xcode/Scripts/runtests.sh \
144  xcode/Scripts/versiongenerate.py \
145  xcode/gtest.xcodeproj/project.pbxproj
146
147# xcode sample files
148EXTRA_DIST += \
149  xcode/Samples/FrameworkSample/Info.plist \
150  xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj \
151  xcode/Samples/FrameworkSample/runtests.sh \
152  xcode/Samples/FrameworkSample/widget.cc \
153  xcode/Samples/FrameworkSample/widget.h \
154  xcode/Samples/FrameworkSample/widget_test.cc
155
156# C++Builder project files
157EXTRA_DIST += \
158  codegear/gtest.cbproj \
159  codegear/gtest.groupproj \
160  codegear/gtest_all.cc \
161  codegear/gtest_link.cc \
162  codegear/gtest_main.cbproj \
163  codegear/gtest_unittest.cbproj
164
165# Distribute and install M4 macro
166m4datadir = $(datadir)/aclocal
167m4data_DATA = m4/gtest.m4
168EXTRA_DIST += $(m4data_DATA)
169
170# We define the global AM_CPPFLAGS as everything we compile includes from these
171# directories.
172AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/include
173
174# Modifies compiler and linker flags for pthreads compatibility.
175if HAVE_PTHREADS
176  AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1
177  AM_LIBS = @PTHREAD_LIBS@
178else
179  AM_CXXFLAGS = -DGTEST_HAS_PTHREAD=0
180endif
181
182# Build rules for libraries.
183lib_LTLIBRARIES = lib/libgtest.la lib/libgtest_main.la
184
185lib_libgtest_la_SOURCES = src/gtest-all.cc
186
187pkginclude_HEADERS = \
188  include/gtest/gtest-death-test.h \
189  include/gtest/gtest-message.h \
190  include/gtest/gtest-param-test.h \
191  include/gtest/gtest-printers.h \
192  include/gtest/gtest-spi.h \
193  include/gtest/gtest-test-part.h \
194  include/gtest/gtest-typed-test.h \
195  include/gtest/gtest.h \
196  include/gtest/gtest_pred_impl.h \
197  include/gtest/gtest_prod.h
198
199pkginclude_internaldir = $(pkgincludedir)/internal
200pkginclude_internal_HEADERS = \
201  include/gtest/internal/gtest-death-test-internal.h \
202  include/gtest/internal/gtest-filepath.h \
203  include/gtest/internal/gtest-internal.h \
204  include/gtest/internal/gtest-linked_ptr.h \
205  include/gtest/internal/gtest-param-util-generated.h \
206  include/gtest/internal/gtest-param-util.h \
207  include/gtest/internal/gtest-port.h \
208  include/gtest/internal/gtest-string.h \
209  include/gtest/internal/gtest-tuple.h \
210  include/gtest/internal/gtest-type-util.h
211
212lib_libgtest_main_la_SOURCES = src/gtest_main.cc
213lib_libgtest_main_la_LIBADD = lib/libgtest.la
214
215# Bulid rules for samples and tests. Automake's naming for some of
216# these variables isn't terribly obvious, so this is a brief
217# reference:
218#
219# TESTS -- Programs run automatically by "make check"
220# check_PROGRAMS -- Programs built by "make check" but not necessarily run
221
222noinst_LTLIBRARIES = samples/libsamples.la
223
224samples_libsamples_la_SOURCES = \
225  samples/sample1.cc \
226  samples/sample1.h \
227  samples/sample2.cc \
228  samples/sample2.h \
229  samples/sample3-inl.h \
230  samples/sample4.cc \
231  samples/sample4.h
232
233TESTS=
234TESTS_ENVIRONMENT = GTEST_SOURCE_DIR="$(srcdir)/test" \
235                    GTEST_BUILD_DIR="$(top_builddir)/test"
236check_PROGRAMS=
237
238# A simple sample on using gtest.
239TESTS += samples/sample1_unittest
240check_PROGRAMS += samples/sample1_unittest
241samples_sample1_unittest_SOURCES = samples/sample1_unittest.cc
242samples_sample1_unittest_LDADD = lib/libgtest_main.la \
243                                 lib/libgtest.la \
244                                 samples/libsamples.la
245
246# Another sample.  It also verifies that libgtest works.
247TESTS += samples/sample10_unittest
248check_PROGRAMS += samples/sample10_unittest
249samples_sample10_unittest_SOURCES = samples/sample10_unittest.cc
250samples_sample10_unittest_LDADD = lib/libgtest.la
251
252# This tests most constructs of gtest and verifies that libgtest_main
253# and libgtest work.
254TESTS += test/gtest_all_test
255check_PROGRAMS += test/gtest_all_test
256test_gtest_all_test_SOURCES = test/gtest_all_test.cc
257test_gtest_all_test_LDADD = lib/libgtest_main.la \
258                            lib/libgtest.la
259
260# Tests that fused gtest files compile and work.
261FUSED_GTEST_SRC = \
262  fused-src/gtest/gtest-all.cc \
263  fused-src/gtest/gtest.h \
264  fused-src/gtest/gtest_main.cc
265
266if HAVE_PYTHON
267TESTS += test/fused_gtest_test
268check_PROGRAMS += test/fused_gtest_test
269test_fused_gtest_test_SOURCES = $(FUSED_GTEST_SRC) \
270                                samples/sample1.cc samples/sample1_unittest.cc
271test_fused_gtest_test_CPPFLAGS = -I"$(srcdir)/fused-src"
272
273# Build rules for putting fused Google Test files into the distribution
274# package. The user can also create those files by manually running
275# scripts/fuse_gtest_files.py.
276$(test_fused_gtest_test_SOURCES): fused-gtest
277
278fused-gtest: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \
279             $(GTEST_SRC) src/gtest-all.cc src/gtest_main.cc \
280             scripts/fuse_gtest_files.py
281   mkdir -p "$(srcdir)/fused-src"
282   chmod -R u+w "$(srcdir)/fused-src"
283   rm -f "$(srcdir)/fused-src/gtest/gtest-all.cc"
284   rm -f "$(srcdir)/fused-src/gtest/gtest.h"
285   "$(srcdir)/scripts/fuse_gtest_files.py" "$(srcdir)/fused-src"
286   cp -f "$(srcdir)/src/gtest_main.cc" "$(srcdir)/fused-src/gtest/"
287
288maintainer-clean-local:
289   rm -rf "$(srcdir)/fused-src"
290endif
291
292# Death tests may produce core dumps in the build directory. In case
293# this happens, clean them to keep distcleancheck happy.
294CLEANFILES = core
295
296# Disables 'make install' as installing a compiled version of Google
297# Test can lead to undefined behavior due to violation of the
298# One-Definition Rule.
299
300install-exec-local:
301   echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system."
302   false
303
304install-data-local:
305   echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system."
306   false
trunk/3rdparty/googletest/googletest/README.md
r0r249096
1
2### Generic Build Instructions ###
3
4#### Setup ####
5
6To build Google Test and your tests that use it, you need to tell your
7build system where to find its headers and source files.  The exact
8way to do it depends on which build system you use, and is usually
9straightforward.
10
11#### Build ####
12
13Suppose you put Google Test in directory `${GTEST_DIR}`.  To build it,
14create a library build target (or a project as called by Visual Studio
15and Xcode) to compile
16
17    ${GTEST_DIR}/src/gtest-all.cc
18
19with `${GTEST_DIR}/include` in the system header search path and `${GTEST_DIR}`
20in the normal header search path.  Assuming a Linux-like system and gcc,
21something like the following will do:
22
23    g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
24        -pthread -c ${GTEST_DIR}/src/gtest-all.cc
25    ar -rv libgtest.a gtest-all.o
26
27(We need `-pthread` as Google Test uses threads.)
28
29Next, you should compile your test source file with
30`${GTEST_DIR}/include` in the system header search path, and link it
31with gtest and any other necessary libraries:
32
33    g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \
34        -o your_test
35
36As an example, the make/ directory contains a Makefile that you can
37use to build Google Test on systems where GNU make is available
38(e.g. Linux, Mac OS X, and Cygwin).  It doesn't try to build Google
39Test's own tests.  Instead, it just builds the Google Test library and
40a sample test.  You can use it as a starting point for your own build
41script.
42
43If the default settings are correct for your environment, the
44following commands should succeed:
45
46    cd ${GTEST_DIR}/make
47    make
48    ./sample1_unittest
49
50If you see errors, try to tweak the contents of `make/Makefile` to make
51them go away.  There are instructions in `make/Makefile` on how to do
52it.
53
54### Using CMake ###
55
56Google Test comes with a CMake build script (
57[CMakeLists.txt](master/CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for
58cross-platform.). If you don't have CMake installed already, you can
59download it for free from <http://www.cmake.org/>.
60
61CMake works by generating native makefiles or build projects that can
62be used in the compiler environment of your choice.  The typical
63workflow starts with:
64
65    mkdir mybuild       # Create a directory to hold the build output.
66    cd mybuild
67    cmake ${GTEST_DIR}  # Generate native build scripts.
68
69If you want to build Google Test's samples, you should replace the
70last command with
71
72    cmake -Dgtest_build_samples=ON ${GTEST_DIR}
73
74If you are on a \*nix system, you should now see a Makefile in the
75current directory.  Just type 'make' to build gtest.
76
77If you use Windows and have Visual Studio installed, a `gtest.sln` file
78and several `.vcproj` files will be created.  You can then build them
79using Visual Studio.
80
81On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.
82
83### Legacy Build Scripts ###
84
85Before settling on CMake, we have been providing hand-maintained build
86projects/scripts for Visual Studio, Xcode, and Autotools.  While we
87continue to provide them for convenience, they are not actively
88maintained any more.  We highly recommend that you follow the
89instructions in the previous two sections to integrate Google Test
90with your existing build system.
91
92If you still need to use the legacy build scripts, here's how:
93
94The msvc\ folder contains two solutions with Visual C++ projects.
95Open the `gtest.sln` or `gtest-md.sln` file using Visual Studio, and you
96are ready to build Google Test the same way you build any Visual
97Studio project.  Files that have names ending with -md use DLL
98versions of Microsoft runtime libraries (the /MD or the /MDd compiler
99option).  Files without that suffix use static versions of the runtime
100libraries (the /MT or the /MTd option).  Please note that one must use
101the same option to compile both gtest and the test code.  If you use
102Visual Studio 2005 or above, we recommend the -md version as /MD is
103the default for new projects in these versions of Visual Studio.
104
105On Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using
106Xcode.  Build the "gtest" target.  The universal binary framework will
107end up in your selected build directory (selected in the Xcode
108"Preferences..." -> "Building" pane and defaults to xcode/build).
109Alternatively, at the command line, enter:
110
111    xcodebuild
112
113This will build the "Release" configuration of gtest.framework in your
114default build location.  See the "xcodebuild" man page for more
115information about building different configurations and building in
116different locations.
117
118If you wish to use the Google Test Xcode project with Xcode 4.x and
119above, you need to either:
120
121 * update the SDK configuration options in xcode/Config/General.xconfig.
122   Comment options `SDKROOT`, `MACOS_DEPLOYMENT_TARGET`, and `GCC_VERSION`. If
123   you choose this route you lose the ability to target earlier versions
124   of MacOS X.
125 * Install an SDK for an earlier version. This doesn't appear to be
126   supported by Apple, but has been reported to work
127   (http://stackoverflow.com/questions/5378518).
128
129### Tweaking Google Test ###
130
131Google Test can be used in diverse environments.  The default
132configuration may not work (or may not work well) out of the box in
133some environments.  However, you can easily tweak Google Test by
134defining control macros on the compiler command line.  Generally,
135these macros are named like `GTEST_XYZ` and you define them to either 1
136or 0 to enable or disable a certain feature.
137
138We list the most frequently used macros below.  For a complete list,
139see file [include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/include/gtest/internal/gtest-port.h).
140
141### Choosing a TR1 Tuple Library ###
142
143Some Google Test features require the C++ Technical Report 1 (TR1)
144tuple library, which is not yet available with all compilers.  The
145good news is that Google Test implements a subset of TR1 tuple that's
146enough for its own need, and will automatically use this when the
147compiler doesn't provide TR1 tuple.
148
149Usually you don't need to care about which tuple library Google Test
150uses.  However, if your project already uses TR1 tuple, you need to
151tell Google Test to use the same TR1 tuple library the rest of your
152project uses, or the two tuple implementations will clash.  To do
153that, add
154
155    -DGTEST_USE_OWN_TR1_TUPLE=0
156
157to the compiler flags while compiling Google Test and your tests.  If
158you want to force Google Test to use its own tuple library, just add
159
160    -DGTEST_USE_OWN_TR1_TUPLE=1
161
162to the compiler flags instead.
163
164If you don't want Google Test to use tuple at all, add
165
166    -DGTEST_HAS_TR1_TUPLE=0
167
168and all features using tuple will be disabled.
169
170### Multi-threaded Tests ###
171
172Google Test is thread-safe where the pthread library is available.
173After `#include "gtest/gtest.h"`, you can check the `GTEST_IS_THREADSAFE`
174macro to see whether this is the case (yes if the macro is `#defined` to
1751, no if it's undefined.).
176
177If Google Test doesn't correctly detect whether pthread is available
178in your environment, you can force it with
179
180    -DGTEST_HAS_PTHREAD=1
181
182or
183
184    -DGTEST_HAS_PTHREAD=0
185
186When Google Test uses pthread, you may need to add flags to your
187compiler and/or linker to select the pthread library, or you'll get
188link errors.  If you use the CMake script or the deprecated Autotools
189script, this is taken care of for you.  If you use your own build
190script, you'll need to read your compiler and linker's manual to
191figure out what flags to add.
192
193### As a Shared Library (DLL) ###
194
195Google Test is compact, so most users can build and link it as a
196static library for the simplicity.  You can choose to use Google Test
197as a shared library (known as a DLL on Windows) if you prefer.
198
199To compile *gtest* as a shared library, add
200
201    -DGTEST_CREATE_SHARED_LIBRARY=1
202
203to the compiler flags.  You'll also need to tell the linker to produce
204a shared library instead - consult your linker's manual for how to do
205it.
206
207To compile your *tests* that use the gtest shared library, add
208
209    -DGTEST_LINKED_AS_SHARED_LIBRARY=1
210
211to the compiler flags.
212
213Note: while the above steps aren't technically necessary today when
214using some compilers (e.g. GCC), they may become necessary in the
215future, if we decide to improve the speed of loading the library (see
216<http://gcc.gnu.org/wiki/Visibility> for details).  Therefore you are
217recommended to always add the above flags when using Google Test as a
218shared library.  Otherwise a future release of Google Test may break
219your build script.
220
221### Avoiding Macro Name Clashes ###
222
223In C++, macros don't obey namespaces.  Therefore two libraries that
224both define a macro of the same name will clash if you #include both
225definitions.  In case a Google Test macro clashes with another
226library, you can force Google Test to rename its macro to avoid the
227conflict.
228
229Specifically, if both Google Test and some other code define macro
230FOO, you can add
231
232    -DGTEST_DONT_DEFINE_FOO=1
233
234to the compiler flags to tell Google Test to change the macro's name
235from `FOO` to `GTEST_FOO`.  Currently `FOO` can be `FAIL`, `SUCCEED`,
236or `TEST`.  For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll
237need to write
238
239    GTEST_TEST(SomeTest, DoesThis) { ... }
240
241instead of
242
243    TEST(SomeTest, DoesThis) { ... }
244
245in order to define a test.
246
247## Developing Google Test ##
248
249This section discusses how to make your own changes to Google Test.
250
251### Testing Google Test Itself ###
252
253To make sure your changes work as intended and don't break existing
254functionality, you'll want to compile and run Google Test's own tests.
255For that you can use CMake:
256
257    mkdir mybuild
258    cd mybuild
259    cmake -Dgtest_build_tests=ON ${GTEST_DIR}
260
261Make sure you have Python installed, as some of Google Test's tests
262are written in Python.  If the cmake command complains about not being
263able to find Python (`Could NOT find PythonInterp (missing:
264PYTHON_EXECUTABLE)`), try telling it explicitly where your Python
265executable can be found:
266
267    cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR}
268
269Next, you can build Google Test and all of its own tests.  On \*nix,
270this is usually done by 'make'.  To run the tests, do
271
272    make test
273
274All tests should pass.
275
276Normally you don't need to worry about regenerating the source files,
277unless you need to modify them.  In that case, you should modify the
278corresponding .pump files instead and run the pump.py Python script to
279regenerate them.  You can find pump.py in the [scripts/](scripts/) directory.
280Read the [Pump manual](docs/PumpManual.md) for how to use it.
trunk/3rdparty/googletest/googletest/build-aux/.keep
r0r249096
1# Defines functions and macros useful for building Google Test and
2# Google Mock.
3#
4# Note:
5#
6# - This file will be run twice when building Google Mock (once via
7#   Google Test's CMakeLists.txt, and once via Google Mock's).
8#   Therefore it shouldn't have any side effects other than defining
9#   the functions and macros.
10#
11# - The functions/macros defined in this file may depend on Google
12#   Test and Google Mock's option() definitions, and thus must be
13#   called *after* the options have been defined.
14
15# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
16#
17# This must be a macro(), as inside a function string() can only
18# update variables in the function scope.
19macro(fix_default_compiler_settings_)
20  if (MSVC)
21    # For MSVC, CMake sets certain flags to defaults we want to override.
22    # This replacement code is taken from sample in the CMake Wiki at
23    # http://www.cmake.org/Wiki/CMake_FAQ#Dynamic_Replace.
24    foreach (flag_var
25             CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
26             CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
27      if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt)
28        # When Google Test is built as a shared library, it should also use
29        # shared runtime libraries.  Otherwise, it may end up with multiple
30        # copies of runtime library data in different modules, resulting in
31        # hard-to-find crashes. When it is built as a static library, it is
32        # preferable to use CRT as static libraries, as we don't have to rely
33        # on CRT DLLs being available. CMake always defaults to using shared
34        # CRT libraries, so we override that default here.
35        string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}")
36      endif()
37
38      # We prefer more strict warning checking for building Google Test.
39      # Replaces /W3 with /W4 in defaults.
40      string(REPLACE "/W3" "/W4" ${flag_var} "${${flag_var}}")
41    endforeach()
42  endif()
43endmacro()
44
45# Defines the compiler/linker flags used to build Google Test and
46# Google Mock.  You can tweak these definitions to suit your need.  A
47# variable's value is empty before it's explicitly assigned to.
48macro(config_compiler_and_linker)
49  if (NOT gtest_disable_pthreads)
50    # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT.
51    find_package(Threads)
52  endif()
53
54  fix_default_compiler_settings_()
55  if (MSVC)
56    # Newlines inside flags variables break CMake's NMake generator.
57    # TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.
58    set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi")
59    if (MSVC_VERSION LESS 1400)  # 1400 is Visual Studio 2005
60      # Suppress spurious warnings MSVC 7.1 sometimes issues.
61      # Forcing value to bool.
62      set(cxx_base_flags "${cxx_base_flags} -wd4800")
63      # Copy constructor and assignment operator could not be generated.
64      set(cxx_base_flags "${cxx_base_flags} -wd4511 -wd4512")
65      # Compatibility warnings not applicable to Google Test.
66      # Resolved overload was found by argument-dependent lookup.
67      set(cxx_base_flags "${cxx_base_flags} -wd4675")
68    endif()
69    if (MSVC_VERSION LESS 1500)  # 1500 is Visual Studio 2008
70      # Conditional expression is constant.
71      # When compiling with /W4, we get several instances of C4127
72      # (Conditional expression is constant). In our code, we disable that
73      # warning on a case-by-case basis. However, on Visual Studio 2005,
74      # the warning fires on std::list. Therefore on that compiler and earlier,
75      # we disable the warning project-wide.
76      set(cxx_base_flags "${cxx_base_flags} -wd4127")
77    endif()
78    if (NOT (MSVC_VERSION LESS 1700))  # 1700 is Visual Studio 2012.
79      # Suppress "unreachable code" warning on VS 2012 and later.
80      # http://stackoverflow.com/questions/3232669 explains the issue.
81      set(cxx_base_flags "${cxx_base_flags} -wd4702")
82    endif()
83
84    set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32")
85    set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN")
86    set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
87    set(cxx_no_exception_flags "-D_HAS_EXCEPTIONS=0")
88    set(cxx_no_rtti_flags "-GR-")
89  elseif (CMAKE_COMPILER_IS_GNUCXX)
90    set(cxx_base_flags "-Wall -Wshadow")
91    set(cxx_exception_flags "-fexceptions")
92    set(cxx_no_exception_flags "-fno-exceptions")
93    # Until version 4.3.2, GCC doesn't define a macro to indicate
94    # whether RTTI is enabled.  Therefore we define GTEST_HAS_RTTI
95    # explicitly.
96    set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0")
97    set(cxx_strict_flags
98      "-Wextra -Wno-unused-parameter -Wno-missing-field-initializers")
99  elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro")
100    set(cxx_exception_flags "-features=except")
101    # Sun Pro doesn't provide macros to indicate whether exceptions and
102    # RTTI are enabled, so we define GTEST_HAS_* explicitly.
103    set(cxx_no_exception_flags "-features=no%except -DGTEST_HAS_EXCEPTIONS=0")
104    set(cxx_no_rtti_flags "-features=no%rtti -DGTEST_HAS_RTTI=0")
105  elseif (CMAKE_CXX_COMPILER_ID STREQUAL "VisualAge" OR
106      CMAKE_CXX_COMPILER_ID STREQUAL "XL")
107    # CMake 2.8 changes Visual Age's compiler ID to "XL".
108    set(cxx_exception_flags "-qeh")
109    set(cxx_no_exception_flags "-qnoeh")
110    # Until version 9.0, Visual Age doesn't define a macro to indicate
111    # whether RTTI is enabled.  Therefore we define GTEST_HAS_RTTI
112    # explicitly.
113    set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0")
114  elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP")
115    set(cxx_base_flags "-AA -mt")
116    set(cxx_exception_flags "-DGTEST_HAS_EXCEPTIONS=1")
117    set(cxx_no_exception_flags "+noeh -DGTEST_HAS_EXCEPTIONS=0")
118    # RTTI can not be disabled in HP aCC compiler.
119    set(cxx_no_rtti_flags "")
120  endif()
121
122  if (CMAKE_USE_PTHREADS_INIT)  # The pthreads library is available and allowed.
123    set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=1")
124  else()
125    set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=0")
126  endif()
127
128  # For building gtest's own tests and samples.
129  set(cxx_exception "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_exception_flags}")
130  set(cxx_no_exception
131    "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_no_exception_flags}")
132  set(cxx_default "${cxx_exception}")
133  set(cxx_no_rtti "${cxx_default} ${cxx_no_rtti_flags}")
134  set(cxx_use_own_tuple "${cxx_default} -DGTEST_USE_OWN_TR1_TUPLE=1")
135
136  # For building the gtest libraries.
137  set(cxx_strict "${cxx_default} ${cxx_strict_flags}")
138endmacro()
139
140# Defines the gtest & gtest_main libraries.  User tests should link
141# with one of them.
142function(cxx_library_with_type name type cxx_flags)
143  # type can be either STATIC or SHARED to denote a static or shared library.
144  # ARGN refers to additional arguments after 'cxx_flags'.
145  add_library(${name} ${type} ${ARGN})
146  set_target_properties(${name}
147    PROPERTIES
148    COMPILE_FLAGS "${cxx_flags}")
149  if (BUILD_SHARED_LIBS OR type STREQUAL "SHARED")
150    set_target_properties(${name}
151      PROPERTIES
152      COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1")
153  endif()
154  if (CMAKE_USE_PTHREADS_INIT)
155    target_link_libraries(${name} ${CMAKE_THREAD_LIBS_INIT})
156  endif()
157endfunction()
158
159########################################################################
160#
161# Helper functions for creating build targets.
162
163function(cxx_shared_library name cxx_flags)
164  cxx_library_with_type(${name} SHARED "${cxx_flags}" ${ARGN})
165endfunction()
166
167function(cxx_library name cxx_flags)
168  cxx_library_with_type(${name} "" "${cxx_flags}" ${ARGN})
169endfunction()
170
171# cxx_executable_with_flags(name cxx_flags libs srcs...)
172#
173# creates a named C++ executable that depends on the given libraries and
174# is built from the given source files with the given compiler flags.
175function(cxx_executable_with_flags name cxx_flags libs)
176  add_executable(${name} ${ARGN})
177  if (cxx_flags)
178    set_target_properties(${name}
179      PROPERTIES
180      COMPILE_FLAGS "${cxx_flags}")
181  endif()
182  if (BUILD_SHARED_LIBS)
183    set_target_properties(${name}
184      PROPERTIES
185      COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
186  endif()
187  # To support mixing linking in static and dynamic libraries, link each
188  # library in with an extra call to target_link_libraries.
189  foreach (lib "${libs}")
190    target_link_libraries(${name} ${lib})
191  endforeach()
192endfunction()
193
194# cxx_executable(name dir lib srcs...)
195#
196# creates a named target that depends on the given libs and is built
197# from the given source files.  dir/name.cc is implicitly included in
198# the source file list.
199function(cxx_executable name dir libs)
200  cxx_executable_with_flags(
201    ${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN})
202endfunction()
203
204# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
205find_package(PythonInterp)
206
207# cxx_test_with_flags(name cxx_flags libs srcs...)
208#
209# creates a named C++ test that depends on the given libs and is built
210# from the given source files with the given compiler flags.
211function(cxx_test_with_flags name cxx_flags libs)
212  cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
213  add_test(${name} ${name})
214endfunction()
215
216# cxx_test(name libs srcs...)
217#
218# creates a named test target that depends on the given libs and is
219# built from the given source files.  Unlike cxx_test_with_flags,
220# test/name.cc is already implicitly included in the source file list.
221function(cxx_test name libs)
222  cxx_test_with_flags("${name}" "${cxx_default}" "${libs}"
223    "test/${name}.cc" ${ARGN})
224endfunction()
225
226# py_test(name)
227#
228# creates a Python test with the given name whose main module is in
229# test/name.py.  It does nothing if Python is not installed.
230function(py_test name)
231  # We are not supporting Python tests on Linux yet as they consider
232  # all Linux environments to be google3 and try to use google3 features.
233  if (PYTHONINTERP_FOUND)
234    # ${CMAKE_BINARY_DIR} is known at configuration time, so we can
235    # directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
236    # only at ctest runtime (by calling ctest -c <Configuration>), so
237    # we have to escape $ to delay variable substitution here.
238    add_test(${name}
239      ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
240          --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE})
241  endif()
242endfunction()
trunk/3rdparty/googletest/googletest/codegear/gtest.cbproj
r0r249096
1<?xml version="1.0" encoding="utf-8"?>
2<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3  <PropertyGroup>
4    <ProjectGuid>{bca37a72-5b07-46cf-b44e-89f8e06451a2}</ProjectGuid>
5    <Config Condition="'$(Config)'==''">Release</Config>
6  </PropertyGroup>
7  <PropertyGroup Condition="'$(Config)'=='Base' or '$(Base)'!=''">
8    <Base>true</Base>
9  </PropertyGroup>
10  <PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
11    <Base>true</Base>
12    <Cfg_1>true</Cfg_1>
13    <CfgParent>Base</CfgParent>
14  </PropertyGroup>
15  <PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
16    <Base>true</Base>
17    <Cfg_2>true</Cfg_2>
18    <CfgParent>Base</CfgParent>
19  </PropertyGroup>
20  <PropertyGroup Condition="'$(Base)'!=''">
21    <BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>
22    <OutputExt>lib</OutputExt>
23    <DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>
24    <Defines>NO_STRICT</Defines>
25    <DynamicRTL>true</DynamicRTL>
26    <UsePackages>true</UsePackages>
27    <ProjectType>CppStaticLibrary</ProjectType>
28    <BCC_CPPCompileAlways>true</BCC_CPPCompileAlways>
29    <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;GR32_BDS2006.bpi;GR32_DSGN_BDS2006.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;CExceptionExpert11.bpi</PackageImports>
30    <BCC_wpar>false</BCC_wpar>
31    <IncludePath>$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\include;..</IncludePath>
32    <AllPackageLibs>rtl.lib;vcl.lib</AllPackageLibs>
33    <TLIB_PageSize>32</TLIB_PageSize>
34    <ILINK_LibraryPath>$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk</ILINK_LibraryPath>
35  </PropertyGroup>
36  <PropertyGroup Condition="'$(Cfg_1)'!=''">
37    <BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>
38    <DCC_Optimize>false</DCC_Optimize>
39    <DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>
40    <Defines>_DEBUG;$(Defines)</Defines>
41    <ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>
42    <BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>
43    <ILINK_DisableIncrementalLinking>true</ILINK_DisableIncrementalLinking>
44    <BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>
45    <DCC_Define>DEBUG</DCC_Define>
46    <BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>
47    <IntermediateOutputDir>Debug</IntermediateOutputDir>
48    <TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>
49    <BCC_StackFrames>true</BCC_StackFrames>
50    <BCC_DisableOptimizations>true</BCC_DisableOptimizations>
51    <ILINK_LibraryPath>$(BDS)\lib\debug;$(ILINK_LibraryPath)</ILINK_LibraryPath>
52    <TASM_Debugging>Full</TASM_Debugging>
53    <BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>
54  </PropertyGroup>
55  <PropertyGroup Condition="'$(Cfg_2)'!=''">
56    <Defines>NDEBUG;$(Defines)</Defines>
57    <IntermediateOutputDir>Release</IntermediateOutputDir>
58    <ILINK_LibraryPath>$(BDS)\lib\release;$(ILINK_LibraryPath)</ILINK_LibraryPath>
59    <TASM_Debugging>None</TASM_Debugging>
60  </PropertyGroup>
61  <ProjectExtensions>
62    <Borland.Personality>CPlusPlusBuilder.Personality</Borland.Personality>
63    <Borland.ProjectType>CppStaticLibrary</Borland.ProjectType>
64    <BorlandProject>
65<BorlandProject><CPlusPlusBuilder.Personality><VersionInfo><VersionInfo Name="IncludeVerInfo">False</VersionInfo><VersionInfo Name="AutoIncBuild">False</VersionInfo><VersionInfo Name="MajorVer">1</VersionInfo><VersionInfo Name="MinorVer">0</VersionInfo><VersionInfo Name="Release">0</VersionInfo><VersionInfo Name="Build">0</VersionInfo><VersionInfo Name="Debug">False</VersionInfo><VersionInfo Name="PreRelease">False</VersionInfo><VersionInfo Name="Special">False</VersionInfo><VersionInfo Name="Private">False</VersionInfo><VersionInfo Name="DLL">False</VersionInfo><VersionInfo Name="Locale">1033</VersionInfo><VersionInfo Name="CodePage">1252</VersionInfo></VersionInfo><VersionInfoKeys><VersionInfoKeys Name="CompanyName"></VersionInfoKeys><VersionInfoKeys Name="FileDescription"></VersionInfoKeys><VersionInfoKeys Name="FileVersion">1.0.0.0</VersionInfoKeys><VersionInfoKeys Name="InternalName"></VersionInfoKeys><VersionInfoKeys Name="LegalCopyright"></VersionInfoKeys><VersionInfoKeys Name="LegalTrademarks"></VersionInfoKeys><VersionInfoKeys Name="OriginalFilename"></VersionInfoKeys><VersionInfoKeys Name="ProductName"></VersionInfoKeys><VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys><VersionInfoKeys Name="Comments"></VersionInfoKeys></VersionInfoKeys><Debugging><Debugging Name="DebugSourceDirs"></Debugging></Debugging><Parameters><Parameters Name="RunParams"></Parameters><Parameters Name="Launcher"></Parameters><Parameters Name="UseLauncher">False</Parameters><Parameters Name="DebugCWD"></Parameters><Parameters Name="HostApplication"></Parameters><Parameters Name="RemoteHost"></Parameters><Parameters Name="RemotePath"></Parameters><Parameters Name="RemoteParams"></Parameters><Parameters Name="RemoteLauncher"></Parameters><Parameters Name="UseRemoteLauncher">False</Parameters><Parameters Name="RemoteCWD"></Parameters><Parameters Name="RemoteDebug">False</Parameters><Parameters Name="Debug Symbols Search Path"></Parameters><Parameters Name="LoadAllSymbols">True</Parameters><Parameters Name="LoadUnspecifiedSymbols">False</Parameters></Parameters><Excluded_Packages>
66     
67     
68      <Excluded_Packages Name="$(BDS)\bin\bcboffice2k100.bpl">CodeGear C++Builder Office 2000 Servers Package</Excluded_Packages>
69      <Excluded_Packages Name="$(BDS)\bin\bcbofficexp100.bpl">CodeGear C++Builder Office XP Servers Package</Excluded_Packages>
70    </Excluded_Packages><Linker><Linker Name="LibPrefix"></Linker><Linker Name="LibSuffix"></Linker><Linker Name="LibVersion"></Linker></Linker><ProjectProperties><ProjectProperties Name="AutoShowDeps">False</ProjectProperties><ProjectProperties Name="ManagePaths">True</ProjectProperties><ProjectProperties Name="VerifyPackages">True</ProjectProperties></ProjectProperties><HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Count">3</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item0">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\include;..</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item1">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\include;..</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item2">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\src;..\include</HistoryLists_hlIncludePath></HistoryLists_hlIncludePath><HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Count">1</HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Item0">$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk</HistoryLists_hlILINK_LibraryPath></HistoryLists_hlILINK_LibraryPath><HistoryLists_hlDefines><HistoryLists_hlDefines Name="Count">1</HistoryLists_hlDefines><HistoryLists_hlDefines Name="Item0">NO_STRICT</HistoryLists_hlDefines></HistoryLists_hlDefines><HistoryLists_hlTLIB_PageSize><HistoryLists_hlTLIB_PageSize Name="Count">1</HistoryLists_hlTLIB_PageSize><HistoryLists_hlTLIB_PageSize Name="Item0">32</HistoryLists_hlTLIB_PageSize><HistoryLists_hlTLIB_PageSize Name="Item1">16</HistoryLists_hlTLIB_PageSize></HistoryLists_hlTLIB_PageSize></CPlusPlusBuilder.Personality></BorlandProject></BorlandProject>
71  </ProjectExtensions>
72  <Import Project="$(MSBuildBinPath)\Borland.Cpp.Targets" />
73  <ItemGroup>
74    <None Include="..\include\gtest\gtest-death-test.h">
75      <BuildOrder>3</BuildOrder>
76    </None>
77    <None Include="..\include\gtest\gtest-message.h">
78      <BuildOrder>4</BuildOrder>
79    </None>
80    <None Include="..\include\gtest\gtest-param-test.h">
81      <BuildOrder>5</BuildOrder>
82    </None>
83    <None Include="..\include\gtest\gtest-spi.h">
84      <BuildOrder>6</BuildOrder>
85    </None>
86    <None Include="..\include\gtest\gtest-test-part.h">
87      <BuildOrder>7</BuildOrder>
88    </None>
89    <None Include="..\include\gtest\gtest-typed-test.h">
90      <BuildOrder>8</BuildOrder>
91    </None>
92    <None Include="..\include\gtest\gtest.h">
93      <BuildOrder>0</BuildOrder>
94    </None>
95    <None Include="..\include\gtest\gtest_pred_impl.h">
96      <BuildOrder>1</BuildOrder>
97    </None>
98    <None Include="..\include\gtest\gtest_prod.h">
99      <BuildOrder>2</BuildOrder>
100    </None>
101    <None Include="..\include\gtest\internal\gtest-death-test-internal.h">
102      <BuildOrder>9</BuildOrder>
103    </None>
104    <None Include="..\include\gtest\internal\gtest-filepath.h">
105      <BuildOrder>10</BuildOrder>
106    </None>
107    <None Include="..\include\gtest\internal\gtest-internal.h">
108      <BuildOrder>11</BuildOrder>
109    </None>
110    <None Include="..\include\gtest\internal\gtest-linked_ptr.h">
111      <BuildOrder>12</BuildOrder>
112    </None>
113    <None Include="..\include\gtest\internal\gtest-param-util-generated.h">
114      <BuildOrder>14</BuildOrder>
115    </None>
116    <None Include="..\include\gtest\internal\gtest-param-util.h">
117      <BuildOrder>13</BuildOrder>
118    </None>
119    <None Include="..\include\gtest\internal\gtest-port.h">
120      <BuildOrder>15</BuildOrder>
121    </None>
122    <None Include="..\include\gtest\internal\gtest-string.h">
123      <BuildOrder>16</BuildOrder>
124    </None>
125    <None Include="..\include\gtest\internal\gtest-type-util.h">
126      <BuildOrder>17</BuildOrder>
127    </None>
128    <CppCompile Include="gtest_all.cc">
129      <BuildOrder>18</BuildOrder>
130    </CppCompile>
131    <BuildConfiguration Include="Debug">
132      <Key>Cfg_1</Key>
133    </BuildConfiguration>
134    <BuildConfiguration Include="Release">
135      <Key>Cfg_2</Key>
136    </BuildConfiguration>
137  </ItemGroup>
138</Project>
No newline at end of file
trunk/3rdparty/googletest/googletest/codegear/gtest.groupproj
r0r249096
1<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
2  <PropertyGroup>
3    <ProjectGuid>{c1d923e0-6cba-4332-9b6f-3420acbf5091}</ProjectGuid>
4  </PropertyGroup>
5  <ItemGroup />
6  <ItemGroup>
7    <Projects Include="gtest.cbproj" />
8    <Projects Include="gtest_main.cbproj" />
9    <Projects Include="gtest_unittest.cbproj" />
10  </ItemGroup>
11  <ProjectExtensions>
12    <Borland.Personality>Default.Personality</Borland.Personality>
13    <Borland.ProjectType />
14    <BorlandProject>
15<BorlandProject xmlns=""><Default.Personality></Default.Personality></BorlandProject></BorlandProject>
16  </ProjectExtensions>
17  <Target Name="gtest">
18    <MSBuild Projects="gtest.cbproj" Targets="" />
19  </Target>
20  <Target Name="gtest:Clean">
21    <MSBuild Projects="gtest.cbproj" Targets="Clean" />
22  </Target>
23  <Target Name="gtest:Make">
24    <MSBuild Projects="gtest.cbproj" Targets="Make" />
25  </Target>
26  <Target Name="gtest_main">
27    <MSBuild Projects="gtest_main.cbproj" Targets="" />
28  </Target>
29  <Target Name="gtest_main:Clean">
30    <MSBuild Projects="gtest_main.cbproj" Targets="Clean" />
31  </Target>
32  <Target Name="gtest_main:Make">
33    <MSBuild Projects="gtest_main.cbproj" Targets="Make" />
34  </Target>
35  <Target Name="gtest_unittest">
36    <MSBuild Projects="gtest_unittest.cbproj" Targets="" />
37  </Target>
38  <Target Name="gtest_unittest:Clean">
39    <MSBuild Projects="gtest_unittest.cbproj" Targets="Clean" />
40  </Target>
41  <Target Name="gtest_unittest:Make">
42    <MSBuild Projects="gtest_unittest.cbproj" Targets="Make" />
43  </Target>
44  <Target Name="Build">
45    <CallTarget Targets="gtest;gtest_main;gtest_unittest" />
46  </Target>
47  <Target Name="Clean">
48    <CallTarget Targets="gtest:Clean;gtest_main:Clean;gtest_unittest:Clean" />
49  </Target>
50  <Target Name="Make">
51    <CallTarget Targets="gtest:Make;gtest_main:Make;gtest_unittest:Make" />
52  </Target>
53  <Import Condition="Exists('$(MSBuildBinPath)\Borland.Group.Targets')" Project="$(MSBuildBinPath)\Borland.Group.Targets" />
54</Project>
No newline at end of file
trunk/3rdparty/googletest/googletest/codegear/gtest_all.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: Josh Kelley (joshkel@gmail.com)
31//
32// Google C++ Testing Framework (Google Test)
33//
34// C++Builder's IDE cannot build a static library from files with hyphens
35// in their name.  See http://qc.codegear.com/wc/qcmain.aspx?d=70977 .
36// This file serves as a workaround.
37
38#include "src/gtest-all.cc"
trunk/3rdparty/googletest/googletest/codegear/gtest_link.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: Josh Kelley (joshkel@gmail.com)
31//
32// Google C++ Testing Framework (Google Test)
33//
34// Links gtest.lib and gtest_main.lib into the current project in C++Builder.
35// This means that these libraries can't be renamed, but it's the only way to
36// ensure that Debug versus Release test builds are linked against the
37// appropriate Debug or Release build of the libraries.
38
39#pragma link "gtest.lib"
40#pragma link "gtest_main.lib"
trunk/3rdparty/googletest/googletest/codegear/gtest_main.cbproj
r0r249096
1<?xml version="1.0" encoding="utf-8"?>
2<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3  <PropertyGroup>
4    <ProjectGuid>{bca37a72-5b07-46cf-b44e-89f8e06451a2}</ProjectGuid>
5    <Config Condition="'$(Config)'==''">Release</Config>
6  </PropertyGroup>
7  <PropertyGroup Condition="'$(Config)'=='Base' or '$(Base)'!=''">
8    <Base>true</Base>
9  </PropertyGroup>
10  <PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
11    <Base>true</Base>
12    <Cfg_1>true</Cfg_1>
13    <CfgParent>Base</CfgParent>
14  </PropertyGroup>
15  <PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
16    <Base>true</Base>
17    <Cfg_2>true</Cfg_2>
18    <CfgParent>Base</CfgParent>
19  </PropertyGroup>
20  <PropertyGroup Condition="'$(Base)'!=''">
21    <BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>
22    <OutputExt>lib</OutputExt>
23    <DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>
24    <Defines>NO_STRICT</Defines>
25    <DynamicRTL>true</DynamicRTL>
26    <UsePackages>true</UsePackages>
27    <ProjectType>CppStaticLibrary</ProjectType>
28    <BCC_CPPCompileAlways>true</BCC_CPPCompileAlways>
29    <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;GR32_BDS2006.bpi;GR32_DSGN_BDS2006.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;CExceptionExpert11.bpi</PackageImports>
30    <BCC_wpar>false</BCC_wpar>
31    <IncludePath>$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\include;..</IncludePath>
32    <AllPackageLibs>rtl.lib;vcl.lib</AllPackageLibs>
33    <TLIB_PageSize>32</TLIB_PageSize>
34    <ILINK_LibraryPath>$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk</ILINK_LibraryPath>
35  </PropertyGroup>
36  <PropertyGroup Condition="'$(Cfg_1)'!=''">
37    <BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>
38    <DCC_Optimize>false</DCC_Optimize>
39    <DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>
40    <Defines>_DEBUG;$(Defines)</Defines>
41    <ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>
42    <BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>
43    <ILINK_DisableIncrementalLinking>true</ILINK_DisableIncrementalLinking>
44    <BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>
45    <DCC_Define>DEBUG</DCC_Define>
46    <BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>
47    <IntermediateOutputDir>Debug</IntermediateOutputDir>
48    <TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>
49    <BCC_StackFrames>true</BCC_StackFrames>
50    <BCC_DisableOptimizations>true</BCC_DisableOptimizations>
51    <ILINK_LibraryPath>$(BDS)\lib\debug;$(ILINK_LibraryPath)</ILINK_LibraryPath>
52    <TASM_Debugging>Full</TASM_Debugging>
53    <BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>
54  </PropertyGroup>
55  <PropertyGroup Condition="'$(Cfg_2)'!=''">
56    <Defines>NDEBUG;$(Defines)</Defines>
57    <IntermediateOutputDir>Release</IntermediateOutputDir>
58    <ILINK_LibraryPath>$(BDS)\lib\release;$(ILINK_LibraryPath)</ILINK_LibraryPath>
59    <TASM_Debugging>None</TASM_Debugging>
60  </PropertyGroup>
61  <ProjectExtensions>
62    <Borland.Personality>CPlusPlusBuilder.Personality</Borland.Personality>
63    <Borland.ProjectType>CppStaticLibrary</Borland.ProjectType>
64    <BorlandProject>
65<BorlandProject><CPlusPlusBuilder.Personality><VersionInfo><VersionInfo Name="IncludeVerInfo">False</VersionInfo><VersionInfo Name="AutoIncBuild">False</VersionInfo><VersionInfo Name="MajorVer">1</VersionInfo><VersionInfo Name="MinorVer">0</VersionInfo><VersionInfo Name="Release">0</VersionInfo><VersionInfo Name="Build">0</VersionInfo><VersionInfo Name="Debug">False</VersionInfo><VersionInfo Name="PreRelease">False</VersionInfo><VersionInfo Name="Special">False</VersionInfo><VersionInfo Name="Private">False</VersionInfo><VersionInfo Name="DLL">False</VersionInfo><VersionInfo Name="Locale">1033</VersionInfo><VersionInfo Name="CodePage">1252</VersionInfo></VersionInfo><VersionInfoKeys><VersionInfoKeys Name="CompanyName"></VersionInfoKeys><VersionInfoKeys Name="FileDescription"></VersionInfoKeys><VersionInfoKeys Name="FileVersion">1.0.0.0</VersionInfoKeys><VersionInfoKeys Name="InternalName"></VersionInfoKeys><VersionInfoKeys Name="LegalCopyright"></VersionInfoKeys><VersionInfoKeys Name="LegalTrademarks"></VersionInfoKeys><VersionInfoKeys Name="OriginalFilename"></VersionInfoKeys><VersionInfoKeys Name="ProductName"></VersionInfoKeys><VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys><VersionInfoKeys Name="Comments"></VersionInfoKeys></VersionInfoKeys><Debugging><Debugging Name="DebugSourceDirs"></Debugging></Debugging><Parameters><Parameters Name="RunParams"></Parameters><Parameters Name="Launcher"></Parameters><Parameters Name="UseLauncher">False</Parameters><Parameters Name="DebugCWD"></Parameters><Parameters Name="HostApplication"></Parameters><Parameters Name="RemoteHost"></Parameters><Parameters Name="RemotePath"></Parameters><Parameters Name="RemoteParams"></Parameters><Parameters Name="RemoteLauncher"></Parameters><Parameters Name="UseRemoteLauncher">False</Parameters><Parameters Name="RemoteCWD"></Parameters><Parameters Name="RemoteDebug">False</Parameters><Parameters Name="Debug Symbols Search Path"></Parameters><Parameters Name="LoadAllSymbols">True</Parameters><Parameters Name="LoadUnspecifiedSymbols">False</Parameters></Parameters><Excluded_Packages>
66      <Excluded_Packages Name="$(BDS)\bin\bcboffice2k100.bpl">CodeGear C++Builder Office 2000 Servers Package</Excluded_Packages>
67      <Excluded_Packages Name="$(BDS)\bin\bcbofficexp100.bpl">CodeGear C++Builder Office XP Servers Package</Excluded_Packages>
68    </Excluded_Packages><Linker><Linker Name="LibPrefix"></Linker><Linker Name="LibSuffix"></Linker><Linker Name="LibVersion"></Linker></Linker><ProjectProperties><ProjectProperties Name="AutoShowDeps">False</ProjectProperties><ProjectProperties Name="ManagePaths">True</ProjectProperties><ProjectProperties Name="VerifyPackages">True</ProjectProperties></ProjectProperties><HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Count">3</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item0">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\include;..</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item1">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\include;..</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item2">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\src;..\src;..\include</HistoryLists_hlIncludePath></HistoryLists_hlIncludePath><HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Count">1</HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Item0">$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk</HistoryLists_hlILINK_LibraryPath></HistoryLists_hlILINK_LibraryPath><HistoryLists_hlDefines><HistoryLists_hlDefines Name="Count">1</HistoryLists_hlDefines><HistoryLists_hlDefines Name="Item0">NO_STRICT</HistoryLists_hlDefines></HistoryLists_hlDefines><HistoryLists_hlTLIB_PageSize><HistoryLists_hlTLIB_PageSize Name="Count">1</HistoryLists_hlTLIB_PageSize><HistoryLists_hlTLIB_PageSize Name="Item0">32</HistoryLists_hlTLIB_PageSize><HistoryLists_hlTLIB_PageSize Name="Item1">16</HistoryLists_hlTLIB_PageSize></HistoryLists_hlTLIB_PageSize></CPlusPlusBuilder.Personality></BorlandProject></BorlandProject>
69  </ProjectExtensions>
70  <Import Project="$(MSBuildBinPath)\Borland.Cpp.Targets" />
71  <ItemGroup>
72    <CppCompile Include="..\src\gtest_main.cc">
73      <BuildOrder>0</BuildOrder>
74    </CppCompile>
75    <BuildConfiguration Include="Debug">
76      <Key>Cfg_1</Key>
77    </BuildConfiguration>
78    <BuildConfiguration Include="Release">
79      <Key>Cfg_2</Key>
80    </BuildConfiguration>
81  </ItemGroup>
82</Project>
trunk/3rdparty/googletest/googletest/codegear/gtest_unittest.cbproj
r0r249096
1<?xml version="1.0" encoding="utf-8"?>
2<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3  <PropertyGroup>
4    <ProjectGuid>{eea63393-5ac5-4b9c-8909-d75fef2daa41}</ProjectGuid>
5    <Config Condition="'$(Config)'==''">Release</Config>
6  </PropertyGroup>
7  <PropertyGroup Condition="'$(Config)'=='Base' or '$(Base)'!=''">
8    <Base>true</Base>
9  </PropertyGroup>
10  <PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
11    <Base>true</Base>
12    <Cfg_1>true</Cfg_1>
13    <CfgParent>Base</CfgParent>
14  </PropertyGroup>
15  <PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
16    <Base>true</Base>
17    <Cfg_2>true</Cfg_2>
18    <CfgParent>Base</CfgParent>
19  </PropertyGroup>
20  <PropertyGroup Condition="'$(Base)'!=''">
21    <OutputExt>exe</OutputExt>
22    <BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>
23    <Defines>NO_STRICT</Defines>
24    <DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>
25    <DynamicRTL>true</DynamicRTL>
26    <ILINK_ObjectSearchPath>..\test</ILINK_ObjectSearchPath>
27    <UsePackages>true</UsePackages>
28    <ProjectType>CppConsoleApplication</ProjectType>
29    <NoVCL>true</NoVCL>
30    <BCC_CPPCompileAlways>true</BCC_CPPCompileAlways>
31    <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>
32    <BCC_wpar>false</BCC_wpar>
33    <IncludePath>$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\include;..\test;..</IncludePath>
34    <ILINK_LibraryPath>$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk;..\test</ILINK_LibraryPath>
35    <Multithreaded>true</Multithreaded>
36  </PropertyGroup>
37  <PropertyGroup Condition="'$(Cfg_1)'!=''">
38    <BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>
39    <DCC_Optimize>false</DCC_Optimize>
40    <DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>
41    <Defines>_DEBUG;$(Defines)</Defines>
42    <ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>
43    <BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>
44    <ILINK_DisableIncrementalLinking>true</ILINK_DisableIncrementalLinking>
45    <BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>
46    <DCC_Define>DEBUG</DCC_Define>
47    <BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>
48    <IntermediateOutputDir>Debug</IntermediateOutputDir>
49    <TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>
50    <BCC_StackFrames>true</BCC_StackFrames>
51    <BCC_DisableOptimizations>true</BCC_DisableOptimizations>
52    <ILINK_LibraryPath>$(BDS)\lib\debug;$(ILINK_LibraryPath)</ILINK_LibraryPath>
53    <TASM_Debugging>Full</TASM_Debugging>
54    <BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>
55  </PropertyGroup>
56  <PropertyGroup Condition="'$(Cfg_2)'!=''">
57    <Defines>NDEBUG;$(Defines)</Defines>
58    <IntermediateOutputDir>Release</IntermediateOutputDir>
59    <ILINK_LibraryPath>$(BDS)\lib\release;$(ILINK_LibraryPath)</ILINK_LibraryPath>
60    <TASM_Debugging>None</TASM_Debugging>
61  </PropertyGroup>
62  <ProjectExtensions>
63    <Borland.Personality>CPlusPlusBuilder.Personality</Borland.Personality>
64    <Borland.ProjectType>CppConsoleApplication</Borland.ProjectType>
65    <BorlandProject>
66<BorlandProject><CPlusPlusBuilder.Personality><VersionInfo><VersionInfo Name="IncludeVerInfo">False</VersionInfo><VersionInfo Name="AutoIncBuild">False</VersionInfo><VersionInfo Name="MajorVer">1</VersionInfo><VersionInfo Name="MinorVer">0</VersionInfo><VersionInfo Name="Release">0</VersionInfo><VersionInfo Name="Build">0</VersionInfo><VersionInfo Name="Debug">False</VersionInfo><VersionInfo Name="PreRelease">False</VersionInfo><VersionInfo Name="Special">False</VersionInfo><VersionInfo Name="Private">False</VersionInfo><VersionInfo Name="DLL">False</VersionInfo><VersionInfo Name="Locale">1033</VersionInfo><VersionInfo Name="CodePage">1252</VersionInfo></VersionInfo><VersionInfoKeys><VersionInfoKeys Name="CompanyName"></VersionInfoKeys><VersionInfoKeys Name="FileDescription"></VersionInfoKeys><VersionInfoKeys Name="FileVersion">1.0.0.0</VersionInfoKeys><VersionInfoKeys Name="InternalName"></VersionInfoKeys><VersionInfoKeys Name="LegalCopyright"></VersionInfoKeys><VersionInfoKeys Name="LegalTrademarks"></VersionInfoKeys><VersionInfoKeys Name="OriginalFilename"></VersionInfoKeys><VersionInfoKeys Name="ProductName"></VersionInfoKeys><VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys><VersionInfoKeys Name="Comments"></VersionInfoKeys></VersionInfoKeys><Debugging><Debugging Name="DebugSourceDirs"></Debugging></Debugging><Parameters><Parameters Name="RunParams"></Parameters><Parameters Name="Launcher"></Parameters><Parameters Name="UseLauncher">False</Parameters><Parameters Name="DebugCWD"></Parameters><Parameters Name="HostApplication"></Parameters><Parameters Name="RemoteHost"></Parameters><Parameters Name="RemotePath"></Parameters><Parameters Name="RemoteParams"></Parameters><Parameters Name="RemoteLauncher"></Parameters><Parameters Name="UseRemoteLauncher">False</Parameters><Parameters Name="RemoteCWD"></Parameters><Parameters Name="RemoteDebug">False</Parameters><Parameters Name="Debug Symbols Search Path"></Parameters><Parameters Name="LoadAllSymbols">True</Parameters><Parameters Name="LoadUnspecifiedSymbols">False</Parameters></Parameters><Excluded_Packages>
67     
68     
69      <Excluded_Packages Name="$(BDS)\bin\bcboffice2k100.bpl">CodeGear C++Builder Office 2000 Servers Package</Excluded_Packages>
70      <Excluded_Packages Name="$(BDS)\bin\bcbofficexp100.bpl">CodeGear C++Builder Office XP Servers Package</Excluded_Packages>
71    </Excluded_Packages><Linker><Linker Name="LibPrefix"></Linker><Linker Name="LibSuffix"></Linker><Linker Name="LibVersion"></Linker></Linker><ProjectProperties><ProjectProperties Name="AutoShowDeps">False</ProjectProperties><ProjectProperties Name="ManagePaths">True</ProjectProperties><ProjectProperties Name="VerifyPackages">True</ProjectProperties></ProjectProperties><HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Count">3</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item0">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\include;..\test;..</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item1">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\include;..\test</HistoryLists_hlIncludePath><HistoryLists_hlIncludePath Name="Item2">$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\include</HistoryLists_hlIncludePath></HistoryLists_hlIncludePath><HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Count">1</HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Item0">$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk;..\test</HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Item1">$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk;..\test</HistoryLists_hlILINK_LibraryPath><HistoryLists_hlILINK_LibraryPath Name="Item2">$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk;$(OUTPUTDIR);..\test</HistoryLists_hlILINK_LibraryPath></HistoryLists_hlILINK_LibraryPath><HistoryLists_hlDefines><HistoryLists_hlDefines Name="Count">2</HistoryLists_hlDefines><HistoryLists_hlDefines Name="Item0">NO_STRICT</HistoryLists_hlDefines><HistoryLists_hlDefines Name="Item1">STRICT</HistoryLists_hlDefines></HistoryLists_hlDefines></CPlusPlusBuilder.Personality></BorlandProject></BorlandProject>
72  </ProjectExtensions>
73  <Import Project="$(MSBuildBinPath)\Borland.Cpp.Targets" />
74  <ItemGroup>
75    <CppCompile Include="..\test\gtest_unittest.cc">
76      <BuildOrder>0</BuildOrder>
77    </CppCompile>
78    <CppCompile Include="gtest_link.cc">
79      <BuildOrder>1</BuildOrder>
80    </CppCompile>
81    <BuildConfiguration Include="Debug">
82      <Key>Cfg_1</Key>
83    </BuildConfiguration>
84    <BuildConfiguration Include="Release">
85      <Key>Cfg_2</Key>
86    </BuildConfiguration>
87  </ItemGroup>
88</Project>
No newline at end of file
trunk/3rdparty/googletest/googletest/configure.ac
r0r249096
1m4_include(m4/acx_pthread.m4)
2
3# At this point, the Xcode project assumes the version string will be three
4# integers separated by periods and surrounded by square brackets (e.g.
5# "[1.0.1]"). It also asumes that there won't be any closing parenthesis
6# between "AC_INIT(" and the closing ")" including comments and strings.
7AC_INIT([Google C++ Testing Framework],
8        [1.7.0],
9        [googletestframework@googlegroups.com],
10        [gtest])
11
12# Provide various options to initialize the Autoconf and configure processes.
13AC_PREREQ([2.59])
14AC_CONFIG_SRCDIR([./LICENSE])
15AC_CONFIG_MACRO_DIR([m4])
16AC_CONFIG_AUX_DIR([build-aux])
17AC_CONFIG_HEADERS([build-aux/config.h])
18AC_CONFIG_FILES([Makefile])
19AC_CONFIG_FILES([scripts/gtest-config], [chmod +x scripts/gtest-config])
20
21# Initialize Automake with various options. We require at least v1.9, prevent
22# pedantic complaints about package files, and enable various distribution
23# targets.
24AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects])
25
26# Check for programs used in building Google Test.
27AC_PROG_CC
28AC_PROG_CXX
29AC_LANG([C++])
30AC_PROG_LIBTOOL
31
32# TODO(chandlerc@google.com): Currently we aren't running the Python tests
33# against the interpreter detected by AM_PATH_PYTHON, and so we condition
34# HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's
35# version to be >= 2.3. This will allow the scripts to use a "/usr/bin/env"
36# hashbang.
37PYTHON=  # We *do not* allow the user to specify a python interpreter
38AC_PATH_PROG([PYTHON],[python],[:])
39AS_IF([test "$PYTHON" != ":"],
40      [AM_PYTHON_CHECK_VERSION([$PYTHON],[2.3],[:],[PYTHON=":"])])
41AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"])
42
43# Configure pthreads.
44AC_ARG_WITH([pthreads],
45            [AS_HELP_STRING([--with-pthreads],
46               [use pthreads (default is yes)])],
47            [with_pthreads=$withval],
48            [with_pthreads=check])
49
50have_pthreads=no
51AS_IF([test "x$with_pthreads" != "xno"],
52      [ACX_PTHREAD(
53        [],
54        [AS_IF([test "x$with_pthreads" != "xcheck"],
55               [AC_MSG_FAILURE(
56                 [--with-pthreads was specified, but unable to be used])])])
57       have_pthreads="$acx_pthread_ok"])
58AM_CONDITIONAL([HAVE_PTHREADS],[test "x$have_pthreads" = "xyes"])
59AC_SUBST(PTHREAD_CFLAGS)
60AC_SUBST(PTHREAD_LIBS)
61
62# TODO(chandlerc@google.com) Check for the necessary system headers.
63
64# TODO(chandlerc@google.com) Check the types, structures, and other compiler
65# and architecture characteristics.
66
67# Output the generated files. No further autoconf macros may be used.
68AC_OUTPUT
trunk/3rdparty/googletest/googletest/docs/AdvancedGuide.md
r0r249096
1
2
3Now that you have read [Primer](Primer.md) and learned how to write tests
4using Google Test, it's time to learn some new tricks. This document
5will show you more assertions as well as how to construct complex
6failure messages, propagate fatal failures, reuse and speed up your
7test fixtures, and use various flags with your tests.
8
9# More Assertions #
10
11This section covers some less frequently used, but still significant,
12assertions.
13
14## Explicit Success and Failure ##
15
16These three assertions do not actually test a value or expression. Instead,
17they generate a success or failure directly. Like the macros that actually
18perform a test, you may stream a custom failure message into the them.
19
20| `SUCCEED();` |
21|:-------------|
22
23Generates a success. This does NOT make the overall test succeed. A test is
24considered successful only if none of its assertions fail during its execution.
25
26Note: `SUCCEED()` is purely documentary and currently doesn't generate any
27user-visible output. However, we may add `SUCCEED()` messages to Google Test's
28output in the future.
29
30| `FAIL();`  | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` |
31|:-----------|:-----------------|:------------------------------------------------------|
32
33`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal
34failure. These are useful when control flow, rather than a Boolean expression,
35deteremines the test's success or failure. For example, you might want to write
36something like:
37
38```
39switch(expression) {
40  case 1: ... some checks ...
41  case 2: ... some other checks
42  ...
43  default: FAIL() << "We shouldn't get here.";
44}
45```
46
47Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#Assertion_Placement.md) for more information.
48
49_Availability_: Linux, Windows, Mac.
50
51## Exception Assertions ##
52
53These are for verifying that a piece of code throws (or does not
54throw) an exception of the given type:
55
56| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
57|:--------------------|:-----------------------|:-------------|
58| `ASSERT_THROW(`_statement_, _exception\_type_`);`  | `EXPECT_THROW(`_statement_, _exception\_type_`);`  | _statement_ throws an exception of the given type  |
59| `ASSERT_ANY_THROW(`_statement_`);`                | `EXPECT_ANY_THROW(`_statement_`);`                | _statement_ throws an exception of any type        |
60| `ASSERT_NO_THROW(`_statement_`);`                 | `EXPECT_NO_THROW(`_statement_`);`                 | _statement_ doesn't throw any exception            |
61
62Examples:
63
64```
65ASSERT_THROW(Foo(5), bar_exception);
66
67EXPECT_NO_THROW({
68  int n = 5;
69  Bar(&n);
70});
71```
72
73_Availability_: Linux, Windows, Mac; since version 1.1.0.
74
75## Predicate Assertions for Better Error Messages ##
76
77Even though Google Test has a rich set of assertions, they can never be
78complete, as it's impossible (nor a good idea) to anticipate all the scenarios
79a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
80to check a complex expression, for lack of a better macro. This has the problem
81of not showing you the values of the parts of the expression, making it hard to
82understand what went wrong. As a workaround, some users choose to construct the
83failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
84is awkward especially when the expression has side-effects or is expensive to
85evaluate.
86
87Google Test gives you three different options to solve this problem:
88
89### Using an Existing Boolean Function ###
90
91If you already have a function or a functor that returns `bool` (or a type
92that can be implicitly converted to `bool`), you can use it in a _predicate
93assertion_ to get the function arguments printed for free:
94
95| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
96|:--------------------|:-----------------------|:-------------|
97| `ASSERT_PRED1(`_pred1, val1_`);`       | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
98| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` |  _pred2(val1, val2)_ returns true |
99|  ...                | ...                    | ...          |
100
101In the above, _predn_ is an _n_-ary predicate function or functor, where
102_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
103if the predicate returns `true` when applied to the given arguments, and fails
104otherwise. When the assertion fails, it prints the value of each argument. In
105either case, the arguments are evaluated exactly once.
106
107Here's an example. Given
108
109```
110// Returns true iff m and n have no common divisors except 1.
111bool MutuallyPrime(int m, int n) { ... }
112const int a = 3;
113const int b = 4;
114const int c = 10;
115```
116
117the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
118assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message
119
120<pre>
121!MutuallyPrime(b, c) is false, where<br>
122b is 4<br>
123c is 10<br>
124</pre>
125
126**Notes:**
127
128  1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](http://code.google.com/p/googletest/wiki/FAQ#The_compiler_complains_%22no_matching_function_to_call%22) for how to resolve it.
129  1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.
130
131_Availability_: Linux, Windows, Mac
132
133### Using a Function That Returns an AssertionResult ###
134
135While `EXPECT_PRED*()` and friends are handy for a quick job, the
136syntax is not satisfactory: you have to use different macros for
137different arities, and it feels more like Lisp than C++.  The
138`::testing::AssertionResult` class solves this problem.
139
140An `AssertionResult` object represents the result of an assertion
141(whether it's a success or a failure, and an associated message).  You
142can create an `AssertionResult` using one of these factory
143functions:
144
145```
146namespace testing {
147
148// Returns an AssertionResult object to indicate that an assertion has
149// succeeded.
150AssertionResult AssertionSuccess();
151
152// Returns an AssertionResult object to indicate that an assertion has
153// failed.
154AssertionResult AssertionFailure();
155
156}
157```
158
159You can then use the `<<` operator to stream messages to the
160`AssertionResult` object.
161
162To provide more readable messages in Boolean assertions
163(e.g. `EXPECT_TRUE()`), write a predicate function that returns
164`AssertionResult` instead of `bool`. For example, if you define
165`IsEven()` as:
166
167```
168::testing::AssertionResult IsEven(int n) {
169  if ((n % 2) == 0)
170    return ::testing::AssertionSuccess();
171  else
172    return ::testing::AssertionFailure() << n << " is odd";
173}
174```
175
176instead of:
177
178```
179bool IsEven(int n) {
180  return (n % 2) == 0;
181}
182```
183
184the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
185
186<pre>
187Value of: IsEven(Fib(4))<br>
188Actual: false (*3 is odd*)<br>
189Expected: true<br>
190</pre>
191
192instead of a more opaque
193
194<pre>
195Value of: IsEven(Fib(4))<br>
196Actual: false<br>
197Expected: true<br>
198</pre>
199
200If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
201as well, and are fine with making the predicate slower in the success
202case, you can supply a success message:
203
204```
205::testing::AssertionResult IsEven(int n) {
206  if ((n % 2) == 0)
207    return ::testing::AssertionSuccess() << n << " is even";
208  else
209    return ::testing::AssertionFailure() << n << " is odd";
210}
211```
212
213Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
214
215<pre>
216Value of: IsEven(Fib(6))<br>
217Actual: true (8 is even)<br>
218Expected: false<br>
219</pre>
220
221_Availability_: Linux, Windows, Mac; since version 1.4.1.
222
223### Using a Predicate-Formatter ###
224
225If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
226`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
227predicate do not support streaming to `ostream`, you can instead use the
228following _predicate-formatter assertions_ to _fully_ customize how the
229message is formatted:
230
231| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
232|:--------------------|:-----------------------|:-------------|
233| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);`        | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`); | _pred\_format1(val1)_ is successful |
234| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful |
235| `...`               | `...`                  | `...`        |
236
237The difference between this and the previous two groups of macros is that instead of
238a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_
239(_pred\_formatn_), which is a function or functor with the signature:
240
241`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);`
242
243where _val1_, _val2_, ..., and _valn_ are the values of the predicate
244arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding
245expressions as they appear in the source code. The types `T1`, `T2`, ..., and
246`Tn` can be either value types or reference types. For example, if an
247argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`,
248whichever is appropriate.
249
250A predicate-formatter returns a `::testing::AssertionResult` object to indicate
251whether the assertion has succeeded or not. The only way to create such an
252object is to call one of these factory functions:
253
254As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`:
255
256```
257// Returns the smallest prime common divisor of m and n,
258// or 1 when m and n are mutually prime.
259int SmallestPrimeCommonDivisor(int m, int n) { ... }
260
261// A predicate-formatter for asserting that two integers are mutually prime.
262::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
263                                               const char* n_expr,
264                                               int m,
265                                               int n) {
266  if (MutuallyPrime(m, n))
267    return ::testing::AssertionSuccess();
268 
269  return ::testing::AssertionFailure()
270      << m_expr << " and " << n_expr << " (" << m << " and " << n
271      << ") are not mutually prime, " << "as they have a common divisor "
272      << SmallestPrimeCommonDivisor(m, n);
273}
274```
275
276With this predicate-formatter, we can use
277
278```
279EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
280```
281
282to generate the message
283
284<pre>
285b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br>
286</pre>
287
288As you may have realized, many of the assertions we introduced earlier are
289special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
290indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.
291
292_Availability_: Linux, Windows, Mac.
293
294
295## Floating-Point Comparison ##
296
297Comparing floating-point numbers is tricky. Due to round-off errors, it is
298very unlikely that two floating-points will match exactly. Therefore,
299`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points
300can have a wide value range, no single fixed error bound works. It's better to
301compare by a fixed relative error bound, except for values close to 0 due to
302the loss of precision there.
303
304In general, for floating-point comparison to make sense, the user needs to
305carefully choose the error bound. If they don't want or care to, comparing in
306terms of Units in the Last Place (ULPs) is a good default, and Google Test
307provides assertions to do this. Full details about ULPs are quite long; if you
308want to learn more, see
309[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).
310
311### Floating-Point Macros ###
312
313| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
314|:--------------------|:-----------------------|:-------------|
315| `ASSERT_FLOAT_EQ(`_expected, actual_`);`  | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal |
316| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | the two `double` values are almost equal |
317
318By "almost equal", we mean the two values are within 4 ULP's from each
319other.
320
321The following assertions allow you to choose the acceptable error bound:
322
323| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
324|:--------------------|:-----------------------|:-------------|
325| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error |
326
327_Availability_: Linux, Windows, Mac.
328
329### Floating-Point Predicate-Format Functions ###
330
331Some floating-point operations are useful, but not that often used. In order
332to avoid an explosion of new macros, we provide them as predicate-format
333functions that can be used in predicate assertion macros (e.g.
334`EXPECT_PRED_FORMAT2`, etc).
335
336```
337EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
338EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
339```
340
341Verifies that _val1_ is less than, or almost equal to, _val2_. You can
342replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.
343
344_Availability_: Linux, Windows, Mac.
345
346## Windows HRESULT assertions ##
347
348These assertions test for `HRESULT` success or failure.
349
350| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
351|:--------------------|:-----------------------|:-------------|
352| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` |
353| `ASSERT_HRESULT_FAILED(`_expression_`);`    | `EXPECT_HRESULT_FAILED(`_expression_`);`    | _expression_ is a failure `HRESULT` |
354
355The generated output contains the human-readable error message
356associated with the `HRESULT` code returned by _expression_.
357
358You might use them like this:
359
360```
361CComPtr shell;
362ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
363CComVariant empty;
364ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
365```
366
367_Availability_: Windows.
368
369## Type Assertions ##
370
371You can call the function
372```
373::testing::StaticAssertTypeEq<T1, T2>();
374```
375to assert that types `T1` and `T2` are the same.  The function does
376nothing if the assertion is satisfied.  If the types are different,
377the function call will fail to compile, and the compiler error message
378will likely (depending on the compiler) show you the actual values of
379`T1` and `T2`.  This is mainly useful inside template code.
380
381_Caveat:_ When used inside a member function of a class template or a
382function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_
383the function is instantiated.  For example, given:
384```
385template <typename T> class Foo {
386 public:
387  void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
388};
389```
390the code:
391```
392void Test1() { Foo<bool> foo; }
393```
394will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never
395actually instantiated.  Instead, you need:
396```
397void Test2() { Foo<bool> foo; foo.Bar(); }
398```
399to cause a compiler error.
400
401_Availability:_ Linux, Windows, Mac; since version 1.3.0.
402
403## Assertion Placement ##
404
405You can use assertions in any C++ function. In particular, it doesn't
406have to be a method of the test fixture class. The one constraint is
407that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`)
408can only be used in void-returning functions. This is a consequence of
409Google Test not using exceptions. By placing it in a non-void function
410you'll get a confusing compile error like
411`"error: void value not ignored as it ought to be"`.
412
413If you need to use assertions in a function that returns non-void, one option
414is to make the function return the value in an out parameter instead. For
415example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
416need to make sure that `*result` contains some sensible value even when the
417function returns prematurely. As the function now returns `void`, you can use
418any assertion inside of it.
419
420If changing the function's type is not an option, you should just use
421assertions that generate non-fatal failures, such as `ADD_FAILURE*` and
422`EXPECT_*`.
423
424_Note_: Constructors and destructors are not considered void-returning
425functions, according to the C++ language specification, and so you may not use
426fatal assertions in them. You'll get a compilation error if you try. A simple
427workaround is to transfer the entire body of the constructor or destructor to a
428private void-returning method. However, you should be aware that a fatal
429assertion failure in a constructor does not terminate the current test, as your
430intuition might suggest; it merely returns from the constructor early, possibly
431leaving your object in a partially-constructed state. Likewise, a fatal
432assertion failure in a destructor may leave your object in a
433partially-destructed state. Use assertions carefully in these situations!
434
435# Teaching Google Test How to Print Your Values #
436
437When a test assertion such as `EXPECT_EQ` fails, Google Test prints the
438argument values to help you debug.  It does this using a
439user-extensible value printer.
440
441This printer knows how to print built-in C++ types, native arrays, STL
442containers, and any type that supports the `<<` operator.  For other
443types, it prints the raw bytes in the value and hopes that you the
444user can figure it out.
445
446As mentioned earlier, the printer is _extensible_.  That means
447you can teach it to do a better job at printing your particular type
448than to dump the bytes.  To do that, define `<<` for your type:
449
450```
451#include <iostream>
452
453namespace foo {
454
455class Bar { ... };  // We want Google Test to be able to print instances of this.
456
457// It's important that the << operator is defined in the SAME
458// namespace that defines Bar.  C++'s look-up rules rely on that.
459::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {
460  return os << bar.DebugString();  // whatever needed to print bar to os
461}
462
463}  // namespace foo
464```
465
466Sometimes, this might not be an option: your team may consider it bad
467style to have a `<<` operator for `Bar`, or `Bar` may already have a
468`<<` operator that doesn't do what you want (and you cannot change
469it).  If so, you can instead define a `PrintTo()` function like this:
470
471```
472#include <iostream>
473
474namespace foo {
475
476class Bar { ... };
477
478// It's important that PrintTo() is defined in the SAME
479// namespace that defines Bar.  C++'s look-up rules rely on that.
480void PrintTo(const Bar& bar, ::std::ostream* os) {
481  *os << bar.DebugString();  // whatever needed to print bar to os
482}
483
484}  // namespace foo
485```
486
487If you have defined both `<<` and `PrintTo()`, the latter will be used
488when Google Test is concerned.  This allows you to customize how the value
489appears in Google Test's output without affecting code that relies on the
490behavior of its `<<` operator.
491
492If you want to print a value `x` using Google Test's value printer
493yourself, just call `::testing::PrintToString(`_x_`)`, which
494returns an `std::string`:
495
496```
497vector<pair<Bar, int> > bar_ints = GetBarIntVector();
498
499EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
500    << "bar_ints = " << ::testing::PrintToString(bar_ints);
501```
502
503# Death Tests #
504
505In many applications, there are assertions that can cause application failure
506if a condition is not met. These sanity checks, which ensure that the program
507is in a known good state, are there to fail at the earliest possible time after
508some program state is corrupted. If the assertion checks the wrong condition,
509then the program may proceed in an erroneous state, which could lead to memory
510corruption, security holes, or worse. Hence it is vitally important to test
511that such assertion statements work as expected.
512
513Since these precondition checks cause the processes to die, we call such tests
514_death tests_. More generally, any test that checks that a program terminates
515(except by throwing an exception) in an expected fashion is also a death test.
516
517Note that if a piece of code throws an exception, we don't consider it "death"
518for the purpose of death tests, as the caller of the code could catch the exception
519and avoid the crash. If you want to verify exceptions thrown by your code,
520see [Exception Assertions](#Exception_Assertions.md).
521
522If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#Catching_Failures.md).
523
524## How to Write a Death Test ##
525
526Google Test has the following macros to support death tests:
527
528| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
529|:--------------------|:-----------------------|:-------------|
530| `ASSERT_DEATH(`_statement, regex_`); | `EXPECT_DEATH(`_statement, regex_`); | _statement_ crashes with the given error |
531| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`); | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`); | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing |
532| `ASSERT_EXIT(`_statement, predicate, regex_`); | `EXPECT_EXIT(`_statement, predicate, regex_`); |_statement_ exits with the given error and its exit code matches _predicate_ |
533
534where _statement_ is a statement that is expected to cause the process to
535die, _predicate_ is a function or function object that evaluates an integer
536exit status, and _regex_ is a regular expression that the stderr output of
537_statement_ is expected to match. Note that _statement_ can be _any valid
538statement_ (including _compound statement_) and doesn't have to be an
539expression.
540
541As usual, the `ASSERT` variants abort the current test function, while the
542`EXPECT` variants do not.
543
544**Note:** We use the word "crash" here to mean that the process
545terminates with a _non-zero_ exit status code.  There are two
546possibilities: either the process has called `exit()` or `_exit()`
547with a non-zero value, or it may be killed by a signal.
548
549This means that if _statement_ terminates the process with a 0 exit
550code, it is _not_ considered a crash by `EXPECT_DEATH`.  Use
551`EXPECT_EXIT` instead if this is the case, or if you want to restrict
552the exit code more precisely.
553
554A predicate here must accept an `int` and return a `bool`. The death test
555succeeds only if the predicate returns `true`. Google Test defines a few
556predicates that handle the most common cases:
557
558```
559::testing::ExitedWithCode(exit_code)
560```
561
562This expression is `true` if the program exited normally with the given exit
563code.
564
565```
566::testing::KilledBySignal(signal_number)  // Not available on Windows.
567```
568
569This expression is `true` if the program was killed by the given signal.
570
571The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
572that verifies the process' exit code is non-zero.
573
574Note that a death test only cares about three things:
575
576  1. does _statement_ abort or exit the process?
577  1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_?  Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero?  And
578  1. does the stderr output match _regex_?
579
580In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process.
581
582To write a death test, simply use one of the above macros inside your test
583function. For example,
584
585```
586TEST(MyDeathTest, Foo) {
587  // This death test uses a compound statement.
588  ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()");
589}
590TEST(MyDeathTest, NormalExit) {
591  EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
592}
593TEST(MyDeathTest, KillMyself) {
594  EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal");
595}
596```
597
598verifies that:
599
600  * calling `Foo(5)` causes the process to die with the given error message,
601  * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and
602  * calling `KillMyself()` kills the process with signal `SIGKILL`.
603
604The test function body may contain other assertions and statements as well, if
605necessary.
606
607_Important:_ We strongly recommend you to follow the convention of naming your
608test case (not test) `*DeathTest` when it contains a death test, as
609demonstrated in the above example. The `Death Tests And Threads` section below
610explains why.
611
612If a test fixture class is shared by normal tests and death tests, you
613can use typedef to introduce an alias for the fixture class and avoid
614duplicating its code:
615```
616class FooTest : public ::testing::Test { ... };
617
618typedef FooTest FooDeathTest;
619
620TEST_F(FooTest, DoesThis) {
621  // normal test
622}
623
624TEST_F(FooDeathTest, DoesThat) {
625  // death test
626}
627```
628
629_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0).  `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0.
630
631## Regular Expression Syntax ##
632
633On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the
634[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
635syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
636
637On Windows, Google Test uses its own simple regular expression
638implementation. It lacks many features you can find in POSIX extended
639regular expressions.  For example, we don't support union (`"x|y"`),
640grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count
641(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a
642literal character, period (`.`), or a single `\\` escape sequence; `x`
643and `y` denote regular expressions.):
644
645| `c` | matches any literal character `c` |
646|:----|:----------------------------------|
647| `\\d` | matches any decimal digit         |
648| `\\D` | matches any character that's not a decimal digit |
649| `\\f` | matches `\f`                      |
650| `\\n` | matches `\n`                      |
651| `\\r` | matches `\r`                      |
652| `\\s` | matches any ASCII whitespace, including `\n` |
653| `\\S` | matches any character that's not a whitespace |
654| `\\t` | matches `\t`                      |
655| `\\v` | matches `\v`                      |
656| `\\w` | matches any letter, `_`, or decimal digit |
657| `\\W` | matches any character that `\\w` doesn't match |
658| `\\c` | matches any literal character `c`, which must be a punctuation |
659| `\\.` | matches the `.` character         |
660| `.` | matches any single character except `\n` |
661| `A?` | matches 0 or 1 occurrences of `A` |
662| `A*` | matches 0 or many occurrences of `A` |
663| `A+` | matches 1 or many occurrences of `A` |
664| `^` | matches the beginning of a string (not that of each line) |
665| `$` | matches the end of a string (not that of each line) |
666| `xy` | matches `x` followed by `y`       |
667
668To help you determine which capability is available on your system,
669Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX
670extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses
671the simple version.  If you want your death tests to work in both
672cases, you can either `#if` on these macros or use the more limited
673syntax only.
674
675## How It Works ##
676
677Under the hood, `ASSERT_EXIT()` spawns a new process and executes the
678death test statement in that process. The details of of how precisely
679that happens depend on the platform and the variable
680`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the
681command-line flag `--gtest_death_test_style`).
682
683  * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which:
684    * If the variable's value is `"fast"`, the death test statement is immediately executed.
685    * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run.
686  * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX.
687
688Other values for the variable are illegal and will cause the death test to
689fail. Currently, the flag's default value is `"fast"`. However, we reserve the
690right to change it in the future. Therefore, your tests should not depend on
691this.
692
693In either case, the parent process waits for the child process to complete, and checks that
694
695  1. the child's exit status satisfies the predicate, and
696  1. the child's stderr matches the regular expression.
697
698If the death test statement runs to completion without dying, the child
699process will nonetheless terminate, and the assertion fails.
700
701## Death Tests And Threads ##
702
703The reason for the two death test styles has to do with thread safety. Due to
704well-known problems with forking in the presence of threads, death tests should
705be run in a single-threaded context. Sometimes, however, it isn't feasible to
706arrange that kind of environment. For example, statically-initialized modules
707may start threads before main is ever reached. Once threads have been created,
708it may be difficult or impossible to clean them up.
709
710Google Test has three features intended to raise awareness of threading issues.
711
712  1. A warning is emitted if multiple threads are running when a death test is encountered.
713  1. Test cases with a name ending in "DeathTest" are run before all other tests.
714  1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads.
715
716It's perfectly fine to create threads inside a death test statement; they are
717executed in a separate process and cannot affect the parent.
718
719## Death Test Styles ##
720
721The "threadsafe" death test style was introduced in order to help mitigate the
722risks of testing in a possibly multithreaded environment. It trades increased
723test execution time (potentially dramatically so) for improved thread safety.
724We suggest using the faster, default "fast" style unless your test has specific
725problems with it.
726
727You can choose a particular style of death tests by setting the flag
728programmatically:
729
730```
731::testing::FLAGS_gtest_death_test_style = "threadsafe";
732```
733
734You can do this in `main()` to set the style for all death tests in the
735binary, or in individual tests. Recall that flags are saved before running each
736test and restored afterwards, so you need not do that yourself. For example:
737
738```
739TEST(MyDeathTest, TestOne) {
740  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
741  // This test is run in the "threadsafe" style:
742  ASSERT_DEATH(ThisShouldDie(), "");
743}
744
745TEST(MyDeathTest, TestTwo) {
746  // This test is run in the "fast" style:
747  ASSERT_DEATH(ThisShouldDie(), "");
748}
749
750int main(int argc, char** argv) {
751  ::testing::InitGoogleTest(&argc, argv);
752  ::testing::FLAGS_gtest_death_test_style = "fast";
753  return RUN_ALL_TESTS();
754}
755```
756
757## Caveats ##
758
759The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement.
760If it leaves the current function via a `return` statement or by throwing an exception,
761the death test is considered to have failed.  Some Google Test macros may return
762from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_.
763
764Since _statement_ runs in the child process, any in-memory side effect (e.g.
765modifying a variable, releasing memory, etc) it causes will _not_ be observable
766in the parent process. In particular, if you release memory in a death test,
767your program will fail the heap check as the parent process will never see the
768memory reclaimed. To solve this problem, you can
769
770  1. try not to free memory in a death test;
771  1. free the memory again in the parent process; or
772  1. do not use the heap checker in your program.
773
774Due to an implementation detail, you cannot place multiple death test
775assertions on the same line; otherwise, compilation will fail with an unobvious
776error message.
777
778Despite the improved thread safety afforded by the "threadsafe" style of death
779test, thread problems such as deadlock are still possible in the presence of
780handlers registered with `pthread_atfork(3)`.
781
782# Using Assertions in Sub-routines #
783
784## Adding Traces to Assertions ##
785
786If a test sub-routine is called from several places, when an assertion
787inside it fails, it can be hard to tell which invocation of the
788sub-routine the failure is from.  You can alleviate this problem using
789extra logging or custom failure messages, but that usually clutters up
790your tests. A better solution is to use the `SCOPED_TRACE` macro:
791
792| `SCOPED_TRACE(`_message_`);` |
793|:-----------------------------|
794
795where _message_ can be anything streamable to `std::ostream`. This
796macro will cause the current file name, line number, and the given
797message to be added in every failure message. The effect will be
798undone when the control leaves the current lexical scope.
799
800For example,
801
802```
80310: void Sub1(int n) {
80411:   EXPECT_EQ(1, Bar(n));
80512:   EXPECT_EQ(2, Bar(n + 1));
80613: }
80714:
80815: TEST(FooTest, Bar) {
80916:   {
81017:     SCOPED_TRACE("A");  // This trace point will be included in
81118:                         // every failure in this scope.
81219:     Sub1(1);
81320:   }
81421:   // Now it won't.
81522:   Sub1(9);
81623: }
817```
818
819could result in messages like these:
820
821```
822path/to/foo_test.cc:11: Failure
823Value of: Bar(n)
824Expected: 1
825  Actual: 2
826   Trace:
827path/to/foo_test.cc:17: A
828
829path/to/foo_test.cc:12: Failure
830Value of: Bar(n + 1)
831Expected: 2
832  Actual: 3
833```
834
835Without the trace, it would've been difficult to know which invocation
836of `Sub1()` the two failures come from respectively. (You could add an
837extra message to each assertion in `Sub1()` to indicate the value of
838`n`, but that's tedious.)
839
840Some tips on using `SCOPED_TRACE`:
841
842  1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site.
843  1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from.
844  1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`.
845  1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered.
846  1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file!
847
848_Availability:_ Linux, Windows, Mac.
849
850## Propagating Fatal Failures ##
851
852A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
853when they fail they only abort the _current function_, not the entire test. For
854example, the following test will segfault:
855```
856void Subroutine() {
857  // Generates a fatal failure and aborts the current function.
858  ASSERT_EQ(1, 2);
859  // The following won't be executed.
860  ...
861}
862
863TEST(FooTest, Bar) {
864  Subroutine();
865  // The intended behavior is for the fatal failure
866  // in Subroutine() to abort the entire test.
867  // The actual behavior: the function goes on after Subroutine() returns.
868  int* p = NULL;
869  *p = 3; // Segfault!
870}
871```
872
873Since we don't use exceptions, it is technically impossible to
874implement the intended behavior here.  To alleviate this, Google Test
875provides two solutions.  You could use either the
876`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
877`HasFatalFailure()` function.  They are described in the following two
878subsections.
879
880### Asserting on Subroutines ###
881
882As shown above, if your test calls a subroutine that has an `ASSERT_*`
883failure in it, the test will continue after the subroutine
884returns. This may not be what you want.
885
886Often people want fatal failures to propagate like exceptions.  For
887that Google Test offers the following macros:
888
889| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
890|:--------------------|:-----------------------|:-------------|
891| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. |
892
893Only failures in the thread that executes the assertion are checked to
894determine the result of this type of assertions.  If _statement_
895creates new threads, failures in these threads are ignored.
896
897Examples:
898
899```
900ASSERT_NO_FATAL_FAILURE(Foo());
901
902int i;
903EXPECT_NO_FATAL_FAILURE({
904  i = Bar();
905});
906```
907
908_Availability:_ Linux, Windows, Mac. Assertions from multiple threads
909are currently not supported.
910
911### Checking for Failures in the Current Test ###
912
913`HasFatalFailure()` in the `::testing::Test` class returns `true` if an
914assertion in the current test has suffered a fatal failure. This
915allows functions to catch fatal failures in a sub-routine and return
916early.
917
918```
919class Test {
920 public:
921  ...
922  static bool HasFatalFailure();
923};
924```
925
926The typical usage, which basically simulates the behavior of a thrown
927exception, is:
928
929```
930TEST(FooTest, Bar) {
931  Subroutine();
932  // Aborts if Subroutine() had a fatal failure.
933  if (HasFatalFailure())
934    return;
935  // The following won't be executed.
936  ...
937}
938```
939
940If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
941fixture, you must add the `::testing::Test::` prefix, as in:
942
943```
944if (::testing::Test::HasFatalFailure())
945  return;
946```
947
948Similarly, `HasNonfatalFailure()` returns `true` if the current test
949has at least one non-fatal failure, and `HasFailure()` returns `true`
950if the current test has at least one failure of either kind.
951
952_Availability:_ Linux, Windows, Mac.  `HasNonfatalFailure()` and
953`HasFailure()` are available since version 1.4.0.
954
955# Logging Additional Information #
956
957In your test code, you can call `RecordProperty("key", value)` to log
958additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output
959if you specify one. For example, the test
960
961```
962TEST_F(WidgetUsageTest, MinAndMaxWidgets) {
963  RecordProperty("MaximumWidgets", ComputeMaxUsage());
964  RecordProperty("MinimumWidgets", ComputeMinUsage());
965}
966```
967
968will output XML like this:
969
970```
971...
972  <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest"
973            MaximumWidgets="12"
974            MinimumWidgets="9" />
975...
976```
977
978_Note_:
979  * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class.
980  * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`).
981  * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element.
982
983_Availability_: Linux, Windows, Mac.
984
985# Sharing Resources Between Tests in the Same Test Case #
986
987
988
989Google Test creates a new test fixture object for each test in order to make
990tests independent and easier to debug. However, sometimes tests use resources
991that are expensive to set up, making the one-copy-per-test model prohibitively
992expensive.
993
994If the tests don't change the resource, there's no harm in them sharing a
995single resource copy. So, in addition to per-test set-up/tear-down, Google Test
996also supports per-test-case set-up/tear-down. To use it:
997
998  1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources.
999  1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down.
1000
1001That's it! Google Test automatically calls `SetUpTestCase()` before running the
1002_first test_ in the `FooTest` test case (i.e. before creating the first
1003`FooTest` object), and calls `TearDownTestCase()` after running the _last test_
1004in it (i.e. after deleting the last `FooTest` object). In between, the tests
1005can use the shared resources.
1006
1007Remember that the test order is undefined, so your code can't depend on a test
1008preceding or following another. Also, the tests must either not modify the
1009state of any shared resource, or, if they do modify the state, they must
1010restore the state to its original value before passing control to the next
1011test.
1012
1013Here's an example of per-test-case set-up and tear-down:
1014```
1015class FooTest : public ::testing::Test {
1016 protected:
1017  // Per-test-case set-up.
1018  // Called before the first test in this test case.
1019  // Can be omitted if not needed.
1020  static void SetUpTestCase() {
1021    shared_resource_ = new ...;
1022  }
1023
1024  // Per-test-case tear-down.
1025  // Called after the last test in this test case.
1026  // Can be omitted if not needed.
1027  static void TearDownTestCase() {
1028    delete shared_resource_;
1029    shared_resource_ = NULL;
1030  }
1031
1032  // You can define per-test set-up and tear-down logic as usual.
1033  virtual void SetUp() { ... }
1034  virtual void TearDown() { ... }
1035
1036  // Some expensive resource shared by all tests.
1037  static T* shared_resource_;
1038};
1039
1040T* FooTest::shared_resource_ = NULL;
1041
1042TEST_F(FooTest, Test1) {
1043  ... you can refer to shared_resource here ...
1044}
1045TEST_F(FooTest, Test2) {
1046  ... you can refer to shared_resource here ...
1047}
1048```
1049
1050_Availability:_ Linux, Windows, Mac.
1051
1052# Global Set-Up and Tear-Down #
1053
1054Just as you can do set-up and tear-down at the test level and the test case
1055level, you can also do it at the test program level. Here's how.
1056
1057First, you subclass the `::testing::Environment` class to define a test
1058environment, which knows how to set-up and tear-down:
1059
1060```
1061class Environment {
1062 public:
1063  virtual ~Environment() {}
1064  // Override this to define how to set up the environment.
1065  virtual void SetUp() {}
1066  // Override this to define how to tear down the environment.
1067  virtual void TearDown() {}
1068};
1069```
1070
1071Then, you register an instance of your environment class with Google Test by
1072calling the `::testing::AddGlobalTestEnvironment()` function:
1073
1074```
1075Environment* AddGlobalTestEnvironment(Environment* env);
1076```
1077
1078Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
1079the environment object, then runs the tests if there was no fatal failures, and
1080finally calls `TearDown()` of the environment object.
1081
1082It's OK to register multiple environment objects. In this case, their `SetUp()`
1083will be called in the order they are registered, and their `TearDown()` will be
1084called in the reverse order.
1085
1086Note that Google Test takes ownership of the registered environment objects.
1087Therefore **do not delete them** by yourself.
1088
1089You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is
1090called, probably in `main()`. If you use `gtest_main`, you need to      call
1091this before `main()` starts for it to take effect. One way to do this is to
1092define a global variable like this:
1093
1094```
1095::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
1096```
1097
1098However, we strongly recommend you to write your own `main()` and call
1099`AddGlobalTestEnvironment()` there, as relying on initialization of global
1100variables makes the code harder to read and may cause problems when you
1101register multiple environments from different translation units and the
1102environments have dependencies among them (remember that the compiler doesn't
1103guarantee the order in which global variables from different translation units
1104are initialized).
1105
1106_Availability:_ Linux, Windows, Mac.
1107
1108
1109# Value Parameterized Tests #
1110
1111_Value-parameterized tests_ allow you to test your code with different
1112parameters without writing multiple copies of the same test.
1113
1114Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag.
1115
1116```
1117TEST(MyCodeTest, TestFoo) {
1118  // A code to test foo().
1119}
1120```
1121
1122Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code.
1123
1124```
1125void TestFooHelper(bool flag_value) {
1126  flag = flag_value;
1127  // A code to test foo().
1128}
1129
1130TEST(MyCodeTest, TestFoo) {
1131  TestFooHelper(false);
1132  TestFooHelper(true);
1133}
1134```
1135
1136But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred?
1137
1138Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values.
1139
1140Here are some other situations when value-parameterized tests come handy:
1141
1142  * You want to test different implementations of an OO interface.
1143  * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it!
1144
1145## How to Write Value-Parameterized Tests ##
1146
1147To write value-parameterized tests, first you should define a fixture
1148class.  It must be derived from both `::testing::Test` and
1149`::testing::WithParamInterface<T>` (the latter is a pure interface),
1150where `T` is the type of your parameter values.  For convenience, you
1151can just derive the fixture class from `::testing::TestWithParam<T>`,
1152which itself is derived from both `::testing::Test` and
1153`::testing::WithParamInterface<T>`. `T` can be any copyable type. If
1154it's a raw pointer, you are responsible for managing the lifespan of
1155the pointed values.
1156
1157```
1158class FooTest : public ::testing::TestWithParam<const char*> {
1159  // You can implement all the usual fixture class members here.
1160  // To access the test parameter, call GetParam() from class
1161  // TestWithParam<T>.
1162};
1163
1164// Or, when you want to add parameters to a pre-existing fixture class:
1165class BaseTest : public ::testing::Test {
1166  ...
1167};
1168class BarTest : public BaseTest,
1169                public ::testing::WithParamInterface<const char*> {
1170  ...
1171};
1172```
1173
1174Then, use the `TEST_P` macro to define as many test patterns using
1175this fixture as you want.  The `_P` suffix is for "parameterized" or
1176"pattern", whichever you prefer to think.
1177
1178```
1179TEST_P(FooTest, DoesBlah) {
1180  // Inside a test, access the test parameter with the GetParam() method
1181  // of the TestWithParam<T> class:
1182  EXPECT_TRUE(foo.Blah(GetParam()));
1183  ...
1184}
1185
1186TEST_P(FooTest, HasBlahBlah) {
1187  ...
1188}
1189```
1190
1191Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test
1192case with any set of parameters you want. Google Test defines a number of
1193functions for generating test parameters. They return what we call
1194(surprise!) _parameter generators_. Here is a summary of them,
1195which are all in the `testing` namespace:
1196
1197| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
1198|:----------------------------|:------------------------------------------------------------------------------------------------------------------|
1199| `Values(v1, v2, ..., vN)`   | Yields values `{v1, v2, ..., vN}`.                                                                                |
1200| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time.  |
1201| `Bool()`                    | Yields sequence `{false, true}`.                                                                                  |
1202| `Combine(g1, g2, ..., gN)`  | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `<tr1/tuple>` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-port.h) for more information. |
1203
1204For more details, see the comments at the definitions of these functions in the [source code](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-param-test.h).
1205
1206The following statement will instantiate tests from the `FooTest` test case
1207each with parameter values `"meeny"`, `"miny"`, and `"moe"`.
1208
1209```
1210INSTANTIATE_TEST_CASE_P(InstantiationName,
1211                        FooTest,
1212                        ::testing::Values("meeny", "miny", "moe"));
1213```
1214
1215To distinguish different instances of the pattern (yes, you can
1216instantiate it more than once), the first argument to
1217`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual
1218test case name. Remember to pick unique prefixes for different
1219instantiations. The tests from the instantiation above will have these
1220names:
1221
1222  * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
1223  * `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
1224  * `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
1225  * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
1226  * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
1227  * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
1228
1229You can use these names in [--gtest\_filter](#Running_a_Subset_of_the_Tests.md).
1230
1231This statement will instantiate all tests from `FooTest` again, each
1232with parameter values `"cat"` and `"dog"`:
1233
1234```
1235const char* pets[] = {"cat", "dog"};
1236INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest,
1237                        ::testing::ValuesIn(pets));
1238```
1239
1240The tests from the instantiation above will have these names:
1241
1242  * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
1243  * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
1244  * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
1245  * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
1246
1247Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_
1248tests in the given test case, whether their definitions come before or
1249_after_ the `INSTANTIATE_TEST_CASE_P` statement.
1250
1251You can see
1252[these](http://code.google.com/p/googletest/source/browse/trunk/samples/sample7_unittest.cc)
1253[files](http://code.google.com/p/googletest/source/browse/trunk/samples/sample8_unittest.cc) for more examples.
1254
1255_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0.
1256
1257## Creating Value-Parameterized Abstract Tests ##
1258
1259In the above, we define and instantiate `FooTest` in the same source
1260file. Sometimes you may want to define value-parameterized tests in a
1261library and let other people instantiate them later. This pattern is
1262known as <i>abstract tests</i>. As an example of its application, when you
1263are designing an interface you can write a standard suite of abstract
1264tests (perhaps using a factory function as the test parameter) that
1265all implementations of the interface are expected to pass. When
1266someone implements the interface, he can instantiate your suite to get
1267all the interface-conformance tests for free.
1268
1269To define abstract tests, you should organize your code like this:
1270
1271  1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests.
1272  1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests.
1273
1274Once they are defined, you can instantiate them by including
1275`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking
1276with `foo_param_test.cc`. You can instantiate the same abstract test
1277case multiple times, possibly in different source files.
1278
1279# Typed Tests #
1280
1281Suppose you have multiple implementations of the same interface and
1282want to make sure that all of them satisfy some common requirements.
1283Or, you may have defined several types that are supposed to conform to
1284the same "concept" and you want to verify it.  In both cases, you want
1285the same test logic repeated for different types.
1286
1287While you can write one `TEST` or `TEST_F` for each type you want to
1288test (and you may even factor the test logic into a function template
1289that you invoke from the `TEST`), it's tedious and doesn't scale:
1290if you want _m_ tests over _n_ types, you'll end up writing _m\*n_
1291`TEST`s.
1292
1293_Typed tests_ allow you to repeat the same test logic over a list of
1294types.  You only need to write the test logic once, although you must
1295know the type list when writing typed tests.  Here's how you do it:
1296
1297First, define a fixture class template.  It should be parameterized
1298by a type.  Remember to derive it from `::testing::Test`:
1299
1300```
1301template <typename T>
1302class FooTest : public ::testing::Test {
1303 public:
1304  ...
1305  typedef std::list<T> List;
1306  static T shared_;
1307  T value_;
1308};
1309```
1310
1311Next, associate a list of types with the test case, which will be
1312repeated for each type in the list:
1313
1314```
1315typedef ::testing::Types<char, int, unsigned int> MyTypes;
1316TYPED_TEST_CASE(FooTest, MyTypes);
1317```
1318
1319The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse
1320correctly.  Otherwise the compiler will think that each comma in the
1321type list introduces a new macro argument.
1322
1323Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test
1324for this test case.  You can repeat this as many times as you want:
1325
1326```
1327TYPED_TEST(FooTest, DoesBlah) {
1328  // Inside a test, refer to the special name TypeParam to get the type
1329  // parameter.  Since we are inside a derived class template, C++ requires
1330  // us to visit the members of FooTest via 'this'.
1331  TypeParam n = this->value_;
1332
1333  // To visit static members of the fixture, add the 'TestFixture::'
1334  // prefix.
1335  n += TestFixture::shared_;
1336
1337  // To refer to typedefs in the fixture, add the 'typename TestFixture::'
1338  // prefix.  The 'typename' is required to satisfy the compiler.
1339  typename TestFixture::List values;
1340  values.push_back(n);
1341  ...
1342}
1343
1344TYPED_TEST(FooTest, HasPropertyA) { ... }
1345```
1346
1347You can see `samples/sample6_unittest.cc` for a complete example.
1348
1349_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1350since version 1.1.0.
1351
1352# Type-Parameterized Tests #
1353
1354_Type-parameterized tests_ are like typed tests, except that they
1355don't require you to know the list of types ahead of time.  Instead,
1356you can define the test logic first and instantiate it with different
1357type lists later.  You can even instantiate it more than once in the
1358same program.
1359
1360If you are designing an interface or concept, you can define a suite
1361of type-parameterized tests to verify properties that any valid
1362implementation of the interface/concept should have.  Then, the author
1363of each implementation can just instantiate the test suite with his
1364type to verify that it conforms to the requirements, without having to
1365write similar tests repeatedly.  Here's an example:
1366
1367First, define a fixture class template, as we did with typed tests:
1368
1369```
1370template <typename T>
1371class FooTest : public ::testing::Test {
1372  ...
1373};
1374```
1375
1376Next, declare that you will define a type-parameterized test case:
1377
1378```
1379TYPED_TEST_CASE_P(FooTest);
1380```
1381
1382The `_P` suffix is for "parameterized" or "pattern", whichever you
1383prefer to think.
1384
1385Then, use `TYPED_TEST_P()` to define a type-parameterized test.  You
1386can repeat this as many times as you want:
1387
1388```
1389TYPED_TEST_P(FooTest, DoesBlah) {
1390  // Inside a test, refer to TypeParam to get the type parameter.
1391  TypeParam n = 0;
1392  ...
1393}
1394
1395TYPED_TEST_P(FooTest, HasPropertyA) { ... }
1396```
1397
1398Now the tricky part: you need to register all test patterns using the
1399`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them.
1400The first argument of the macro is the test case name; the rest are
1401the names of the tests in this test case:
1402
1403```
1404REGISTER_TYPED_TEST_CASE_P(FooTest,
1405                           DoesBlah, HasPropertyA);
1406```
1407
1408Finally, you are free to instantiate the pattern with the types you
1409want.  If you put the above code in a header file, you can `#include`
1410it in multiple C++ source files and instantiate it multiple times.
1411
1412```
1413typedef ::testing::Types<char, int, unsigned int> MyTypes;
1414INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
1415```
1416
1417To distinguish different instances of the pattern, the first argument
1418to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be
1419added to the actual test case name.  Remember to pick unique prefixes
1420for different instances.
1421
1422In the special case where the type list contains only one type, you
1423can write that type directly without `::testing::Types<...>`, like this:
1424
1425```
1426INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
1427```
1428
1429You can see `samples/sample6_unittest.cc` for a complete example.
1430
1431_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1432since version 1.1.0.
1433
1434# Testing Private Code #
1435
1436If you change your software's internal implementation, your tests should not
1437break as long as the change is not observable by users. Therefore, per the
1438_black-box testing principle_, most of the time you should test your code
1439through its public interfaces.
1440
1441If you still find yourself needing to test internal implementation code,
1442consider if there's a better design that wouldn't require you to do so. If you
1443absolutely have to test non-public interface code though, you can. There are
1444two cases to consider:
1445
1446  * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and
1447  * Private or protected class members
1448
1449## Static Functions ##
1450
1451Both static functions and definitions/declarations in an unnamed namespace are
1452only visible within the same translation unit. To test them, you can `#include`
1453the entire `.cc` file being tested in your `*_test.cc` file. (#including `.cc`
1454files is not a good way to reuse code - you should not do this in production
1455code!)
1456
1457However, a better approach is to move the private code into the
1458`foo::internal` namespace, where `foo` is the namespace your project normally
1459uses, and put the private declarations in a `*-internal.h` file. Your
1460production `.cc` files and your tests are allowed to include this internal
1461header, but your clients are not. This way, you can fully test your internal
1462implementation without leaking it to your clients.
1463
1464## Private Class Members ##
1465
1466Private class members are only accessible from within the class or by friends.
1467To access a class' private members, you can declare your test fixture as a
1468friend to the class and define accessors in your fixture. Tests using the
1469fixture can then access the private members of your production class via the
1470accessors in the fixture. Note that even though your fixture is a friend to
1471your production class, your tests are not automatically friends to it, as they
1472are technically defined in sub-classes of the fixture.
1473
1474Another way to test private members is to refactor them into an implementation
1475class, which is then declared in a `*-internal.h` file. Your clients aren't
1476allowed to include this header but your tests can. Such is called the Pimpl
1477(Private Implementation) idiom.
1478
1479Or, you can declare an individual test as a friend of your class by adding this
1480line in the class body:
1481
1482```
1483FRIEND_TEST(TestCaseName, TestName);
1484```
1485
1486For example,
1487```
1488// foo.h
1489#include "gtest/gtest_prod.h"
1490
1491// Defines FRIEND_TEST.
1492class Foo {
1493  ...
1494 private:
1495  FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
1496  int Bar(void* x);
1497};
1498
1499// foo_test.cc
1500...
1501TEST(FooTest, BarReturnsZeroOnNull) {
1502  Foo foo;
1503  EXPECT_EQ(0, foo.Bar(NULL));
1504  // Uses Foo's private member Bar().
1505}
1506```
1507
1508Pay special attention when your class is defined in a namespace, as you should
1509define your test fixtures and tests in the same namespace if you want them to
1510be friends of your class. For example, if the code to be tested looks like:
1511
1512```
1513namespace my_namespace {
1514
1515class Foo {
1516  friend class FooTest;
1517  FRIEND_TEST(FooTest, Bar);
1518  FRIEND_TEST(FooTest, Baz);
1519  ...
1520  definition of the class Foo
1521  ...
1522};
1523
1524}  // namespace my_namespace
1525```
1526
1527Your test code should be something like:
1528
1529```
1530namespace my_namespace {
1531class FooTest : public ::testing::Test {
1532 protected:
1533  ...
1534};
1535
1536TEST_F(FooTest, Bar) { ... }
1537TEST_F(FooTest, Baz) { ... }
1538
1539}  // namespace my_namespace
1540```
1541
1542# Catching Failures #
1543
1544If you are building a testing utility on top of Google Test, you'll
1545want to test your utility.  What framework would you use to test it?
1546Google Test, of course.
1547
1548The challenge is to verify that your testing utility reports failures
1549correctly.  In frameworks that report a failure by throwing an
1550exception, you could catch the exception and assert on it.  But Google
1551Test doesn't use exceptions, so how do we test that a piece of code
1552generates an expected failure?
1553
1554`"gtest/gtest-spi.h"` contains some constructs to do this.  After
1555#including this header, you can use
1556
1557| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` |
1558|:--------------------------------------------------|
1559
1560to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure
1561whose message contains the given _substring_, or use
1562
1563| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` |
1564|:-----------------------------------------------------|
1565
1566if you are expecting a non-fatal (e.g. `EXPECT_*`) failure.
1567
1568For technical reasons, there are some caveats:
1569
1570  1. You cannot stream a failure message to either macro.
1571  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object.
1572  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value.
1573
1574_Note:_ Google Test is designed with threads in mind.  Once the
1575synchronization primitives in `"gtest/internal/gtest-port.h"` have
1576been implemented, Google Test will become thread-safe, meaning that
1577you can then use assertions in multiple threads concurrently.  Before
1578
1579that, however, Google Test only supports single-threaded usage.  Once
1580thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()`
1581will capture failures in the current thread only. If _statement_
1582creates new threads, failures in these threads will be ignored.  If
1583you want to capture failures from all threads instead, you should use
1584the following macros:
1585
1586| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1587|:-----------------------------------------------------------------|
1588| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1589
1590# Getting the Current Test's Name #
1591
1592Sometimes a function may need to know the name of the currently running test.
1593For example, you may be using the `SetUp()` method of your test fixture to set
1594the golden file name based on which test is running. The `::testing::TestInfo`
1595class has this information:
1596
1597```
1598namespace testing {
1599
1600class TestInfo {
1601 public:
1602  // Returns the test case name and the test name, respectively.
1603  //
1604  // Do NOT delete or free the return value - it's managed by the
1605  // TestInfo class.
1606  const char* test_case_name() const;
1607  const char* name() const;
1608};
1609
1610}  // namespace testing
1611```
1612
1613
1614> To obtain a `TestInfo` object for the currently running test, call
1615`current_test_info()` on the `UnitTest` singleton object:
1616
1617```
1618// Gets information about the currently running test.
1619// Do NOT delete the returned object - it's managed by the UnitTest class.
1620const ::testing::TestInfo* const test_info =
1621  ::testing::UnitTest::GetInstance()->current_test_info();
1622printf("We are in test %s of test case %s.\n",
1623       test_info->name(), test_info->test_case_name());
1624```
1625
1626`current_test_info()` returns a null pointer if no test is running. In
1627particular, you cannot find the test case name in `TestCaseSetUp()`,
1628`TestCaseTearDown()` (where you know the test case name implicitly), or
1629functions called from them.
1630
1631_Availability:_ Linux, Windows, Mac.
1632
1633# Extending Google Test by Handling Test Events #
1634
1635Google Test provides an <b>event listener API</b> to let you receive
1636notifications about the progress of a test program and test
1637failures. The events you can listen to include the start and end of
1638the test program, a test case, or a test method, among others. You may
1639use this API to augment or replace the standard console output,
1640replace the XML output, or provide a completely different form of
1641output, such as a GUI or a database. You can also use test events as
1642checkpoints to implement a resource leak checker, for example.
1643
1644_Availability:_ Linux, Windows, Mac; since v1.4.0.
1645
1646## Defining Event Listeners ##
1647
1648To define a event listener, you subclass either
1649[testing::TestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#855)
1650or [testing::EmptyTestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#905).
1651The former is an (abstract) interface, where <i>each pure virtual method<br>
1652can be overridden to handle a test event</i> (For example, when a test
1653starts, the `OnTestStart()` method will be called.). The latter provides
1654an empty implementation of all methods in the interface, such that a
1655subclass only needs to override the methods it cares about.
1656
1657When an event is fired, its context is passed to the handler function
1658as an argument. The following argument types are used:
1659  * [UnitTest](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#1007) reflects the state of the entire test program,
1660  * [TestCase](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#689) has information about a test case, which can contain one or more tests,
1661  * [TestInfo](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#599) contains the state of a test, and
1662  * [TestPartResult](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-test-part.h#42) represents the result of a test assertion.
1663
1664An event handler function can examine the argument it receives to find
1665out interesting information about the event and the test program's
1666state.  Here's an example:
1667
1668```
1669  class MinimalistPrinter : public ::testing::EmptyTestEventListener {
1670    // Called before a test starts.
1671    virtual void OnTestStart(const ::testing::TestInfo& test_info) {
1672      printf("*** Test %s.%s starting.\n",
1673             test_info.test_case_name(), test_info.name());
1674    }
1675
1676    // Called after a failed assertion or a SUCCEED() invocation.
1677    virtual void OnTestPartResult(
1678        const ::testing::TestPartResult& test_part_result) {
1679      printf("%s in %s:%d\n%s\n",
1680             test_part_result.failed() ? "*** Failure" : "Success",
1681             test_part_result.file_name(),
1682             test_part_result.line_number(),
1683             test_part_result.summary());
1684    }
1685
1686    // Called after a test ends.
1687    virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
1688      printf("*** Test %s.%s ending.\n",
1689             test_info.test_case_name(), test_info.name());
1690    }
1691  };
1692```
1693
1694## Using Event Listeners ##
1695
1696To use the event listener you have defined, add an instance of it to
1697the Google Test event listener list (represented by class
1698[TestEventListeners](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#929)
1699- note the "s" at the end of the name) in your
1700`main()` function, before calling `RUN_ALL_TESTS()`:
1701```
1702int main(int argc, char** argv) {
1703  ::testing::InitGoogleTest(&argc, argv);
1704  // Gets hold of the event listener list.
1705  ::testing::TestEventListeners& listeners =
1706      ::testing::UnitTest::GetInstance()->listeners();
1707  // Adds a listener to the end.  Google Test takes the ownership.
1708  listeners.Append(new MinimalistPrinter);
1709  return RUN_ALL_TESTS();
1710}
1711```
1712
1713There's only one problem: the default test result printer is still in
1714effect, so its output will mingle with the output from your minimalist
1715printer. To suppress the default printer, just release it from the
1716event listener list and delete it. You can do so by adding one line:
1717```
1718  ...
1719  delete listeners.Release(listeners.default_result_printer());
1720  listeners.Append(new MinimalistPrinter);
1721  return RUN_ALL_TESTS();
1722```
1723
1724Now, sit back and enjoy a completely different output from your
1725tests. For more details, you can read this
1726[sample](http://code.google.com/p/googletest/source/browse/trunk/samples/sample9_unittest.cc).
1727
1728You may append more than one listener to the list. When an `On*Start()`
1729or `OnTestPartResult()` event is fired, the listeners will receive it in
1730the order they appear in the list (since new listeners are added to
1731the end of the list, the default text printer and the default XML
1732generator will receive the event first). An `On*End()` event will be
1733received by the listeners in the _reverse_ order. This allows output by
1734listeners added later to be framed by output from listeners added
1735earlier.
1736
1737## Generating Failures in Listeners ##
1738
1739You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`,
1740`FAIL()`, etc) when processing an event. There are some restrictions:
1741
1742  1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively).
1743  1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure.
1744
1745When you add listeners to the listener list, you should put listeners
1746that handle `OnTestPartResult()` _before_ listeners that can generate
1747failures. This ensures that failures generated by the latter are
1748attributed to the right test by the former.
1749
1750We have a sample of failure-raising listener
1751[here](http://code.google.com/p/googletest/source/browse/trunk/samples/sample10_unittest.cc).
1752
1753# Running Test Programs: Advanced Options #
1754
1755Google Test test programs are ordinary executables. Once built, you can run
1756them directly and affect their behavior via the following environment variables
1757and/or command line flags. For the flags to work, your programs must call
1758`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
1759
1760To see a list of supported flags and their usage, please run your test
1761program with the `--help` flag.  You can also use `-h`, `-?`, or `/?`
1762for short.  This feature is added in version 1.3.0.
1763
1764If an option is specified both by an environment variable and by a
1765flag, the latter takes precedence.  Most of the options can also be
1766set/read in code: to access the value of command line flag
1767`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`.  A common pattern is
1768to set the value of a flag before calling `::testing::InitGoogleTest()`
1769to change the default value of the flag:
1770```
1771int main(int argc, char** argv) {
1772  // Disables elapsed time by default.
1773  ::testing::GTEST_FLAG(print_time) = false;
1774
1775  // This allows the user to override the flag on the command line.
1776  ::testing::InitGoogleTest(&argc, argv);
1777
1778  return RUN_ALL_TESTS();
1779}
1780```
1781
1782## Selecting Tests ##
1783
1784This section shows various options for choosing which tests to run.
1785
1786### Listing Test Names ###
1787
1788Sometimes it is necessary to list the available tests in a program before
1789running them so that a filter may be applied if needed. Including the flag
1790`--gtest_list_tests` overrides all other flags and lists tests in the following
1791format:
1792```
1793TestCase1.
1794  TestName1
1795  TestName2
1796TestCase2.
1797  TestName
1798```
1799
1800None of the tests listed are actually run if the flag is provided. There is no
1801corresponding environment variable for this flag.
1802
1803_Availability:_ Linux, Windows, Mac.
1804
1805### Running a Subset of the Tests ###
1806
1807By default, a Google Test program runs all tests the user has defined.
1808Sometimes, you want to run only a subset of the tests (e.g. for debugging or
1809quickly verifying a change). If you set the `GTEST_FILTER` environment variable
1810or the `--gtest_filter` flag to a filter string, Google Test will only run the
1811tests whose full names (in the form of `TestCaseName.TestName`) match the
1812filter.
1813
1814The format of a filter is a '`:`'-separated list of wildcard patterns (called
1815the positive patterns) optionally followed by a '`-`' and another
1816'`:`'-separated pattern list (called the negative patterns). A test matches the
1817filter if and only if it matches any of the positive patterns but does not
1818match any of the negative patterns.
1819
1820A pattern may contain `'*'` (matches any string) or `'?'` (matches any single
1821character). For convenience, the filter `'*-NegativePatterns'` can be also
1822written as `'-NegativePatterns'`.
1823
1824For example:
1825
1826  * `./foo_test` Has no flag, and thus runs all its tests.
1827  * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value.
1828  * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`.
1829  * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`.
1830  * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.
1831  * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`.
1832
1833_Availability:_ Linux, Windows, Mac.
1834
1835### Temporarily Disabling Tests ###
1836
1837If you have a broken test that you cannot fix right away, you can add the
1838`DISABLED_` prefix to its name. This will exclude it from execution. This is
1839better than commenting out the code or using `#if 0`, as disabled tests are
1840still compiled (and thus won't rot).
1841
1842If you need to disable all tests in a test case, you can either add `DISABLED_`
1843to the front of the name of each test, or alternatively add it to the front of
1844the test case name.
1845
1846For example, the following tests won't be run by Google Test, even though they
1847will still be compiled:
1848
1849```
1850// Tests that Foo does Abc.
1851TEST(FooTest, DISABLED_DoesAbc) { ... }
1852
1853class DISABLED_BarTest : public ::testing::Test { ... };
1854
1855// Tests that Bar does Xyz.
1856TEST_F(DISABLED_BarTest, DoesXyz) { ... }
1857```
1858
1859_Note:_ This feature should only be used for temporary pain-relief. You still
1860have to fix the disabled tests at a later date. As a reminder, Google Test will
1861print a banner warning you if a test program contains any disabled tests.
1862
1863_Tip:_ You can easily count the number of disabled tests you have
1864using `grep`. This number can be used as a metric for improving your
1865test quality.
1866
1867_Availability:_ Linux, Windows, Mac.
1868
1869### Temporarily Enabling Disabled Tests ###
1870
1871To include [disabled tests](#Temporarily_Disabling_Tests.md) in test
1872execution, just invoke the test program with the
1873`--gtest_also_run_disabled_tests` flag or set the
1874`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other
1875than `0`.  You can combine this with the
1876[--gtest\_filter](#Running_a_Subset_of_the_Tests.md) flag to further select
1877which disabled tests to run.
1878
1879_Availability:_ Linux, Windows, Mac; since version 1.3.0.
1880
1881## Repeating the Tests ##
1882
1883Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
1884will fail only 1% of the time, making it rather hard to reproduce the bug under
1885a debugger. This can be a major source of frustration.
1886
1887The `--gtest_repeat` flag allows you to repeat all (or selected) test methods
1888in a program many times. Hopefully, a flaky test will eventually fail and give
1889you a chance to debug. Here's how to use it:
1890
1891| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. |
1892|:---------------------------------|:--------------------------------------------------------|
1893| `$ foo_test --gtest_repeat=-1`   | A negative count means repeating forever.               |
1894| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. |
1895| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. |
1896
1897If your test program contains global set-up/tear-down code registered
1898using `AddGlobalTestEnvironment()`, it will be repeated in each
1899iteration as well, as the flakiness may be in it. You can also specify
1900the repeat count by setting the `GTEST_REPEAT` environment variable.
1901
1902_Availability:_ Linux, Windows, Mac.
1903
1904## Shuffling the Tests ##
1905
1906You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
1907environment variable to `1`) to run the tests in a program in a random
1908order. This helps to reveal bad dependencies between tests.
1909
1910By default, Google Test uses a random seed calculated from the current
1911time. Therefore you'll get a different order every time. The console
1912output includes the random seed value, such that you can reproduce an
1913order-related test failure later. To specify the random seed
1914explicitly, use the `--gtest_random_seed=SEED` flag (or set the
1915`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer
1916between 0 and 99999. The seed value 0 is special: it tells Google Test
1917to do the default behavior of calculating the seed from the current
1918time.
1919
1920If you combine this with `--gtest_repeat=N`, Google Test will pick a
1921different random seed and re-shuffle the tests in each iteration.
1922
1923_Availability:_ Linux, Windows, Mac; since v1.4.0.
1924
1925## Controlling Test Output ##
1926
1927This section teaches how to tweak the way test results are reported.
1928
1929### Colored Terminal Output ###
1930
1931Google Test can use colors in its terminal output to make it easier to spot
1932the separation between tests, and whether tests passed.
1933
1934You can set the GTEST\_COLOR environment variable or set the `--gtest_color`
1935command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
1936disable colors, or let Google Test decide. When the value is `auto`, Google
1937Test will use colors if and only if the output goes to a terminal and (on
1938non-Windows platforms) the `TERM` environment variable is set to `xterm` or
1939`xterm-color`.
1940
1941_Availability:_ Linux, Windows, Mac.
1942
1943### Suppressing the Elapsed Time ###
1944
1945By default, Google Test prints the time it takes to run each test.  To
1946suppress that, run the test program with the `--gtest_print_time=0`
1947command line flag.  Setting the `GTEST_PRINT_TIME` environment
1948variable to `0` has the same effect.
1949
1950_Availability:_ Linux, Windows, Mac.  (In Google Test 1.3.0 and lower,
1951the default behavior is that the elapsed time is **not** printed.)
1952
1953### Generating an XML Report ###
1954
1955Google Test can emit a detailed XML report to a file in addition to its normal
1956textual output. The report contains the duration of each test, and thus can
1957help you identify slow tests.
1958
1959To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
1960`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will
1961create the file at the given location. You can also just use the string
1962`"xml"`, in which case the output can be found in the `test_detail.xml` file in
1963the current directory.
1964
1965If you specify a directory (for example, `"xml:output/directory/"` on Linux or
1966`"xml:output\directory\"` on Windows), Google Test will create the XML file in
1967that directory, named after the test executable (e.g. `foo_test.xml` for test
1968program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
1969over from a previous run), Google Test will pick a different name (e.g.
1970`foo_test_1.xml`) to avoid overwriting it.
1971
1972The report uses the format described here.  It is based on the
1973`junitreport` Ant task and can be parsed by popular continuous build
1974systems like [Hudson](https://hudson.dev.java.net/). Since that format
1975was originally intended for Java, a little interpretation is required
1976to make it apply to Google Test tests, as shown here:
1977
1978```
1979<testsuites name="AllTests" ...>
1980  <testsuite name="test_case_name" ...>
1981    <testcase name="test_name" ...>
1982      <failure message="..."/>
1983      <failure message="..."/>
1984      <failure message="..."/>
1985    </testcase>
1986  </testsuite>
1987</testsuites>
1988```
1989
1990  * The root `<testsuites>` element corresponds to the entire test program.
1991  * `<testsuite>` elements correspond to Google Test test cases.
1992  * `<testcase>` elements correspond to Google Test test functions.
1993
1994For instance, the following program
1995
1996```
1997TEST(MathTest, Addition) { ... }
1998TEST(MathTest, Subtraction) { ... }
1999TEST(LogicTest, NonContradiction) { ... }
2000```
2001
2002could generate this report:
2003
2004```
2005<?xml version="1.0" encoding="UTF-8"?>
2006<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests">
2007  <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15">
2008    <testcase name="Addition" status="run" time="7" classname="">
2009      <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type=""/>
2010      <failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type=""/>
2011    </testcase>
2012    <testcase name="Subtraction" status="run" time="5" classname="">
2013    </testcase>
2014  </testsuite>
2015  <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5">
2016    <testcase name="NonContradiction" status="run" time="5" classname="">
2017    </testcase>
2018  </testsuite>
2019</testsuites>
2020```
2021
2022Things to note:
2023
2024  * The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed.
2025  * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds.
2026  * Each `<failure>` element corresponds to a single failed Google Test assertion.
2027  * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts.
2028
2029_Availability:_ Linux, Windows, Mac.
2030
2031## Controlling How Failures Are Reported ##
2032
2033### Turning Assertion Failures into Break-Points ###
2034
2035When running test programs under a debugger, it's very convenient if the
2036debugger can catch an assertion failure and automatically drop into interactive
2037mode. Google Test's _break-on-failure_ mode supports this behavior.
2038
2039To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
2040other than `0` . Alternatively, you can use the `--gtest_break_on_failure`
2041command line flag.
2042
2043_Availability:_ Linux, Windows, Mac.
2044
2045### Disabling Catching Test-Thrown Exceptions ###
2046
2047Google Test can be used either with or without exceptions enabled.  If
2048a test throws a C++ exception or (on Windows) a structured exception
2049(SEH), by default Google Test catches it, reports it as a test
2050failure, and continues with the next test method.  This maximizes the
2051coverage of a test run.  Also, on Windows an uncaught exception will
2052cause a pop-up window, so catching the exceptions allows you to run
2053the tests automatically.
2054
2055When debugging the test failures, however, you may instead want the
2056exceptions to be handled by the debugger, such that you can examine
2057the call stack when an exception is thrown.  To achieve that, set the
2058`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the
2059`--gtest_catch_exceptions=0` flag when running the tests.
2060
2061**Availability**: Linux, Windows, Mac.
2062
2063### Letting Another Testing Framework Drive ###
2064
2065If you work on a project that has already been using another testing
2066framework and is not ready to completely switch to Google Test yet,
2067you can get much of Google Test's benefit by using its assertions in
2068your existing tests.  Just change your `main()` function to look
2069like:
2070
2071```
2072#include "gtest/gtest.h"
2073
2074int main(int argc, char** argv) {
2075  ::testing::GTEST_FLAG(throw_on_failure) = true;
2076  // Important: Google Test must be initialized.
2077  ::testing::InitGoogleTest(&argc, argv);
2078
2079  ... whatever your existing testing framework requires ...
2080}
2081```
2082
2083With that, you can use Google Test assertions in addition to the
2084native assertions your testing framework provides, for example:
2085
2086```
2087void TestFooDoesBar() {
2088  Foo foo;
2089  EXPECT_LE(foo.Bar(1), 100);     // A Google Test assertion.
2090  CPPUNIT_ASSERT(foo.IsEmpty());  // A native assertion.
2091}
2092```
2093
2094If a Google Test assertion fails, it will print an error message and
2095throw an exception, which will be treated as a failure by your host
2096testing framework.  If you compile your code with exceptions disabled,
2097a failed Google Test assertion will instead exit your program with a
2098non-zero code, which will also signal a test failure to your test
2099runner.
2100
2101If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in
2102your `main()`, you can alternatively enable this feature by specifying
2103the `--gtest_throw_on_failure` flag on the command-line or setting the
2104`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value.
2105
2106Death tests are _not_ supported when other test framework is used to organize tests.
2107
2108_Availability:_ Linux, Windows, Mac; since v1.3.0.
2109
2110## Distributing Test Functions to Multiple Machines ##
2111
2112If you have more than one machine you can use to run a test program,
2113you might want to run the test functions in parallel and get the
2114result faster.  We call this technique _sharding_, where each machine
2115is called a _shard_.
2116
2117Google Test is compatible with test sharding.  To take advantage of
2118this feature, your test runner (not part of Google Test) needs to do
2119the following:
2120
2121  1. Allocate a number of machines (shards) to run the tests.
2122  1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards.  It must be the same for all shards.
2123  1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard.  Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`.
2124  1. Run the same test program on all shards.  When Google Test sees the above two environment variables, it will select a subset of the test functions to run.  Across all shards, each test function in the program will be run exactly once.
2125  1. Wait for all shards to finish, then collect and report the results.
2126
2127Your project may have tests that were written without Google Test and
2128thus don't understand this protocol.  In order for your test runner to
2129figure out which test supports sharding, it can set the environment
2130variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path.  If a
2131test program supports sharding, it will create this file to
2132acknowledge the fact (the actual contents of the file are not
2133important at this time; although we may stick some useful information
2134in it in the future.); otherwise it will not create it.
2135
2136Here's an example to make it clear.  Suppose you have a test program
2137`foo_test` that contains the following 5 test functions:
2138```
2139TEST(A, V)
2140TEST(A, W)
2141TEST(B, X)
2142TEST(B, Y)
2143TEST(B, Z)
2144```
2145and you have 3 machines at your disposal.  To run the test functions in
2146parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and
2147set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively.
2148Then you would run the same `foo_test` on each machine.
2149
2150Google Test reserves the right to change how the work is distributed
2151across the shards, but here's one possible scenario:
2152
2153  * Machine #0 runs `A.V` and `B.X`.
2154  * Machine #1 runs `A.W` and `B.Y`.
2155  * Machine #2 runs `B.Z`.
2156
2157_Availability:_ Linux, Windows, Mac; since version 1.3.0.
2158
2159# Fusing Google Test Source Files #
2160
2161Google Test's implementation consists of ~30 files (excluding its own
2162tests).  Sometimes you may want them to be packaged up in two files (a
2163`.h` and a `.cc`) instead, such that you can easily copy them to a new
2164machine and start hacking there.  For this we provide an experimental
2165Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0).
2166Assuming you have Python 2.4 or above installed on your machine, just
2167go to that directory and run
2168```
2169python fuse_gtest_files.py OUTPUT_DIR
2170```
2171
2172and you should see an `OUTPUT_DIR` directory being created with files
2173`gtest/gtest.h` and `gtest/gtest-all.cc` in it.  These files contain
2174everything you need to use Google Test.  Just copy them to anywhere
2175you want and you are ready to write tests.  You can use the
2176[scripts/test/Makefile](http://code.google.com/p/googletest/source/browse/trunk/scripts/test/Makefile)
2177file as an example on how to compile your tests against them.
2178
2179# Where to Go from Here #
2180
2181Congratulations! You've now learned more advanced Google Test tools and are
2182ready to tackle more complex testing tasks. If you want to dive even deeper, you
2183can read the [Frequently-Asked Questions](FAQ.md).
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/DevGuide.md
r0r249096
1
2
3If you are interested in understanding the internals of Google Test,
4building from source, or contributing ideas or modifications to the
5project, then this document is for you.
6
7# Introduction #
8
9First, let's give you some background of the project.
10
11## Licensing ##
12
13All Google Test source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php).
14
15## The Google Test Community ##
16
17The Google Test community exists primarily through the [discussion group](http://groups.google.com/group/googletestframework), the
18[issue tracker](http://code.google.com/p/googletest/issues/list) and, to a lesser extent, the [source control repository](http://code.google.com/p/googletest/source/checkout). You are definitely encouraged to contribute to the
19discussion and you can also help us to keep the effectiveness of the
20group high by following and promoting the guidelines listed here.
21
22### Please Be Friendly ###
23
24Showing courtesy and respect to others is a vital part of the Google
25culture, and we strongly encourage everyone participating in Google
26Test development to join us in accepting nothing less. Of course,
27being courteous is not the same as failing to constructively disagree
28with each other, but it does mean that we should be respectful of each
29other when enumerating the 42 technical reasons that a particular
30proposal may not be the best choice. There's never a reason to be
31antagonistic or dismissive toward anyone who is sincerely trying to
32contribute to a discussion.
33
34Sure, C++ testing is serious business and all that, but it's also
35a lot of fun. Let's keep it that way. Let's strive to be one of the
36friendliest communities in all of open source.
37
38### Where to Discuss Google Test ###
39
40As always, discuss Google Test in the official [Google C++ Testing Framework discussion group](http://groups.google.com/group/googletestframework).  You don't have to actually submit
41code in order to sign up. Your participation itself is a valuable
42contribution.
43
44# Working with the Code #
45
46If you want to get your hands dirty with the code inside Google Test,
47this is the section for you.
48
49## Checking Out the Source from Subversion ##
50
51Checking out the Google Test source is most useful if you plan to
52tweak it yourself.  You check out the source for Google Test using a
53[Subversion](http://subversion.tigris.org/) client as you would for any
54other project hosted on Google Code.  Please see the instruction on
55the [source code access page](http://code.google.com/p/googletest/source/checkout) for how to do it.
56
57## Compiling from Source ##
58
59Once you check out the code, you can find instructions on how to
60compile it in the [README](http://code.google.com/p/googletest/source/browse/trunk/README) file.
61
62## Testing ##
63
64A testing framework is of no good if itself is not thoroughly tested.
65Tests should be written for any new code, and changes should be
66verified to not break existing tests before they are submitted for
67review. To perform the tests, follow the instructions in [README](http://code.google.com/p/googletest/source/browse/trunk/README) and
68verify that there are no failures.
69
70# Contributing Code #
71
72We are excited that Google Test is now open source, and hope to get
73great patches from the community. Before you fire up your favorite IDE
74and begin hammering away at that new feature, though, please take the
75time to read this section and understand the process. While it seems
76rigorous, we want to keep a high standard of quality in the code
77base.
78
79## Contributor License Agreements ##
80
81You must sign a Contributor License Agreement (CLA) before we can
82accept any code.  The CLA protects you and us.
83
84  * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html).
85  * If you work for a company that wants to allow you to contribute your work to Google Test, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html).
86
87Follow either of the two links above to access the appropriate CLA and
88instructions for how to sign and return it.
89
90## Coding Style ##
91
92To keep the source consistent, readable, diffable and easy to merge,
93we use a fairly rigid coding style, as defined by the [google-styleguide](http://code.google.com/p/google-styleguide/) project.  All patches will be expected
94to conform to the style outlined [here](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
95
96## Updating Generated Code ##
97
98Some of Google Test's source files are generated by the Pump tool (a
99Python script).  If you need to update such files, please modify the
100source (`foo.h.pump`) and re-generate the C++ file using Pump.  You
101can read the PumpManual for details.
102
103## Submitting Patches ##
104
105Please do submit code. Here's what you need to do:
106
107  1. Normally you should make your change against the SVN trunk instead of a branch or a tag, as the latter two are for release control and should be treated mostly as read-only.
108  1. Decide which code you want to submit. A submission should be a set of changes that addresses one issue in the [Google Test issue tracker](http://code.google.com/p/googletest/issues/list). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one.
109  1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches.
110  1. Ensure that your code adheres to the [Google Test source code style](#Coding_Style.md).
111  1. Ensure that there are unit tests for your code.
112  1. Sign a Contributor License Agreement.
113  1. Create a patch file using `svn diff`.
114  1. We use [Rietveld](http://codereview.appspot.com/) to do web-based code reviews.  You can read about the tool [here](http://code.google.com/p/rietveld/wiki/CodeReviewHelp).  When you are ready, upload your patch via Rietveld and notify `googletestframework@googlegroups.com` to review it.  There are several ways to upload the patch.  We recommend using the [upload\_gtest.py](http://code.google.com/p/googletest/source/browse/trunk/scripts/upload_gtest.py) script, which you can find in the `scripts/` folder in the SVN trunk.
115
116## Google Test Committers ##
117
118The current members of the Google Test engineering team are the only
119committers at present. In the great tradition of eating one's own
120dogfood, we will be requiring each new Google Test engineering team
121member to earn the right to become a committer by following the
122procedures in this document, writing consistently great code, and
123demonstrating repeatedly that he or she truly gets the zen of Google
124Test.
125
126# Release Process #
127
128We follow the typical release process for Subversion-based projects:
129
130  1. A release branch named `release-X.Y` is created.
131  1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable.
132  1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch.
133  1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time).
134  1. Go back to step 1 to create another release branch and so on.
135
136
137---
138
139This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project.  Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/).
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/Documentation.md
r0r249096
1This page lists all documentation wiki pages for Google Test **(the SVN trunk version)**
2-- **if you use a released version of Google Test, please read the
3documentation for that specific version instead.**
4
5  * [Primer](Primer.md) -- start here if you are new to Google Test.
6  * [Samples](Samples.md) -- learn from examples.
7  * [AdvancedGuide](AdvancedGuide.md) -- learn more about Google Test.
8  * [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac.
9  * [Frequently-Asked Questions](FAQ.md) -- check here before asking a question on the mailing list.
10
11To contribute code to Google Test, read:
12
13  * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch.
14  * [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/FAQ.md
r0r249096
1
2
3If you cannot find the answer to your question here, and you have read
4[Primer](Primer.md) and [AdvancedGuide](AdvancedGuide.md), send it to
5googletestframework@googlegroups.com.
6
7## Why should I use Google Test instead of my favorite C++ testing framework? ##
8
9First, let us say clearly that we don't want to get into the debate of
10which C++ testing framework is **the best**.  There exist many fine
11frameworks for writing C++ tests, and we have tremendous respect for
12the developers and users of them.  We don't think there is (or will
13be) a single best framework - you have to pick the right tool for the
14particular task you are tackling.
15
16We created Google Test because we couldn't find the right combination
17of features and conveniences in an existing framework to satisfy _our_
18needs.  The following is a list of things that _we_ like about Google
19Test.  We don't claim them to be unique to Google Test - rather, the
20combination of them makes Google Test the choice for us.  We hope this
21list can help you decide whether it is for you too.
22
23  * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc.  As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems.
24  * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle.
25  * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`.  It doesn't require a new set of macros or special functions.
26  * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them.
27  * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions.
28  * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop.
29  * You can decide which tests to run using name patterns.  This saves time when you want to quickly reproduce a test failure.
30  * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson.
31  * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](http://code.google.com/p/googletest/wiki/AdvancedGuide#Global_Set-Up_and_Tear-Down) and tests parameterized by [values](http://code.google.com/p/googletest/wiki/AdvancedGuide#Value_Parameterized_Tests) or [types](http://code.google.com/p/googletest/wiki/AdvancedGuide#Typed_Tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself.  In particular, you can:
32    * expand your testing vocabulary by defining [custom predicates](http://code.google.com/p/googletest/wiki/AdvancedGuide#Predicate_Assertions_for_Better_Error_Messages),
33    * teach Google Test how to [print your types](http://code.google.com/p/googletest/wiki/AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values),
34    * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](http://code.google.com/p/googletest/wiki/AdvancedGuide#Catching_Failures), and
35    * reflect on the test cases or change the test output format by intercepting the [test events](http://code.google.com/p/googletest/wiki/AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events).
36
37## I'm getting warnings when compiling Google Test.  Would you fix them? ##
38
39We strive to minimize compiler warnings Google Test generates.  Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS.
40
41Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment:
42
43  * You may be using a different compiler as we use, or a different version of the same compiler.  We cannot possibly test for all compilers.
44  * You may be compiling on a different platform as we do.
45  * Your project may be using different compiler flags as we do.
46
47It is not always possible to make Google Test warning-free for everyone.  Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex.
48
49If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers.  That'll suppress warnings from Google Test headers.
50
51## Why should not test case names and test names contain underscore? ##
52
53Underscore (`_`) is special, as C++ reserves the following to be used by
54the compiler and the standard library:
55
56  1. any identifier that starts with an `_` followed by an upper-case letter, and
57  1. any identifier that containers two consecutive underscores (i.e. `__`) _anywhere_ in its name.
58
59User code is _prohibited_ from using such identifiers.
60
61Now let's look at what this means for `TEST` and `TEST_F`.
62
63Currently `TEST(TestCaseName, TestName)` generates a class named
64`TestCaseName_TestName_Test`.  What happens if `TestCaseName` or `TestName`
65contains `_`?
66
67  1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid.
68  1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid.
69  1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid.
70  1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid.
71
72So clearly `TestCaseName` and `TestName` cannot start or end with `_`
73(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't
74followed by an upper-case letter.  But that's getting complicated.  So
75for simplicity we just say that it cannot start with `_`.).
76
77It may seem fine for `TestCaseName` and `TestName` to contain `_` in the
78middle.  However, consider this:
79```
80TEST(Time, Flies_Like_An_Arrow) { ... }
81TEST(Time_Flies, Like_An_Arrow) { ... }
82```
83
84Now, the two `TEST`s will both generate the same class
85(`Time_Files_Like_An_Arrow_Test`).  That's not good.
86
87So for simplicity, we just ask the users to avoid `_` in `TestCaseName`
88and `TestName`.  The rule is more constraining than necessary, but it's
89simple and easy to remember.  It also gives Google Test some wiggle
90room in case its implementation needs to change in the future.
91
92If you violate the rule, there may not be immediately consequences,
93but your test may (just may) break with a new compiler (or a new
94version of the compiler you are using) or with a new version of Google
95Test.  Therefore it's best to follow the rule.
96
97## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ##
98
99In the early days, we said that you could install
100compiled Google Test libraries on `*`nix systems using `make install`.
101Then every user of your machine can write tests without
102recompiling Google Test.
103
104This seemed like a good idea, but it has a
105got-cha: every user needs to compile his tests using the _same_ compiler
106flags used to compile the installed Google Test libraries; otherwise
107he may run into undefined behaviors (i.e. the tests can behave
108strangely and may even crash for no obvious reasons).
109
110Why?  Because C++ has this thing called the One-Definition Rule: if
111two C++ source files contain different definitions of the same
112class/function/variable, and you link them together, you violate the
113rule.  The linker may or may not catch the error (in many cases it's
114not required by the C++ standard to catch the violation).  If it
115doesn't, you get strange run-time behaviors that are unexpected and
116hard to debug.
117
118If you compile Google Test and your test code using different compiler
119flags, they may see different definitions of the same
120class/function/variable (e.g. due to the use of `#if` in Google Test).
121Therefore, for your sanity, we recommend to avoid installing pre-compiled
122Google Test libraries.  Instead, each project should compile
123Google Test itself such that it can be sure that the same flags are
124used for both Google Test and the tests.
125
126## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ##
127
128(Answered by Trevor Robinson)
129
130Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or
131`msvc\gtest.sln`. Go through the migration wizard to migrate the
132solution and project files to Visual Studio 2008. Select
133`Configuration Manager...` from the `Build` menu. Select `<New...>` from
134the `Active solution platform` dropdown.  Select `x64` from the new
135platform dropdown, leave `Copy settings from` set to `Win32` and
136`Create new project platforms` checked, then click `OK`. You now have
137`Win32` and `x64` platform configurations, selectable from the
138`Standard` toolbar, which allow you to toggle between building 32-bit or
13964-bit binaries (or both at once using Batch Build).
140
141In order to prevent build output files from overwriting one another,
142you'll need to change the `Intermediate Directory` settings for the
143newly created platform configuration across all the projects. To do
144this, multi-select (e.g. using shift-click) all projects (but not the
145solution) in the `Solution Explorer`. Right-click one of them and
146select `Properties`. In the left pane, select `Configuration Properties`,
147and from the `Configuration` dropdown, select `All Configurations`.
148Make sure the selected platform is `x64`. For the
149`Intermediate Directory` setting, change the value from
150`$(PlatformName)\$(ConfigurationName)` to
151`$(OutDir)\$(ProjectName)`. Click `OK` and then build the
152solution. When the build is complete, the 64-bit binaries will be in
153the `msvc\x64\Debug` directory.
154
155## Can I use Google Test on MinGW? ##
156
157We haven't tested this ourselves, but Per Abrahamsen reported that he
158was able to compile and install Google Test successfully when using
159MinGW from Cygwin.  You'll need to configure it with:
160
161`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"`
162
163You should be able to replace the `-mno-cygwin` option with direct links
164to the real MinGW binaries, but we haven't tried that.
165
166Caveats:
167
168  * There are many warnings when compiling.
169  * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW.
170
171We also have reports on successful cross compilation of Google Test
172MinGW binaries on Linux using
173[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows)
174on the WxWidgets site.
175
176Please contact `googletestframework@googlegroups.com` if you are
177interested in improving the support for MinGW.
178
179## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ##
180
181Due to some peculiarity of C++, it requires some non-trivial template
182meta programming tricks to support using `NULL` as an argument of the
183`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where
184it's most needed (otherwise we make the implementation of Google Test
185harder to maintain and more error-prone than necessary).
186
187The `EXPECT_EQ()` macro takes the _expected_ value as its first
188argument and the _actual_ value as the second. It's reasonable that
189someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this
190indeed was requested several times. Therefore we implemented it.
191
192The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the
193assertion fails, you already know that `ptr` must be `NULL`, so it
194doesn't add any information to print ptr in this case. That means
195`EXPECT_TRUE(ptr != NULL)` works just as well.
196
197If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll
198have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`,
199we don't have a convention on the order of the two arguments for
200`EXPECT_NE`. This means using the template meta programming tricks
201twice in the implementation, making it even harder to understand and
202maintain. We believe the benefit doesn't justify the cost.
203
204Finally, with the growth of Google Mock's [matcher](http://code.google.com/p/googlemock/wiki/CookBook#Using_Matchers_in_Google_Test_Assertions) library, we are
205encouraging people to use the unified `EXPECT_THAT(value, matcher)`
206syntax more often in tests. One significant advantage of the matcher
207approach is that matchers can be easily combined to form new matchers,
208while the `EXPECT_NE`, etc, macros cannot be easily
209combined. Therefore we want to invest more in the matchers than in the
210`EXPECT_XX()` macros.
211
212## Does Google Test support running tests in parallel? ##
213
214Test runners tend to be tightly coupled with the build/test
215environment, and Google Test doesn't try to solve the problem of
216running tests in parallel.  Instead, we tried to make Google Test work
217nicely with test runners.  For example, Google Test's XML report
218contains the time spent on each test, and its `gtest_list_tests` and
219`gtest_filter` flags can be used for splitting the execution of test
220methods into multiple processes.  These functionalities can help the
221test runner run the tests in parallel.
222
223## Why don't Google Test run the tests in different threads to speed things up? ##
224
225It's difficult to write thread-safe code.  Most tests are not written
226with thread-safety in mind, and thus may not work correctly in a
227multi-threaded setting.
228
229If you think about it, it's already hard to make your code work when
230you know what other threads are doing.  It's much harder, and
231sometimes even impossible, to make your code work when you don't know
232what other threads are doing (remember that test methods can be added,
233deleted, or modified after your test was written).  If you want to run
234the tests in parallel, you'd better run them in different processes.
235
236## Why aren't Google Test assertions implemented using exceptions? ##
237
238Our original motivation was to be able to use Google Test in projects
239that disable exceptions.  Later we realized some additional benefits
240of this approach:
241
242  1. Throwing in a destructor is undefined behavior in C++.  Not using exceptions means Google Test's assertions are safe to use in destructors.
243  1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing.
244  1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code:
245```
246try { ... ASSERT_TRUE(...) ... }
247catch (...) { ... }
248```
249The above code will pass even if the `ASSERT_TRUE` throws.  While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test.
250
251The downside of not using exceptions is that `ASSERT_*` (implemented
252using `return`) will only abort the current function, not the current
253`TEST`.
254
255## Why do we use two different macros for tests with and without fixtures? ##
256
257Unfortunately, C++'s macro system doesn't allow us to use the same
258macro for both cases.  One possibility is to provide only one macro
259for tests with fixtures, and require the user to define an empty
260fixture sometimes:
261
262```
263class FooTest : public ::testing::Test {};
264
265TEST_F(FooTest, DoesThis) { ... }
266```
267or
268```
269typedef ::testing::Test FooTest;
270
271TEST_F(FooTest, DoesThat) { ... }
272```
273
274Yet, many people think this is one line too many. :-) Our goal was to
275make it really easy to write tests, so we tried to make simple tests
276trivial to create.  That means using a separate macro for such tests.
277
278We think neither approach is ideal, yet either of them is reasonable.
279In the end, it probably doesn't matter much either way.
280
281## Why don't we use structs as test fixtures? ##
282
283We like to use structs only when representing passive data.  This
284distinction between structs and classes is good for documenting the
285intent of the code's author.  Since test fixtures have logic like
286`SetUp()` and `TearDown()`, they are better defined as classes.
287
288## Why are death tests implemented as assertions instead of using a test runner? ##
289
290Our goal was to make death tests as convenient for a user as C++
291possibly allows.  In particular:
292
293  * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect.  The death test would be written in C++, while the runner spec may or may not be.  A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative.
294  * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn.
295  * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will.  You are not limited to one death test per test method. For example, you can write something like:
296```
297    if (FooCondition()) {
298      ASSERT_DEATH(Bar(), "blah");
299    } else {
300      ASSERT_EQ(5, Bar());
301    }
302```
303If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users.  The fewer artificial limitations the better.
304  * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information.  For example,
305```
306    const int count = GetCount();  // Only known at run time.
307    for (int i = 1; i <= count; i++) {
308      ASSERT_DEATH({
309        double* buffer = new double[i];
310        ... initializes buffer ...
311        Foo(buffer, i)
312      }, "blah blah");
313    }
314```
315The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility.
316
317Another interesting thing about `ASSERT_DEATH` is that it calls `fork()`
318to create a child process to run the death test.  This is lightening
319fast, as `fork()` uses copy-on-write pages and incurs almost zero
320overhead, and the child process starts from the user-supplied
321statement directly, skipping all global and local initialization and
322any code leading to the given statement.  If you launch the child
323process from scratch, it can take seconds just to load everything and
324start running if the test links to many libraries dynamically.
325
326## My death test modifies some state, but the change seems lost after the death test finishes. Why? ##
327
328Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
329expected crash won't kill the test program (i.e. the parent process). As a
330result, any in-memory side effects they incur are observable in their
331respective sub-processes, but not in the parent process. You can think of them
332as running in a parallel universe, more or less.
333
334## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ##
335
336If your class has a static data member:
337
338```
339// foo.h
340class Foo {
341  ...
342  static const int kBar = 100;
343};
344```
345
346You also need to define it _outside_ of the class body in `foo.cc`:
347
348```
349const int Foo::kBar;  // No initializer here.
350```
351
352Otherwise your code is **invalid C++**, and may break in unexpected ways. In
353particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc)
354will generate an "undefined reference" linker error.
355
356## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ##
357
358Google Test doesn't yet have good support for this kind of tests, or
359data-driven tests in general. We hope to be able to make improvements in this
360area soon.
361
362## Can I derive a test fixture from another? ##
363
364Yes.
365
366Each test fixture has a corresponding and same named test case. This means only
367one test case can use a particular fixture. Sometimes, however, multiple test
368cases may want to use the same or slightly different fixtures. For example, you
369may want to make sure that all of a GUI library's test cases don't leak
370important system resources like fonts and brushes.
371
372In Google Test, you share a fixture among test cases by putting the shared
373logic in a base test fixture, then deriving from that base a separate fixture
374for each test case that wants to use this common logic. You then use `TEST_F()`
375to write tests using each derived fixture.
376
377Typically, your code looks like this:
378
379```
380// Defines a base test fixture.
381class BaseTest : public ::testing::Test {
382  protected:
383   ...
384};
385
386// Derives a fixture FooTest from BaseTest.
387class FooTest : public BaseTest {
388  protected:
389    virtual void SetUp() {
390      BaseTest::SetUp();  // Sets up the base fixture first.
391      ... additional set-up work ...
392    }
393    virtual void TearDown() {
394      ... clean-up work for FooTest ...
395      BaseTest::TearDown();  // Remember to tear down the base fixture
396                             // after cleaning up FooTest!
397    }
398    ... functions and variables for FooTest ...
399};
400
401// Tests that use the fixture FooTest.
402TEST_F(FooTest, Bar) { ... }
403TEST_F(FooTest, Baz) { ... }
404
405... additional fixtures derived from BaseTest ...
406```
407
408If necessary, you can continue to derive test fixtures from a derived fixture.
409Google Test has no limit on how deep the hierarchy can be.
410
411For a complete example using derived test fixtures, see
412[sample5](http://code.google.com/p/googletest/source/browse/trunk/samples/sample5_unittest.cc).
413
414## My compiler complains "void value not ignored as it ought to be." What does this mean? ##
415
416You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
417`ASSERT_*()` can only be used in `void` functions.
418
419## My death test hangs (or seg-faults). How do I fix it? ##
420
421In Google Test, death tests are run in a child process and the way they work is
422delicate. To write death tests you really need to understand how they work.
423Please make sure you have read this.
424
425In particular, death tests don't like having multiple threads in the parent
426process. So the first thing you can try is to eliminate creating threads
427outside of `EXPECT_DEATH()`.
428
429Sometimes this is impossible as some library you must use may be creating
430threads before `main()` is even reached. In this case, you can try to minimize
431the chance of conflicts by either moving as many activities as possible inside
432`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
433leaving as few things as possible in it. Also, you can try to set the death
434test style to `"threadsafe"`, which is safer but slower, and see if it helps.
435
436If you go with thread-safe death tests, remember that they rerun the test
437program from the beginning in the child process. Therefore make sure your
438program can run side-by-side with itself and is deterministic.
439
440In the end, this boils down to good concurrent programming. You have to make
441sure that there is no race conditions or dead locks in your program. No silver
442bullet - sorry!
443
444## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ##
445
446The first thing to remember is that Google Test does not reuse the
447same test fixture object across multiple tests. For each `TEST_F`,
448Google Test will create a fresh test fixture object, _immediately_
449call `SetUp()`, run the test body, call `TearDown()`, and then
450_immediately_ delete the test fixture object.
451
452When you need to write per-test set-up and tear-down logic, you have
453the choice between using the test fixture constructor/destructor or
454`SetUp()/TearDown()`. The former is usually preferred, as it has the
455following benefits:
456
457  * By initializing a member variable in the constructor, we have the option to make it `const`, which helps prevent accidental changes to its value and makes the tests more obviously correct.
458  * In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With `SetUp()/TearDown()`, a subclass may make the mistake of forgetting to call the base class' `SetUp()/TearDown()` or call them at the wrong moment.
459
460You may still want to use `SetUp()/TearDown()` in the following rare cases:
461  * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions.
462  * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag.
463  * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`.
464
465## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
466
467If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
468overloaded or a template, the compiler will have trouble figuring out which
469overloaded version it should use. `ASSERT_PRED_FORMAT*` and
470`EXPECT_PRED_FORMAT*` don't have this problem.
471
472If you see this error, you might want to switch to
473`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
474message. If, however, that is not an option, you can resolve the problem by
475explicitly telling the compiler which version to pick.
476
477For example, suppose you have
478
479```
480bool IsPositive(int n) {
481  return n > 0;
482}
483bool IsPositive(double x) {
484  return x > 0;
485}
486```
487
488you will get a compiler error if you write
489
490```
491EXPECT_PRED1(IsPositive, 5);
492```
493
494However, this will work:
495
496```
497EXPECT_PRED1(*static_cast<bool (*)(int)>*(IsPositive), 5);
498```
499
500(The stuff inside the angled brackets for the `static_cast` operator is the
501type of the function pointer for the `int`-version of `IsPositive()`.)
502
503As another example, when you have a template function
504
505```
506template <typename T>
507bool IsNegative(T x) {
508  return x < 0;
509}
510```
511
512you can use it in a predicate assertion like this:
513
514```
515ASSERT_PRED1(IsNegative*<int>*, -5);
516```
517
518Things are more interesting if your template has more than one parameters. The
519following won't compile:
520
521```
522ASSERT_PRED2(*GreaterThan<int, int>*, 5, 0);
523```
524
525
526as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments,
527which is one more than expected. The workaround is to wrap the predicate
528function in parentheses:
529
530```
531ASSERT_PRED2(*(GreaterThan<int, int>)*, 5, 0);
532```
533
534
535## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ##
536
537Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
538instead of
539
540```
541return RUN_ALL_TESTS();
542```
543
544they write
545
546```
547RUN_ALL_TESTS();
548```
549
550This is wrong and dangerous. A test runner needs to see the return value of
551`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()`
552function ignores it, your test will be considered successful even if it has a
553Google Test assertion failure. Very bad.
554
555To help the users avoid this dangerous bug, the implementation of
556`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is
557ignored. If you see this warning, the fix is simple: just make sure its value
558is used as the return value of `main()`.
559
560## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ##
561
562Due to a peculiarity of C++, in order to support the syntax for streaming
563messages to an `ASSERT_*`, e.g.
564
565```
566ASSERT_EQ(1, Foo()) << "blah blah" << foo;
567```
568
569we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
570`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
571content of your constructor/destructor to a private void member function, or
572switch to `EXPECT_*()` if that works. This section in the user's guide explains
573it.
574
575## My set-up function is not called. Why? ##
576
577C++ is case-sensitive. It should be spelled as `SetUp()`.  Did you
578spell it as `Setup()`?
579
580Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
581wonder why it's never called.
582
583## How do I jump to the line of a failure in Emacs directly? ##
584
585Google Test's failure message format is understood by Emacs and many other
586IDEs, like acme and XCode. If a Google Test message is in a compilation buffer
587in Emacs, then it's clickable. You can now hit `enter` on a message to jump to
588the corresponding source code, or use `C-x `` to jump to the next failure.
589
590## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ##
591
592You don't have to. Instead of
593
594```
595class FooTest : public BaseTest {};
596
597TEST_F(FooTest, Abc) { ... }
598TEST_F(FooTest, Def) { ... }
599
600class BarTest : public BaseTest {};
601
602TEST_F(BarTest, Abc) { ... }
603TEST_F(BarTest, Def) { ... }
604```
605
606you can simply `typedef` the test fixtures:
607```
608typedef BaseTest FooTest;
609
610TEST_F(FooTest, Abc) { ... }
611TEST_F(FooTest, Def) { ... }
612
613typedef BaseTest BarTest;
614
615TEST_F(BarTest, Abc) { ... }
616TEST_F(BarTest, Def) { ... }
617```
618
619## The Google Test output is buried in a whole bunch of log messages. What do I do? ##
620
621The Google Test output is meant to be a concise and human-friendly report. If
622your test generates textual output itself, it will mix with the Google Test
623output, making it hard to read. However, there is an easy solution to this
624problem.
625
626Since most log messages go to stderr, we decided to let Google Test output go
627to stdout. This way, you can easily separate the two using redirection. For
628example:
629```
630./my_test > googletest_output.txt
631```
632
633## Why should I prefer test fixtures over global variables? ##
634
635There are several good reasons:
636  1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other.
637  1. Global variables pollute the global namespace.
638  1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common.
639
640## How do I test private class members without writing FRIEND\_TEST()s? ##
641
642You should try to write testable code, which means classes should be easily
643tested from their public interface. One way to achieve this is the Pimpl idiom:
644you move all private members of a class into a helper class, and make all
645members of the helper class public.
646
647You have several other options that don't require using `FRIEND_TEST`:
648  * Write the tests as members of the fixture class:
649```
650class Foo {
651  friend class FooTest;
652  ...
653};
654
655class FooTest : public ::testing::Test {
656 protected:
657  ...
658  void Test1() {...} // This accesses private members of class Foo.
659  void Test2() {...} // So does this one.
660};
661
662TEST_F(FooTest, Test1) {
663  Test1();
664}
665
666TEST_F(FooTest, Test2) {
667  Test2();
668}
669```
670  * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests:
671```
672class Foo {
673  friend class FooTest;
674  ...
675};
676
677class FooTest : public ::testing::Test {
678 protected:
679  ...
680  T1 get_private_member1(Foo* obj) {
681    return obj->private_member1_;
682  }
683};
684
685TEST_F(FooTest, Test1) {
686  ...
687  get_private_member1(x)
688  ...
689}
690```
691  * If the methods are declared **protected**, you can change their access level in a test-only subclass:
692```
693class YourClass {
694  ...
695 protected: // protected access for testability.
696  int DoSomethingReturningInt();
697  ...
698};
699
700// in the your_class_test.cc file:
701class TestableYourClass : public YourClass {
702  ...
703 public: using YourClass::DoSomethingReturningInt; // changes access rights
704  ...
705};
706
707TEST_F(YourClassTest, DoSomethingTest) {
708  TestableYourClass obj;
709  assertEquals(expected_value, obj.DoSomethingReturningInt());
710}
711```
712
713## How do I test private class static members without writing FRIEND\_TEST()s? ##
714
715We find private static methods clutter the header file.  They are
716implementation details and ideally should be kept out of a .h. So often I make
717them free functions instead.
718
719Instead of:
720```
721// foo.h
722class Foo {
723  ...
724 private:
725  static bool Func(int n);
726};
727
728// foo.cc
729bool Foo::Func(int n) { ... }
730
731// foo_test.cc
732EXPECT_TRUE(Foo::Func(12345));
733```
734
735You probably should better write:
736```
737// foo.h
738class Foo {
739  ...
740};
741
742// foo.cc
743namespace internal {
744  bool Func(int n) { ... }
745}
746
747// foo_test.cc
748namespace internal {
749  bool Func(int n);
750}
751
752EXPECT_TRUE(internal::Func(12345));
753```
754
755## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ##
756
757No. You can use a feature called [value-parameterized tests](AdvancedGuide#Value_Parameterized_Tests.md) which
758lets you repeat your tests with different parameters, without defining it more than once.
759
760## How do I test a file that defines main()? ##
761
762To test a `foo.cc` file, you need to compile and link it into your unit test
763program. However, when the file contains a definition for the `main()`
764function, it will clash with the `main()` of your unit test, and will result in
765a build error.
766
767The right solution is to split it into three files:
768  1. `foo.h` which contains the declarations,
769  1. `foo.cc` which contains the definitions except `main()`, and
770  1. `foo_main.cc` which contains nothing but the definition of `main()`.
771
772Then `foo.cc` can be easily tested.
773
774If you are adding tests to an existing file and don't want an intrusive change
775like this, there is a hack: just include the entire `foo.cc` file in your unit
776test. For example:
777```
778// File foo_unittest.cc
779
780// The headers section
781...
782
783// Renames main() in foo.cc to make room for the unit test main()
784#define main FooMain
785
786#include "a/b/foo.cc"
787
788// The tests start here.
789...
790```
791
792
793However, please remember this is a hack and should only be used as the last
794resort.
795
796## What can the statement argument in ASSERT\_DEATH() be? ##
797
798`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used
799wherever `_statement_` is valid. So basically `_statement_` can be any C++
800statement that makes sense in the current context. In particular, it can
801reference global and/or local variables, and can be:
802  * a simple function call (often the case),
803  * a complex expression, or
804  * a compound statement.
805
806> Some examples are shown here:
807```
808// A death test can be a simple function call.
809TEST(MyDeathTest, FunctionCall) {
810  ASSERT_DEATH(Xyz(5), "Xyz failed");
811}
812
813// Or a complex expression that references variables and functions.
814TEST(MyDeathTest, ComplexExpression) {
815  const bool c = Condition();
816  ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
817               "(Func1|Method) failed");
818}
819
820// Death assertions can be used any where in a function. In
821// particular, they can be inside a loop.
822TEST(MyDeathTest, InsideLoop) {
823  // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
824  for (int i = 0; i < 5; i++) {
825    EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
826                   ::testing::Message() << "where i is " << i);
827  }
828}
829
830// A death assertion can contain a compound statement.
831TEST(MyDeathTest, CompoundStatement) {
832  // Verifies that at lease one of Bar(0), Bar(1), ..., and
833  // Bar(4) dies.
834  ASSERT_DEATH({
835    for (int i = 0; i < 5; i++) {
836      Bar(i);
837    }
838  },
839  "Bar has \\d+ errors");}
840```
841
842`googletest_unittest.cc` contains more examples if you are interested.
843
844## What syntax does the regular expression in ASSERT\_DEATH use? ##
845
846On POSIX systems, Google Test uses the POSIX Extended regular
847expression syntax
848(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
849On Windows, it uses a limited variant of regular expression
850syntax. For more details, see the
851[regular expression syntax](AdvancedGuide#Regular_Expression_Syntax.md).
852
853## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ##
854
855Google Test needs to be able to create objects of your test fixture class, so
856it must have a default constructor. Normally the compiler will define one for
857you. However, there are cases where you have to define your own:
858  * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty.
859  * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.)
860
861## Why does ASSERT\_DEATH complain about previous threads that were already joined? ##
862
863With the Linux pthread library, there is no turning back once you cross the
864line from single thread to multiple threads. The first time you create a
865thread, a manager thread is created in addition, so you get 3, not 2, threads.
866Later when the thread you create joins the main thread, the thread count
867decrements by 1, but the manager thread will never be killed, so you still have
8682 threads, which means you cannot safely run a death test.
869
870The new NPTL thread library doesn't suffer from this problem, as it doesn't
871create a manager thread. However, if you don't control which machine your test
872runs on, you shouldn't depend on this.
873
874## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ##
875
876Google Test does not interleave tests from different test cases. That is, it
877runs all tests in one test case first, and then runs all tests in the next test
878case, and so on. Google Test does this because it needs to set up a test case
879before the first test in it is run, and tear it down afterwords. Splitting up
880the test case would require multiple set-up and tear-down processes, which is
881inefficient and makes the semantics unclean.
882
883If we were to determine the order of tests based on test name instead of test
884case name, then we would have a problem with the following situation:
885
886```
887TEST_F(FooTest, AbcDeathTest) { ... }
888TEST_F(FooTest, Uvw) { ... }
889
890TEST_F(BarTest, DefDeathTest) { ... }
891TEST_F(BarTest, Xyz) { ... }
892```
893
894Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
895interleave tests from different test cases, we need to run all tests in the
896`FooTest` case before running any test in the `BarTest` case. This contradicts
897with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
898
899## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ##
900
901You don't have to, but if you like, you may split up the test case into
902`FooTest` and `FooDeathTest`, where the names make it clear that they are
903related:
904
905```
906class FooTest : public ::testing::Test { ... };
907
908TEST_F(FooTest, Abc) { ... }
909TEST_F(FooTest, Def) { ... }
910
911typedef FooTest FooDeathTest;
912
913TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
914TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
915```
916
917## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ##
918
919If you use a user-defined type `FooType` in an assertion, you must make sure
920there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
921defined such that we can print a value of `FooType`.
922
923In addition, if `FooType` is declared in a name space, the `<<` operator also
924needs to be defined in the _same_ name space.
925
926## How do I suppress the memory leak messages on Windows? ##
927
928Since the statically initialized Google Test singleton requires allocations on
929the heap, the Visual C++ memory leak detector will report memory leaks at the
930end of the program run. The easiest way to avoid this is to use the
931`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
932statically initialized heap objects. See MSDN for more details and additional
933heap check/debug routines.
934
935## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ##
936
937You may get a number of the following linker error or warnings if you
938attempt to link your test project with the Google Test library when
939your project and the are not built using the same compiler settings.
940
941  * LNK2005: symbol already defined in object
942  * LNK4217: locally defined symbol 'symbol' imported in function 'function'
943  * LNK4049: locally defined symbol 'symbol' imported
944
945The Google Test project (gtest.vcproj) has the Runtime Library option
946set to /MT (use multi-threaded static libraries, /MTd for debug). If
947your project uses something else, for example /MD (use multi-threaded
948DLLs, /MDd for debug), you need to change the setting in the Google
949Test project to match your project's.
950
951To update this setting open the project properties in the Visual
952Studio IDE then select the branch Configuration Properties | C/C++ |
953Code Generation and change the option "Runtime Library".  You may also try
954using gtest-md.vcproj instead of gtest.vcproj.
955
956## I put my tests in a library and Google Test doesn't run them. What's happening? ##
957Have you read a
958[warning](http://code.google.com/p/googletest/wiki/Primer#Important_note_for_Visual_C++_users) on
959the Google Test Primer page?
960
961## I want to use Google Test with Visual Studio but don't know where to start. ##
962Many people are in your position and one of the posted his solution to
963our mailing list. Here is his link:
964http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html.
965
966## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ##
967Google Test uses parts of the standard C++ library that SunStudio does not support.
968Our users reported success using alternative implementations. Try running the build after runing this commad:
969
970`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'`
971
972## How can my code detect if it is running in a test? ##
973
974If you write code that sniffs whether it's running in a test and does
975different things accordingly, you are leaking test-only logic into
976production code and there is no easy way to ensure that the test-only
977code paths aren't run by mistake in production.  Such cleverness also
978leads to
979[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug).
980Therefore we strongly advise against the practice, and Google Test doesn't
981provide a way to do it.
982
983In general, the recommended way to cause the code to behave
984differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html).
985You can inject different functionality from the test and from the
986production code.  Since your production code doesn't link in the
987for-test logic at all, there is no danger in accidentally running it.
988
989However, if you _really_, _really_, _really_ have no choice, and if
990you follow the rule of ending your test program names with `_test`,
991you can use the _horrible_ hack of sniffing your executable name
992(`argv[0]` in `main()`) to know whether the code is under test.
993
994## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ##
995
996In C++, macros don't obey namespaces.  Therefore two libraries that
997both define a macro of the same name will clash if you #include both
998definitions.  In case a Google Test macro clashes with another
999library, you can force Google Test to rename its macro to avoid the
1000conflict.
1001
1002Specifically, if both Google Test and some other code define macro
1003`FOO`, you can add
1004```
1005  -DGTEST_DONT_DEFINE_FOO=1
1006```
1007to the compiler flags to tell Google Test to change the macro's name
1008from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
1009```
1010  GTEST_TEST(SomeTest, DoesThis) { ... }
1011```
1012instead of
1013```
1014  TEST(SomeTest, DoesThis) { ... }
1015```
1016in order to define a test.
1017
1018Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file.
1019
1020
1021## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ##
1022
1023Yes.
1024
1025The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`).
1026
1027```
1028namespace foo {
1029TEST(CoolTest, DoSomething) {
1030  SUCCEED();
1031}
1032}  // namespace foo
1033
1034namespace bar {
1035TEST(CoolTest, DoSomething) {
1036  SUCCEED();
1037}
1038}  // namespace foo
1039```
1040
1041However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name.
1042
1043```
1044namespace foo {
1045class CoolTest : public ::testing::Test {};  // Fixture foo::CoolTest
1046TEST_F(CoolTest, DoSomething) {
1047  SUCCEED();
1048}
1049}  // namespace foo
1050
1051namespace bar {
1052class CoolTest : public ::testing::Test {};  // Fixture: bar::CoolTest
1053TEST_F(CoolTest, DoSomething) {
1054  SUCCEED();
1055}
1056}  // namespace foo
1057```
1058
1059## How do I build Google Testing Framework with Xcode 4? ##
1060
1061If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like
1062"Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](http://code.google.com/p/googletest/source/browse/trunk/README) file on how to resolve this.
1063
1064## My question is not covered in your FAQ! ##
1065
1066If you cannot find the answer to your question in this FAQ, there are
1067some other resources you can use:
1068
1069  1. read other [wiki pages](http://code.google.com/p/googletest/w/list),
1070  1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics),
1071  1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.).
1072
1073Please note that creating an issue in the
1074[issue tracker](http://code.google.com/p/googletest/issues/list) is _not_
1075a good way to get your answer, as it is monitored infrequently by a
1076very small number of people.
1077
1078When asking a question, it's helpful to provide as much of the
1079following information as possible (people cannot help you if there's
1080not enough information in your question):
1081
1082  * the version (or the revision number if you check out from SVN directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version),
1083  * your operating system,
1084  * the name and version of your compiler,
1085  * the complete command line flags you give to your compiler,
1086  * the complete compiler error messages (if the question is about compilation),
1087  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/Primer.md
r0r249096
1
2
3# Introduction: Why Google C++ Testing Framework? #
4
5_Google C++ Testing Framework_ helps you write better C++ tests.
6
7No matter whether you work on Linux, Windows, or a Mac, if you write C++ code,
8Google Test can help you.
9
10So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
11  1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests.  Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
12  1. Tests should be well _organized_ and reflect the structure of the tested code.  Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
13  1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral.  Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations.  (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
14  1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
15  1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_.  Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
16  1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
17
18Since Google C++ Testing Framework is based on the popular xUnit
19architecture, you'll feel right at home if you've used JUnit or PyUnit before.
20If not, it will take you about 10 minutes to learn the basics and get started.
21So let's go!
22
23_Note:_ We sometimes refer to Google C++ Testing Framework informally
24as _Google Test_.
25
26# Setting up a New Test Project #
27
28To write a test program using Google Test, you need to compile Google
29Test into a library and link your test with it.  We provide build
30files for some popular build systems: `msvc/` for Visual Studio,
31`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland
32C++ Builder, and the autotools script (deprecated) and
33`CMakeLists.txt` for CMake (recommended) in the Google Test root
34directory.  If your build system is not on this list, you can take a
35look at `make/Makefile` to learn how Google Test should be compiled
36(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT`
37and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT`
38is the Google Test root directory).
39
40Once you are able to compile the Google Test library, you should
41create a project or build target for your test program.  Make sure you
42have `GTEST_ROOT/include` in the header search path so that the
43compiler can find `"gtest/gtest.h"` when compiling your test.  Set up
44your test project to link with the Google Test library (for example,
45in Visual Studio, this is done by adding a dependency on
46`gtest.vcproj`).
47
48If you still have questions, take a look at how Google Test's own
49tests are built and use them as examples.
50
51# Basic Concepts #
52
53When using Google Test, you start by writing _assertions_, which are statements
54that check whether a condition is true. An assertion's result can be _success_,
55_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts
56the current function; otherwise the program continues normally.
57
58_Tests_ use assertions to verify the tested code's behavior. If a test crashes
59or has a failed assertion, then it _fails_; otherwise it _succeeds_.
60
61A _test case_ contains one or many tests. You should group your tests into test
62cases that reflect the structure of the tested code. When multiple tests in a
63test case need to share common objects and subroutines, you can put them into a
64_test fixture_ class.
65
66A _test program_ can contain multiple test cases.
67
68We'll now explain how to write a test program, starting at the individual
69assertion level and building up to tests and test cases.
70
71# Assertions #
72
73Google Test assertions are macros that resemble function calls. You test a
74class or function by making assertions about its behavior. When an assertion
75fails, Google Test prints the assertion's source file and line number location,
76along with a failure message. You may also supply a custom failure message
77which will be appended to Google Test's message.
78
79The assertions come in pairs that test the same thing but have different
80effects on the current function. `ASSERT_*` versions generate fatal failures
81when they fail, and **abort the current function**. `EXPECT_*` versions generate
82nonfatal failures, which don't abort the current function. Usually `EXPECT_*`
83are preferred, as they allow more than one failures to be reported in a test.
84However, you should use `ASSERT_*` if it doesn't make sense to continue when
85the assertion in question fails.
86
87Since a failed `ASSERT_*` returns from the current function immediately,
88possibly skipping clean-up code that comes after it, it may cause a space leak.
89Depending on the nature of the leak, it may or may not be worth fixing - so
90keep this in mind if you get a heap checker error in addition to assertion
91errors.
92
93To provide a custom failure message, simply stream it into the macro using the
94`<<` operator, or a sequence of such operators. An example:
95```
96ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
97
98for (int i = 0; i < x.size(); ++i) {
99  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
100}
101```
102
103Anything that can be streamed to an `ostream` can be streamed to an assertion
104macro--in particular, C strings and `string` objects. If a wide string
105(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
106streamed to an assertion, it will be translated to UTF-8 when printed.
107
108## Basic Assertions ##
109
110These assertions do basic true/false condition testing.
111| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
112|:--------------------|:-----------------------|:-------------|
113| `ASSERT_TRUE(`_condition_`)`;  | `EXPECT_TRUE(`_condition_`)`;   | _condition_ is true |
114| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`;  | _condition_ is false |
115
116Remember, when they fail, `ASSERT_*` yields a fatal failure and
117returns from the current function, while `EXPECT_*` yields a nonfatal
118failure, allowing the function to continue running. In either case, an
119assertion failure means its containing test fails.
120
121_Availability_: Linux, Windows, Mac.
122
123## Binary Comparison ##
124
125This section describes assertions that compare two values.
126
127| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
128|:--------------------|:-----------------------|:-------------|
129|`ASSERT_EQ(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ |
130|`ASSERT_NE(`_val1_`, `_val2_`);`      |`EXPECT_NE(`_val1_`, `_val2_`);`      | _val1_ `!=` _val2_ |
131|`ASSERT_LT(`_val1_`, `_val2_`);`      |`EXPECT_LT(`_val1_`, `_val2_`);`      | _val1_ `<` _val2_ |
132|`ASSERT_LE(`_val1_`, `_val2_`);`      |`EXPECT_LE(`_val1_`, `_val2_`);`      | _val1_ `<=` _val2_ |
133|`ASSERT_GT(`_val1_`, `_val2_`);`      |`EXPECT_GT(`_val1_`, `_val2_`);`      | _val1_ `>` _val2_ |
134|`ASSERT_GE(`_val1_`, `_val2_`);`      |`EXPECT_GE(`_val1_`, `_val2_`);`      | _val1_ `>=` _val2_ |
135
136In the event of a failure, Google Test prints both _val1_ and _val2_
137. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions
138we'll introduce later), you should put the expression you want to test
139in the position of _actual_, and put its expected value in _expected_,
140as Google Test's failure messages are optimized for this convention.
141
142Value arguments must be comparable by the assertion's comparison
143operator or you'll get a compiler error.  We used to require the
144arguments to support the `<<` operator for streaming to an `ostream`,
145but it's no longer necessary since v1.6.0 (if `<<` is supported, it
146will be called to print the arguments when the assertion fails;
147otherwise Google Test will attempt to print them in the best way it
148can. For more details and how to customize the printing of the
149arguments, see this Google Mock [recipe](http://code.google.com/p/googlemock/wiki/CookBook#Teaching_Google_Mock_How_to_Print_Your_Values).).
150
151These assertions can work with a user-defined type, but only if you define the
152corresponding comparison operator (e.g. `==`, `<`, etc).  If the corresponding
153operator is defined, prefer using the `ASSERT_*()` macros because they will
154print out not only the result of the comparison, but the two operands as well.
155
156Arguments are always evaluated exactly once. Therefore, it's OK for the
157arguments to have side effects. However, as with any ordinary C/C++ function,
158the arguments' evaluation order is undefined (i.e. the compiler is free to
159choose any order) and your code should not depend on any particular argument
160evaluation order.
161
162`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
163tests if they are in the same memory location, not if they have the same value.
164Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
165`ASSERT_STREQ()` , which will be described later on. In particular, to assert
166that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to
167compare two `string` objects, you should use `ASSERT_EQ`.
168
169Macros in this section work with both narrow and wide string objects (`string`
170and `wstring`).
171
172_Availability_: Linux, Windows, Mac.
173
174## String Comparison ##
175
176The assertions in this group compare two **C strings**. If you want to compare
177two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
178
179| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
180|:--------------------|:-----------------------|:-------------|
181| `ASSERT_STREQ(`_expected\_str_`, `_actual\_str_`);`    | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);`     | the two C strings have the same content |
182| `ASSERT_STRNE(`_str1_`, `_str2_`);`    | `EXPECT_STRNE(`_str1_`, `_str2_`);`     | the two C strings have different content |
183| `ASSERT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | the two C strings have the same content, ignoring case |
184| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case |
185
186Note that "CASE" in an assertion name means that case is ignored.
187
188`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a
189comparison of two wide strings fails, their values will be printed as UTF-8
190narrow strings.
191
192A `NULL` pointer and an empty string are considered _different_.
193
194_Availability_: Linux, Windows, Mac.
195
196See also: For more string comparison tricks (substring, prefix, suffix, and
197regular expression matching, for example), see the [Advanced Google Test Guide](AdvancedGuide.md).
198
199# Simple Tests #
200
201To create a test:
202  1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value.
203  1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
204  1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
205
206```
207TEST(test_case_name, test_name) {
208 ... test body ...
209}
210```
211
212
213`TEST()` arguments go from general to specific. The _first_ argument is the
214name of the test case, and the _second_ argument is the test's name within the
215test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its
216individual name. Tests from different test cases can have the same individual
217name.
218
219For example, let's take a simple integer function:
220```
221int Factorial(int n); // Returns the factorial of n
222```
223
224A test case for this function might look like:
225```
226// Tests factorial of 0.
227TEST(FactorialTest, HandlesZeroInput) {
228  EXPECT_EQ(1, Factorial(0));
229}
230
231// Tests factorial of positive numbers.
232TEST(FactorialTest, HandlesPositiveInput) {
233  EXPECT_EQ(1, Factorial(1));
234  EXPECT_EQ(2, Factorial(2));
235  EXPECT_EQ(6, Factorial(3));
236  EXPECT_EQ(40320, Factorial(8));
237}
238```
239
240Google Test groups the test results by test cases, so logically-related tests
241should be in the same test case; in other words, the first argument to their
242`TEST()` should be the same. In the above example, we have two tests,
243`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
244case `FactorialTest`.
245
246_Availability_: Linux, Windows, Mac.
247
248# Test Fixtures: Using the Same Data Configuration for Multiple Tests #
249
250If you find yourself writing two or more tests that operate on similar data,
251you can use a _test fixture_. It allows you to reuse the same configuration of
252objects for several different tests.
253
254To create a fixture, just:
255  1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes.
256  1. Inside the class, declare any objects you plan to use.
257  1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you.
258  1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](http://code.google.com/p/googletest/wiki/FAQ#Should_I_use_the_constructor/destructor_of_the_test_fixture_or_t).
259  1. If needed, define subroutines for your tests to share.
260
261When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
262access objects and subroutines in the test fixture:
263```
264TEST_F(test_case_name, test_name) {
265 ... test body ...
266}
267```
268
269Like `TEST()`, the first argument is the test case name, but for `TEST_F()`
270this must be the name of the test fixture class. You've probably guessed: `_F`
271is for fixture.
272
273Unfortunately, the C++ macro system does not allow us to create a single macro
274that can handle both types of tests. Using the wrong macro causes a compiler
275error.
276
277Also, you must first define a test fixture class before using it in a
278`TEST_F()`, or you'll get the compiler error "`virtual outside class
279declaration`".
280
281For each test defined with `TEST_F()`, Google Test will:
282  1. Create a _fresh_ test fixture at runtime
283  1. Immediately initialize it via `SetUp()` ,
284  1. Run the test
285  1. Clean up by calling `TearDown()`
286  1. Delete the test fixture.  Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
287
288As an example, let's write tests for a FIFO queue class named `Queue`, which
289has the following interface:
290```
291template <typename E> // E is the element type.
292class Queue {
293 public:
294  Queue();
295  void Enqueue(const E& element);
296  E* Dequeue(); // Returns NULL if the queue is empty.
297  size_t size() const;
298  ...
299};
300```
301
302First, define a fixture class. By convention, you should give it the name
303`FooTest` where `Foo` is the class being tested.
304```
305class QueueTest : public ::testing::Test {
306 protected:
307  virtual void SetUp() {
308    q1_.Enqueue(1);
309    q2_.Enqueue(2);
310    q2_.Enqueue(3);
311  }
312
313  // virtual void TearDown() {}
314
315  Queue<int> q0_;
316  Queue<int> q1_;
317  Queue<int> q2_;
318};
319```
320
321In this case, `TearDown()` is not needed since we don't have to clean up after
322each test, other than what's already done by the destructor.
323
324Now we'll write tests using `TEST_F()` and this fixture.
325```
326TEST_F(QueueTest, IsEmptyInitially) {
327  EXPECT_EQ(0, q0_.size());
328}
329
330TEST_F(QueueTest, DequeueWorks) {
331  int* n = q0_.Dequeue();
332  EXPECT_EQ(NULL, n);
333
334  n = q1_.Dequeue();
335  ASSERT_TRUE(n != NULL);
336  EXPECT_EQ(1, *n);
337  EXPECT_EQ(0, q1_.size());
338  delete n;
339
340  n = q2_.Dequeue();
341  ASSERT_TRUE(n != NULL);
342  EXPECT_EQ(2, *n);
343  EXPECT_EQ(1, q2_.size());
344  delete n;
345}
346```
347
348The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
349to use `EXPECT_*` when you want the test to continue to reveal more errors
350after the assertion failure, and use `ASSERT_*` when continuing after failure
351doesn't make sense. For example, the second assertion in the `Dequeue` test is
352`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later,
353which would lead to a segfault when `n` is `NULL`.
354
355When these tests run, the following happens:
356  1. Google Test constructs a `QueueTest` object (let's call it `t1` ).
357  1. `t1.SetUp()` initializes `t1` .
358  1. The first test ( `IsEmptyInitially` ) runs on `t1` .
359  1. `t1.TearDown()` cleans up after the test finishes.
360  1. `t1` is destructed.
361  1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test.
362
363_Availability_: Linux, Windows, Mac.
364
365_Note_: Google Test automatically saves all _Google Test_ flags when a test
366object is constructed, and restores them when it is destructed.
367
368# Invoking the Tests #
369
370`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
371
372After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files.
373
374When invoked, the `RUN_ALL_TESTS()` macro:
375  1. Saves the state of all  Google Test flags.
376  1. Creates a test fixture object for the first test.
377  1. Initializes it via `SetUp()`.
378  1. Runs the test on the fixture object.
379  1. Cleans up the fixture via `TearDown()`.
380  1. Deletes the fixture.
381  1. Restores the state of all Google Test flags.
382  1. Repeats the above steps for the next test, until all tests have run.
383
384In addition, if the text fixture's constructor generates a fatal failure in
385step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly,
386if step 3 generates a fatal failure, step 4 will be skipped.
387
388_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc`
389will give you a compiler error. The rationale for this design is that the
390automated testing service determines whether a test has passed based on its
391exit code, not on its stdout/stderr output; thus your `main()` function must
392return the value of `RUN_ALL_TESTS()`.
393
394Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once
395conflicts with some advanced Google Test features (e.g. thread-safe death
396tests) and thus is not supported.
397
398_Availability_: Linux, Windows, Mac.
399
400# Writing the main() Function #
401
402You can start from this boilerplate:
403```
404#include "this/package/foo.h"
405#include "gtest/gtest.h"
406
407namespace {
408
409// The fixture for testing class Foo.
410class FooTest : public ::testing::Test {
411 protected:
412  // You can remove any or all of the following functions if its body
413  // is empty.
414
415  FooTest() {
416    // You can do set-up work for each test here.
417  }
418
419  virtual ~FooTest() {
420    // You can do clean-up work that doesn't throw exceptions here.
421  }
422
423  // If the constructor and destructor are not enough for setting up
424  // and cleaning up each test, you can define the following methods:
425
426  virtual void SetUp() {
427    // Code here will be called immediately after the constructor (right
428    // before each test).
429  }
430
431  virtual void TearDown() {
432    // Code here will be called immediately after each test (right
433    // before the destructor).
434  }
435
436  // Objects declared here can be used by all tests in the test case for Foo.
437};
438
439// Tests that the Foo::Bar() method does Abc.
440TEST_F(FooTest, MethodBarDoesAbc) {
441  const string input_filepath = "this/package/testdata/myinputfile.dat";
442  const string output_filepath = "this/package/testdata/myoutputfile.dat";
443  Foo f;
444  EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
445}
446
447// Tests that Foo does Xyz.
448TEST_F(FooTest, DoesXyz) {
449  // Exercises the Xyz feature of Foo.
450}
451
452}  // namespace
453
454int main(int argc, char **argv) {
455  ::testing::InitGoogleTest(&argc, argv);
456  return RUN_ALL_TESTS();
457}
458```
459
460The `::testing::InitGoogleTest()` function parses the command line for Google
461Test flags, and removes all recognized flags. This allows the user to control a
462test program's behavior via various flags, which we'll cover in [AdvancedGuide](AdvancedGuide.md).
463You must call this function before calling `RUN_ALL_TESTS()`, or the flags
464won't be properly initialized.
465
466On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
467in programs compiled in `UNICODE` mode as well.
468
469But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go.
470
471## Important note for Visual C++ users ##
472If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:
473```
474__declspec(dllexport) int PullInMyLibrary() { return 0; }
475```
476If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function:
477```
478int PullInMyLibrary();
479static int dummy = PullInMyLibrary();
480```
481This will keep your tests referenced and will make them register themselves at startup.
482
483In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.
484
485There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!
486
487# Where to Go from Here #
488
489Congratulations! You've learned the Google Test basics. You can start writing
490and running Google Test tests, read some [samples](Samples.md), or continue with
491[AdvancedGuide](AdvancedGuide.md), which describes many more useful Google Test features.
492
493# Known Limitations #
494
495Google Test is designed to be thread-safe.  The implementation is
496thread-safe on systems where the `pthreads` library is available.  It
497is currently _unsafe_ to use Google Test assertions from two threads
498concurrently on other systems (e.g. Windows).  In most tests this is
499not an issue as usually the assertions are done in the main thread. If
500you want to help, you can volunteer to implement the necessary
501synchronization primitives in `gtest-port.h` for your platform.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/PumpManual.md
r0r249096
1
2
3<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
4
5# The Problem #
6
7Template and macro libraries often need to define many classes,
8functions, or macros that vary only (or almost only) in the number of
9arguments they take. It's a lot of repetitive, mechanical, and
10error-prone work.
11
12Variadic templates and variadic macros can alleviate the problem.
13However, while both are being considered by the C++ committee, neither
14is in the standard yet or widely supported by compilers.  Thus they
15are often not a good choice, especially when your code needs to be
16portable. And their capabilities are still limited.
17
18As a result, authors of such libraries often have to write scripts to
19generate their implementation. However, our experience is that it's
20tedious to write such scripts, which tend to reflect the structure of
21the generated code poorly and are often hard to read and edit. For
22example, a small change needed in the generated code may require some
23non-intuitive, non-trivial changes in the script. This is especially
24painful when experimenting with the code.
25
26# Our Solution #
27
28Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
29Programming, or Practical Utility for Meta Programming, whichever you
30prefer) is a simple meta-programming tool for C++. The idea is that a
31programmer writes a `foo.pump` file which contains C++ code plus meta
32code that manipulates the C++ code. The meta code can handle
33iterations over a range, nested iterations, local meta variable
34definitions, simple arithmetic, and conditional expressions. You can
35view it as a small Domain-Specific Language. The meta language is
36designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode,
37for example) and concise, making Pump code intuitive and easy to
38maintain.
39
40## Highlights ##
41
42  * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms.
43  * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly.
44  * The format is human-readable and more concise than XML.
45  * The format works relatively well with Emacs' C++ mode.
46
47## Examples ##
48
49The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line):
50
51```
52$var n = 3     $$ Defines a meta variable n.
53$range i 0..n  $$ Declares the range of meta iterator i (inclusive).
54$for i [[
55               $$ Meta loop.
56// Foo$i does blah for $i-ary predicates.
57$range j 1..i
58template <size_t N $for j [[, typename A$j]]>
59class Foo$i {
60$if i == 0 [[
61  blah a;
62]] $elif i <= 2 [[
63  blah b;
64]] $else [[
65  blah c;
66]]
67};
68
69]]
70```
71
72will be translated by the Pump compiler to:
73
74```
75// Foo0 does blah for 0-ary predicates.
76template <size_t N>
77class Foo0 {
78  blah a;
79};
80
81// Foo1 does blah for 1-ary predicates.
82template <size_t N, typename A1>
83class Foo1 {
84  blah b;
85};
86
87// Foo2 does blah for 2-ary predicates.
88template <size_t N, typename A1, typename A2>
89class Foo2 {
90  blah b;
91};
92
93// Foo3 does blah for 3-ary predicates.
94template <size_t N, typename A1, typename A2, typename A3>
95class Foo3 {
96  blah c;
97};
98```
99
100In another example,
101
102```
103$range i 1..n
104Func($for i + [[a$i]]);
105$$ The text between i and [[ is the separator between iterations.
106```
107
108will generate one of the following lines (without the comments), depending on the value of `n`:
109
110```
111Func();              // If n is 0.
112Func(a1);            // If n is 1.
113Func(a1 + a2);       // If n is 2.
114Func(a1 + a2 + a3);  // If n is 3.
115// And so on...
116```
117
118## Constructs ##
119
120We support the following meta programming constructs:
121
122| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. |
123|:----------------|:-----------------------------------------------------------------------------------------------|
124| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later.          |
125| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`.         |
126| `$($)`          | Generates a single `$` character.                                                              |
127| `$id`           | Value of the named constant or iteration variable.                                             |
128| `$(exp)`        | Value of the expression.                                                                       |
129| `$if exp [[ code ]] else_branch` | Conditional.                                                                                   |
130| `[[ code ]]`    | Meta lexical block.                                                                            |
131| `cpp_code`      | Raw C++ code.                                                                                  |
132| `$$ comment`    | Meta comment.                                                                                  |
133
134**Note:** To give the user some freedom in formatting the Pump source
135code, Pump ignores a new-line character if it's right after `$for foo`
136or next to `[[` or `]]`. Without this rule you'll often be forced to write
137very long lines to get the desired output. Therefore sometimes you may
138need to insert an extra new-line in such places for a new-line to show
139up in your output.
140
141## Grammar ##
142
143```
144code ::= atomic_code*
145atomic_code ::= $var id = exp
146    | $var id = [[ code ]]
147    | $range id exp..exp
148    | $for id sep [[ code ]]
149    | $($)
150    | $id
151    | $(exp)
152    | $if exp [[ code ]] else_branch
153    | [[ code ]]
154    | cpp_code
155sep ::= cpp_code | empty_string
156else_branch ::= $else [[ code ]]
157    | $elif exp [[ code ]] else_branch
158    | empty_string
159exp ::= simple_expression_in_Python_syntax
160```
161
162## Code ##
163
164You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still
165very unpolished and lacks automated tests, although it has been
166successfully used many times. If you find a chance to use it in your
167project, please let us know what you think!  We also welcome help on
168improving Pump.
169
170## Real Examples ##
171
172You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com).  The source file `foo.h.pump` generates `foo.h`.
173
174## Tips ##
175
176  * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1.
177  * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line.
trunk/3rdparty/googletest/googletest/docs/Samples.md
r0r249096
1If you're like us, you'd like to look at some Google Test sample code.  The
2[samples folder](../samples) has a number of well-commented samples showing how to use a
3variety of Google Test features.
4
5  * [Sample #1](../samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions.
6  * [Sample #2](../samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions.
7  * [Sample #3](../samples/sample3_unittest.cc) uses a test fixture.
8  * [Sample #4](../samples/sample4_unittest.cc) is another basic example of using Google Test.
9  * [Sample #5](../samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it.
10  * [Sample #6](../samples/sample6_unittest.cc) demonstrates type-parameterized tests.
11  * [Sample #7](../samples/sample7_unittest.cc) teaches the basics of value-parameterized tests.
12  * [Sample #8](../samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests.
13  * [Sample #9](../samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results.
14  * [Sample #10](../samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker.
trunk/3rdparty/googletest/googletest/docs/V1_5_AdvancedGuide.md
r0r249096
1
2
3Now that you have read [Primer](V1_5_Primer.md) and learned how to write tests
4using Google Test, it's time to learn some new tricks. This document
5will show you more assertions as well as how to construct complex
6failure messages, propagate fatal failures, reuse and speed up your
7test fixtures, and use various flags with your tests.
8
9# More Assertions #
10
11This section covers some less frequently used, but still significant,
12assertions.
13
14## Explicit Success and Failure ##
15
16These three assertions do not actually test a value or expression. Instead,
17they generate a success or failure directly. Like the macros that actually
18perform a test, you may stream a custom failure message into the them.
19
20| `SUCCEED();` |
21|:-------------|
22
23Generates a success. This does NOT make the overall test succeed. A test is
24considered successful only if none of its assertions fail during its execution.
25
26Note: `SUCCEED()` is purely documentary and currently doesn't generate any
27user-visible output. However, we may add `SUCCEED()` messages to Google Test's
28output in the future.
29
30| `FAIL();`  | `ADD_FAILURE();` |
31|:-----------|:-----------------|
32
33`FAIL*` generates a fatal failure while `ADD_FAILURE*` generates a nonfatal
34failure. These are useful when control flow, rather than a Boolean expression,
35deteremines the test's success or failure. For example, you might want to write
36something like:
37
38```
39switch(expression) {
40  case 1: ... some checks ...
41  case 2: ... some other checks
42  ...
43  default: FAIL() << "We shouldn't get here.";
44}
45```
46
47_Availability_: Linux, Windows, Mac.
48
49## Exception Assertions ##
50
51These are for verifying that a piece of code throws (or does not
52throw) an exception of the given type:
53
54| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
55|:--------------------|:-----------------------|:-------------|
56| `ASSERT_THROW(`_statement_, _exception\_type_`);`  | `EXPECT_THROW(`_statement_, _exception\_type_`);`  | _statement_ throws an exception of the given type  |
57| `ASSERT_ANY_THROW(`_statement_`);`                | `EXPECT_ANY_THROW(`_statement_`);`                | _statement_ throws an exception of any type        |
58| `ASSERT_NO_THROW(`_statement_`);`                 | `EXPECT_NO_THROW(`_statement_`);`                 | _statement_ doesn't throw any exception            |
59
60Examples:
61
62```
63ASSERT_THROW(Foo(5), bar_exception);
64
65EXPECT_NO_THROW({
66  int n = 5;
67  Bar(&n);
68});
69```
70
71_Availability_: Linux, Windows, Mac; since version 1.1.0.
72
73## Predicate Assertions for Better Error Messages ##
74
75Even though Google Test has a rich set of assertions, they can never be
76complete, as it's impossible (nor a good idea) to anticipate all the scenarios
77a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
78to check a complex expression, for lack of a better macro. This has the problem
79of not showing you the values of the parts of the expression, making it hard to
80understand what went wrong. As a workaround, some users choose to construct the
81failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
82is awkward especially when the expression has side-effects or is expensive to
83evaluate.
84
85Google Test gives you three different options to solve this problem:
86
87### Using an Existing Boolean Function ###
88
89If you already have a function or a functor that returns `bool` (or a type
90that can be implicitly converted to `bool`), you can use it in a _predicate
91assertion_ to get the function arguments printed for free:
92
93| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
94|:--------------------|:-----------------------|:-------------|
95| `ASSERT_PRED1(`_pred1, val1_`);`       | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
96| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` |  _pred2(val1, val2)_ returns true |
97|  ...                | ...                    | ...          |
98
99In the above, _predn_ is an _n_-ary predicate function or functor, where
100_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
101if the predicate returns `true` when applied to the given arguments, and fails
102otherwise. When the assertion fails, it prints the value of each argument. In
103either case, the arguments are evaluated exactly once.
104
105Here's an example. Given
106
107```
108// Returns true iff m and n have no common divisors except 1.
109bool MutuallyPrime(int m, int n) { ... }
110const int a = 3;
111const int b = 4;
112const int c = 10;
113```
114
115the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
116assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message
117
118<pre>
119!MutuallyPrime(b, c) is false, where<br>
120b is 4<br>
121c is 10<br>
122</pre>
123
124**Notes:**
125
126  1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](http://code.google.com/p/googletest/wiki/V1_5_FAQ#The_compiler_complains_%22no_matching_function_to_call%22) for how to resolve it.
127  1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.
128
129_Availability_: Linux, Windows, Mac
130
131### Using a Function That Returns an AssertionResult ###
132
133While `EXPECT_PRED*()` and friends are handy for a quick job, the
134syntax is not satisfactory: you have to use different macros for
135different arities, and it feels more like Lisp than C++.  The
136`::testing::AssertionResult` class solves this problem.
137
138An `AssertionResult` object represents the result of an assertion
139(whether it's a success or a failure, and an associated message).  You
140can create an `AssertionResult` using one of these factory
141functions:
142
143```
144namespace testing {
145
146// Returns an AssertionResult object to indicate that an assertion has
147// succeeded.
148AssertionResult AssertionSuccess();
149
150// Returns an AssertionResult object to indicate that an assertion has
151// failed.
152AssertionResult AssertionFailure();
153
154}
155```
156
157You can then use the `<<` operator to stream messages to the
158`AssertionResult` object.
159
160To provide more readable messages in Boolean assertions
161(e.g. `EXPECT_TRUE()`), write a predicate function that returns
162`AssertionResult` instead of `bool`. For example, if you define
163`IsEven()` as:
164
165```
166::testing::AssertionResult IsEven(int n) {
167  if ((n % 2) == 0)
168    return ::testing::AssertionSuccess();
169  else
170    return ::testing::AssertionFailure() << n << " is odd";
171}
172```
173
174instead of:
175
176```
177bool IsEven(int n) {
178  return (n % 2) == 0;
179}
180```
181
182the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
183
184<pre>
185Value of: !IsEven(Fib(4))<br>
186Actual: false (*3 is odd*)<br>
187Expected: true<br>
188</pre>
189
190instead of a more opaque
191
192<pre>
193Value of: !IsEven(Fib(4))<br>
194Actual: false<br>
195Expected: true<br>
196</pre>
197
198If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
199as well, and are fine with making the predicate slower in the success
200case, you can supply a success message:
201
202```
203::testing::AssertionResult IsEven(int n) {
204  if ((n % 2) == 0)
205    return ::testing::AssertionSuccess() << n << " is even";
206  else
207    return ::testing::AssertionFailure() << n << " is odd";
208}
209```
210
211Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
212
213<pre>
214Value of: !IsEven(Fib(6))<br>
215Actual: true (8 is even)<br>
216Expected: false<br>
217</pre>
218
219_Availability_: Linux, Windows, Mac; since version 1.4.1.
220
221### Using a Predicate-Formatter ###
222
223If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
224`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
225predicate do not support streaming to `ostream`, you can instead use the
226following _predicate-formatter assertions_ to _fully_ customize how the
227message is formatted:
228
229| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
230|:--------------------|:-----------------------|:-------------|
231| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);`        | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`); | _pred\_format1(val1)_ is successful |
232| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful |
233| `...`               | `...`                  | `...`        |
234
235The difference between this and the previous two groups of macros is that instead of
236a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_
237(_pred\_formatn_), which is a function or functor with the signature:
238
239`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);`
240
241where _val1_, _val2_, ..., and _valn_ are the values of the predicate
242arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding
243expressions as they appear in the source code. The types `T1`, `T2`, ..., and
244`Tn` can be either value types or reference types. For example, if an
245argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`,
246whichever is appropriate.
247
248A predicate-formatter returns a `::testing::AssertionResult` object to indicate
249whether the assertion has succeeded or not. The only way to create such an
250object is to call one of these factory functions:
251
252As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`:
253
254```
255// Returns the smallest prime common divisor of m and n,
256// or 1 when m and n are mutually prime.
257int SmallestPrimeCommonDivisor(int m, int n) { ... }
258
259// A predicate-formatter for asserting that two integers are mutually prime.
260::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
261                                               const char* n_expr,
262                                               int m,
263                                               int n) {
264  if (MutuallyPrime(m, n))
265    return ::testing::AssertionSuccess();
266 
267  return ::testing::AssertionFailure()
268      << m_expr << " and " << n_expr << " (" << m << " and " << n
269      << ") are not mutually prime, " << "as they have a common divisor "
270      << SmallestPrimeCommonDivisor(m, n);
271}
272```
273
274With this predicate-formatter, we can use
275
276```
277EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
278```
279
280to generate the message
281
282<pre>
283b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br>
284</pre>
285
286As you may have realized, many of the assertions we introduced earlier are
287special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
288indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.
289
290_Availability_: Linux, Windows, Mac.
291
292
293## Floating-Point Comparison ##
294
295Comparing floating-point numbers is tricky. Due to round-off errors, it is
296very unlikely that two floating-points will match exactly. Therefore,
297`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points
298can have a wide value range, no single fixed error bound works. It's better to
299compare by a fixed relative error bound, except for values close to 0 due to
300the loss of precision there.
301
302In general, for floating-point comparison to make sense, the user needs to
303carefully choose the error bound. If they don't want or care to, comparing in
304terms of Units in the Last Place (ULPs) is a good default, and Google Test
305provides assertions to do this. Full details about ULPs are quite long; if you
306want to learn more, see
307[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).
308
309### Floating-Point Macros ###
310
311| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
312|:--------------------|:-----------------------|:-------------|
313| `ASSERT_FLOAT_EQ(`_expected, actual_`);`  | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal |
314| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | the two `double` values are almost equal |
315
316By "almost equal", we mean the two values are within 4 ULP's from each
317other.
318
319The following assertions allow you to choose the acceptable error bound:
320
321| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
322|:--------------------|:-----------------------|:-------------|
323| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error |
324
325_Availability_: Linux, Windows, Mac.
326
327### Floating-Point Predicate-Format Functions ###
328
329Some floating-point operations are useful, but not that often used. In order
330to avoid an explosion of new macros, we provide them as predicate-format
331functions that can be used in predicate assertion macros (e.g.
332`EXPECT_PRED_FORMAT2`, etc).
333
334```
335EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
336EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
337```
338
339Verifies that _val1_ is less than, or almost equal to, _val2_. You can
340replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.
341
342_Availability_: Linux, Windows, Mac.
343
344## Windows HRESULT assertions ##
345
346These assertions test for `HRESULT` success or failure.
347
348| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
349|:--------------------|:-----------------------|:-------------|
350| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` |
351| `ASSERT_HRESULT_FAILED(`_expression_`);`    | `EXPECT_HRESULT_FAILED(`_expression_`);`    | _expression_ is a failure `HRESULT` |
352
353The generated output contains the human-readable error message
354associated with the `HRESULT` code returned by _expression_.
355
356You might use them like this:
357
358```
359CComPtr shell;
360ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
361CComVariant empty;
362ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
363```
364
365_Availability_: Windows.
366
367## Type Assertions ##
368
369You can call the function
370```
371::testing::StaticAssertTypeEq<T1, T2>();
372```
373to assert that types `T1` and `T2` are the same.  The function does
374nothing if the assertion is satisfied.  If the types are different,
375the function call will fail to compile, and the compiler error message
376will likely (depending on the compiler) show you the actual values of
377`T1` and `T2`.  This is mainly useful inside template code.
378
379_Caveat:_ When used inside a member function of a class template or a
380function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_
381the function is instantiated.  For example, given:
382```
383template <typename T> class Foo {
384 public:
385  void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
386};
387```
388the code:
389```
390void Test1() { Foo<bool> foo; }
391```
392will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never
393actually instantiated.  Instead, you need:
394```
395void Test2() { Foo<bool> foo; foo.Bar(); }
396```
397to cause a compiler error.
398
399_Availability:_ Linux, Windows, Mac; since version 1.3.0.
400
401## Assertion Placement ##
402
403You can use assertions in any C++ function. In particular, it doesn't
404have to be a method of the test fixture class. The one constraint is
405that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`)
406can only be used in void-returning functions. This is a consequence of
407Google Test not using exceptions. By placing it in a non-void function
408you'll get a confusing compile error like
409`"error: void value not ignored as it ought to be"`.
410
411If you need to use assertions in a function that returns non-void, one option
412is to make the function return the value in an out parameter instead. For
413example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
414need to make sure that `*result` contains some sensible value even when the
415function returns prematurely. As the function now returns `void`, you can use
416any assertion inside of it.
417
418If changing the function's type is not an option, you should just use
419assertions that generate non-fatal failures, such as `ADD_FAILURE*` and
420`EXPECT_*`.
421
422_Note_: Constructors and destructors are not considered void-returning
423functions, according to the C++ language specification, and so you may not use
424fatal assertions in them. You'll get a compilation error if you try. A simple
425workaround is to transfer the entire body of the constructor or destructor to a
426private void-returning method. However, you should be aware that a fatal
427assertion failure in a constructor does not terminate the current test, as your
428intuition might suggest; it merely returns from the constructor early, possibly
429leaving your object in a partially-constructed state. Likewise, a fatal
430assertion failure in a destructor may leave your object in a
431partially-destructed state. Use assertions carefully in these situations!
432
433# Death Tests #
434
435In many applications, there are assertions that can cause application failure
436if a condition is not met. These sanity checks, which ensure that the program
437is in a known good state, are there to fail at the earliest possible time after
438some program state is corrupted. If the assertion checks the wrong condition,
439then the program may proceed in an erroneous state, which could lead to memory
440corruption, security holes, or worse. Hence it is vitally important to test
441that such assertion statements work as expected.
442
443Since these precondition checks cause the processes to die, we call such tests
444_death tests_. More generally, any test that checks that a program terminates
445in an expected fashion is also a death test.
446
447If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#Catching_Failures.md).
448
449## How to Write a Death Test ##
450
451Google Test has the following macros to support death tests:
452
453| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
454|:--------------------|:-----------------------|:-------------|
455| `ASSERT_DEATH(`_statement, regex_`); | `EXPECT_DEATH(`_statement, regex_`); | _statement_ crashes with the given error |
456| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`); | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`); | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing |
457| `ASSERT_EXIT(`_statement, predicate, regex_`); | `EXPECT_EXIT(`_statement, predicate, regex_`); |_statement_ exits with the given error and its exit code matches _predicate_ |
458
459where _statement_ is a statement that is expected to cause the process to
460die, _predicate_ is a function or function object that evaluates an integer
461exit status, and _regex_ is a regular expression that the stderr output of
462_statement_ is expected to match. Note that _statement_ can be _any valid
463statement_ (including _compound statement_) and doesn't have to be an
464expression.
465
466As usual, the `ASSERT` variants abort the current test function, while the
467`EXPECT` variants do not.
468
469**Note:** We use the word "crash" here to mean that the process
470terminates with a _non-zero_ exit status code.  There are two
471possibilities: either the process has called `exit()` or `_exit()`
472with a non-zero value, or it may be killed by a signal.
473
474This means that if _statement_ terminates the process with a 0 exit
475code, it is _not_ considered a crash by `EXPECT_DEATH`.  Use
476`EXPECT_EXIT` instead if this is the case, or if you want to restrict
477the exit code more precisely.
478
479A predicate here must accept an `int` and return a `bool`. The death test
480succeeds only if the predicate returns `true`. Google Test defines a few
481predicates that handle the most common cases:
482
483```
484::testing::ExitedWithCode(exit_code)
485```
486
487This expression is `true` if the program exited normally with the given exit
488code.
489
490```
491::testing::KilledBySignal(signal_number)  // Not available on Windows.
492```
493
494This expression is `true` if the program was killed by the given signal.
495
496The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
497that verifies the process' exit code is non-zero.
498
499Note that a death test only cares about three things:
500
501  1. does _statement_ abort or exit the process?
502  1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_?  Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero?  And
503  1. does the stderr output match _regex_?
504
505In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process.
506
507To write a death test, simply use one of the above macros inside your test
508function. For example,
509
510```
511TEST(My*DeathTest*, Foo) {
512  // This death test uses a compound statement.
513  ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()");
514}
515TEST(MyDeathTest, NormalExit) {
516  EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
517}
518TEST(MyDeathTest, KillMyself) {
519  EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal");
520}
521```
522
523verifies that:
524
525  * calling `Foo(5)` causes the process to die with the given error message,
526  * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and
527  * calling `KillMyself()` kills the process with signal `SIGKILL`.
528
529The test function body may contain other assertions and statements as well, if
530necessary.
531
532_Important:_ We strongly recommend you to follow the convention of naming your
533test case (not test) `*DeathTest` when it contains a death test, as
534demonstrated in the above example. The `Death Tests And Threads` section below
535explains why.
536
537If a test fixture class is shared by normal tests and death tests, you
538can use typedef to introduce an alias for the fixture class and avoid
539duplicating its code:
540```
541class FooTest : public ::testing::Test { ... };
542
543typedef FooTest FooDeathTest;
544
545TEST_F(FooTest, DoesThis) {
546  // normal test
547}
548
549TEST_F(FooDeathTest, DoesThat) {
550  // death test
551}
552```
553
554_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0).  `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0.
555
556## Regular Expression Syntax ##
557
558On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the
559[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
560syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
561
562On Windows, Google Test uses its own simple regular expression
563implementation. It lacks many features you can find in POSIX extended
564regular expressions.  For example, we don't support union (`"x|y"`),
565grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count
566(`"x{5,7}"`), among others. Below is what we do support (`A` denotes a
567literal character, period (`.`), or a single `\\` escape sequence; `x`
568and `y` denote regular expressions.):
569
570| `c` | matches any literal character `c` |
571|:----|:----------------------------------|
572| `\\d` | matches any decimal digit         |
573| `\\D` | matches any character that's not a decimal digit |
574| `\\f` | matches `\f`                      |
575| `\\n` | matches `\n`                      |
576| `\\r` | matches `\r`                      |
577| `\\s` | matches any ASCII whitespace, including `\n` |
578| `\\S` | matches any character that's not a whitespace |
579| `\\t` | matches `\t`                      |
580| `\\v` | matches `\v`                      |
581| `\\w` | matches any letter, `_`, or decimal digit |
582| `\\W` | matches any character that `\\w` doesn't match |
583| `\\c` | matches any literal character `c`, which must be a punctuation |
584| `.` | matches any single character except `\n` |
585| `A?` | matches 0 or 1 occurrences of `A` |
586| `A*` | matches 0 or many occurrences of `A` |
587| `A+` | matches 1 or many occurrences of `A` |
588| `^` | matches the beginning of a string (not that of each line) |
589| `$` | matches the end of a string (not that of each line) |
590| `xy` | matches `x` followed by `y`       |
591
592To help you determine which capability is available on your system,
593Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX
594extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses
595the simple version.  If you want your death tests to work in both
596cases, you can either `#if` on these macros or use the more limited
597syntax only.
598
599## How It Works ##
600
601Under the hood, `ASSERT_EXIT()` spawns a new process and executes the
602death test statement in that process. The details of of how precisely
603that happens depend on the platform and the variable
604`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the
605command-line flag `--gtest_death_test_style`).
606
607  * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which:
608    * If the variable's value is `"fast"`, the death test statement is immediately executed.
609    * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run.
610  * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX.
611
612Other values for the variable are illegal and will cause the death test to
613fail. Currently, the flag's default value is `"fast"`. However, we reserve the
614right to change it in the future. Therefore, your tests should not depend on
615this.
616
617In either case, the parent process waits for the child process to complete, and checks that
618
619  1. the child's exit status satisfies the predicate, and
620  1. the child's stderr matches the regular expression.
621
622If the death test statement runs to completion without dying, the child
623process will nonetheless terminate, and the assertion fails.
624
625## Death Tests And Threads ##
626
627The reason for the two death test styles has to do with thread safety. Due to
628well-known problems with forking in the presence of threads, death tests should
629be run in a single-threaded context. Sometimes, however, it isn't feasible to
630arrange that kind of environment. For example, statically-initialized modules
631may start threads before main is ever reached. Once threads have been created,
632it may be difficult or impossible to clean them up.
633
634Google Test has three features intended to raise awareness of threading issues.
635
636  1. A warning is emitted if multiple threads are running when a death test is encountered.
637  1. Test cases with a name ending in "DeathTest" are run before all other tests.
638  1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads.
639
640It's perfectly fine to create threads inside a death test statement; they are
641executed in a separate process and cannot affect the parent.
642
643## Death Test Styles ##
644
645The "threadsafe" death test style was introduced in order to help mitigate the
646risks of testing in a possibly multithreaded environment. It trades increased
647test execution time (potentially dramatically so) for improved thread safety.
648We suggest using the faster, default "fast" style unless your test has specific
649problems with it.
650
651You can choose a particular style of death tests by setting the flag
652programmatically:
653
654```
655::testing::FLAGS_gtest_death_test_style = "threadsafe";
656```
657
658You can do this in `main()` to set the style for all death tests in the
659binary, or in individual tests. Recall that flags are saved before running each
660test and restored afterwards, so you need not do that yourself. For example:
661
662```
663TEST(MyDeathTest, TestOne) {
664  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
665  // This test is run in the "threadsafe" style:
666  ASSERT_DEATH(ThisShouldDie(), "");
667}
668
669TEST(MyDeathTest, TestTwo) {
670  // This test is run in the "fast" style:
671  ASSERT_DEATH(ThisShouldDie(), "");
672}
673
674int main(int argc, char** argv) {
675  ::testing::InitGoogleTest(&argc, argv);
676  ::testing::FLAGS_gtest_death_test_style = "fast";
677  return RUN_ALL_TESTS();
678}
679```
680
681## Caveats ##
682
683The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement
684except that it can not return from the current function. This means
685_statement_ should not contain `return` or a macro that might return (e.g.
686`ASSERT_TRUE()` ). If _statement_ returns before it crashes, Google Test will
687print an error message, and the test will fail.
688
689Since _statement_ runs in the child process, any in-memory side effect (e.g.
690modifying a variable, releasing memory, etc) it causes will _not_ be observable
691in the parent process. In particular, if you release memory in a death test,
692your program will fail the heap check as the parent process will never see the
693memory reclaimed. To solve this problem, you can
694
695  1. try not to free memory in a death test;
696  1. free the memory again in the parent process; or
697  1. do not use the heap checker in your program.
698
699Due to an implementation detail, you cannot place multiple death test
700assertions on the same line; otherwise, compilation will fail with an unobvious
701error message.
702
703Despite the improved thread safety afforded by the "threadsafe" style of death
704test, thread problems such as deadlock are still possible in the presence of
705handlers registered with `pthread_atfork(3)`.
706
707# Using Assertions in Sub-routines #
708
709## Adding Traces to Assertions ##
710
711If a test sub-routine is called from several places, when an assertion
712inside it fails, it can be hard to tell which invocation of the
713sub-routine the failure is from.  You can alleviate this problem using
714extra logging or custom failure messages, but that usually clutters up
715your tests. A better solution is to use the `SCOPED_TRACE` macro:
716
717| `SCOPED_TRACE(`_message_`);` |
718|:-----------------------------|
719
720where _message_ can be anything streamable to `std::ostream`. This
721macro will cause the current file name, line number, and the given
722message to be added in every failure message. The effect will be
723undone when the control leaves the current lexical scope.
724
725For example,
726
727```
72810: void Sub1(int n) {
72911:   EXPECT_EQ(1, Bar(n));
73012:   EXPECT_EQ(2, Bar(n + 1));
73113: }
73214:
73315: TEST(FooTest, Bar) {
73416:   {
73517:     SCOPED_TRACE("A");  // This trace point will be included in
73618:                         // every failure in this scope.
73719:     Sub1(1);
73820:   }
73921:   // Now it won't.
74022:   Sub1(9);
74123: }
742```
743
744could result in messages like these:
745
746```
747path/to/foo_test.cc:11: Failure
748Value of: Bar(n)
749Expected: 1
750  Actual: 2
751   Trace:
752path/to/foo_test.cc:17: A
753
754path/to/foo_test.cc:12: Failure
755Value of: Bar(n + 1)
756Expected: 2
757  Actual: 3
758```
759
760Without the trace, it would've been difficult to know which invocation
761of `Sub1()` the two failures come from respectively. (You could add an
762extra message to each assertion in `Sub1()` to indicate the value of
763`n`, but that's tedious.)
764
765Some tips on using `SCOPED_TRACE`:
766
767  1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site.
768  1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from.
769  1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`.
770  1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered.
771  1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file!
772
773_Availability:_ Linux, Windows, Mac.
774
775## Propagating Fatal Failures ##
776
777A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
778when they fail they only abort the _current function_, not the entire test. For
779example, the following test will segfault:
780```
781void Subroutine() {
782  // Generates a fatal failure and aborts the current function.
783  ASSERT_EQ(1, 2);
784  // The following won't be executed.
785  ...
786}
787
788TEST(FooTest, Bar) {
789  Subroutine();
790  // The intended behavior is for the fatal failure
791  // in Subroutine() to abort the entire test.
792  // The actual behavior: the function goes on after Subroutine() returns.
793  int* p = NULL;
794  *p = 3; // Segfault!
795}
796```
797
798Since we don't use exceptions, it is technically impossible to
799implement the intended behavior here.  To alleviate this, Google Test
800provides two solutions.  You could use either the
801`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
802`HasFatalFailure()` function.  They are described in the following two
803subsections.
804
805
806
807### Asserting on Subroutines ###
808
809As shown above, if your test calls a subroutine that has an `ASSERT_*`
810failure in it, the test will continue after the subroutine
811returns. This may not be what you want.
812
813Often people want fatal failures to propagate like exceptions.  For
814that Google Test offers the following macros:
815
816| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
817|:--------------------|:-----------------------|:-------------|
818| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. |
819
820Only failures in the thread that executes the assertion are checked to
821determine the result of this type of assertions.  If _statement_
822creates new threads, failures in these threads are ignored.
823
824Examples:
825
826```
827ASSERT_NO_FATAL_FAILURE(Foo());
828
829int i;
830EXPECT_NO_FATAL_FAILURE({
831  i = Bar();
832});
833```
834
835_Availability:_ Linux, Windows, Mac. Assertions from multiple threads
836are currently not supported.
837
838### Checking for Failures in the Current Test ###
839
840`HasFatalFailure()` in the `::testing::Test` class returns `true` if an
841assertion in the current test has suffered a fatal failure. This
842allows functions to catch fatal failures in a sub-routine and return
843early.
844
845```
846class Test {
847 public:
848  ...
849  static bool HasFatalFailure();
850};
851```
852
853The typical usage, which basically simulates the behavior of a thrown
854exception, is:
855
856```
857TEST(FooTest, Bar) {
858  Subroutine();
859  // Aborts if Subroutine() had a fatal failure.
860  if (HasFatalFailure())
861    return;
862  // The following won't be executed.
863  ...
864}
865```
866
867If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
868fixture, you must add the `::testing::Test::` prefix, as in:
869
870```
871if (::testing::Test::HasFatalFailure())
872  return;
873```
874
875Similarly, `HasNonfatalFailure()` returns `true` if the current test
876has at least one non-fatal failure, and `HasFailure()` returns `true`
877if the current test has at least one failure of either kind.
878
879_Availability:_ Linux, Windows, Mac.  `HasNonfatalFailure()` and
880`HasFailure()` are available since version 1.4.0.
881
882# Logging Additional Information #
883
884In your test code, you can call `RecordProperty("key", value)` to log
885additional information, where `value` can be either a C string or a 32-bit
886integer. The _last_ value recorded for a key will be emitted to the XML output
887if you specify one. For example, the test
888
889```
890TEST_F(WidgetUsageTest, MinAndMaxWidgets) {
891  RecordProperty("MaximumWidgets", ComputeMaxUsage());
892  RecordProperty("MinimumWidgets", ComputeMinUsage());
893}
894```
895
896will output XML like this:
897
898```
899...
900  <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest"
901            MaximumWidgets="12"
902            MinimumWidgets="9" />
903...
904```
905
906_Note_:
907  * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class.
908  * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`,     `time`, and `classname`).
909
910_Availability_: Linux, Windows, Mac.
911
912# Sharing Resources Between Tests in the Same Test Case #
913
914
915
916Google Test creates a new test fixture object for each test in order to make
917tests independent and easier to debug. However, sometimes tests use resources
918that are expensive to set up, making the one-copy-per-test model prohibitively
919expensive.
920
921If the tests don't change the resource, there's no harm in them sharing a
922single resource copy. So, in addition to per-test set-up/tear-down, Google Test
923also supports per-test-case set-up/tear-down. To use it:
924
925  1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources.
926  1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down.
927
928That's it! Google Test automatically calls `SetUpTestCase()` before running the
929_first test_ in the `FooTest` test case (i.e. before creating the first
930`FooTest` object), and calls `TearDownTestCase()` after running the _last test_
931in it (i.e. after deleting the last `FooTest` object). In between, the tests
932can use the shared resources.
933
934Remember that the test order is undefined, so your code can't depend on a test
935preceding or following another. Also, the tests must either not modify the
936state of any shared resource, or, if they do modify the state, they must
937restore the state to its original value before passing control to the next
938test.
939
940Here's an example of per-test-case set-up and tear-down:
941```
942class FooTest : public ::testing::Test {
943 protected:
944  // Per-test-case set-up.
945  // Called before the first test in this test case.
946  // Can be omitted if not needed.
947  static void SetUpTestCase() {
948    shared_resource_ = new ...;
949  }
950
951  // Per-test-case tear-down.
952  // Called after the last test in this test case.
953  // Can be omitted if not needed.
954  static void TearDownTestCase() {
955    delete shared_resource_;
956    shared_resource_ = NULL;
957  }
958
959  // You can define per-test set-up and tear-down logic as usual.
960  virtual void SetUp() { ... }
961  virtual void TearDown() { ... }
962
963  // Some expensive resource shared by all tests.
964  static T* shared_resource_;
965};
966
967T* FooTest::shared_resource_ = NULL;
968
969TEST_F(FooTest, Test1) {
970  ... you can refer to shared_resource here ...
971}
972TEST_F(FooTest, Test2) {
973  ... you can refer to shared_resource here ...
974}
975```
976
977_Availability:_ Linux, Windows, Mac.
978
979# Global Set-Up and Tear-Down #
980
981Just as you can do set-up and tear-down at the test level and the test case
982level, you can also do it at the test program level. Here's how.
983
984First, you subclass the `::testing::Environment` class to define a test
985environment, which knows how to set-up and tear-down:
986
987```
988class Environment {
989 public:
990  virtual ~Environment() {}
991  // Override this to define how to set up the environment.
992  virtual void SetUp() {}
993  // Override this to define how to tear down the environment.
994  virtual void TearDown() {}
995};
996```
997
998Then, you register an instance of your environment class with Google Test by
999calling the `::testing::AddGlobalTestEnvironment()` function:
1000
1001```
1002Environment* AddGlobalTestEnvironment(Environment* env);
1003```
1004
1005Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
1006the environment object, then runs the tests if there was no fatal failures, and
1007finally calls `TearDown()` of the environment object.
1008
1009It's OK to register multiple environment objects. In this case, their `SetUp()`
1010will be called in the order they are registered, and their `TearDown()` will be
1011called in the reverse order.
1012
1013Note that Google Test takes ownership of the registered environment objects.
1014Therefore **do not delete them** by yourself.
1015
1016You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is
1017called, probably in `main()`. If you use `gtest_main`, you need to      call
1018this before `main()` starts for it to take effect. One way to do this is to
1019define a global variable like this:
1020
1021```
1022::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
1023```
1024
1025However, we strongly recommend you to write your own `main()` and call
1026`AddGlobalTestEnvironment()` there, as relying on initialization of global
1027variables makes the code harder to read and may cause problems when you
1028register multiple environments from different translation units and the
1029environments have dependencies among them (remember that the compiler doesn't
1030guarantee the order in which global variables from different translation units
1031are initialized).
1032
1033_Availability:_ Linux, Windows, Mac.
1034
1035
1036# Value Parameterized Tests #
1037
1038_Value-parameterized tests_ allow you to test your code with different
1039parameters without writing multiple copies of the same test.
1040
1041Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag.
1042
1043```
1044TEST(MyCodeTest, TestFoo) {
1045  // A code to test foo().
1046}
1047```
1048
1049Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code.
1050
1051```
1052void TestFooHelper(bool flag_value) {
1053  flag = flag_value;
1054  // A code to test foo().
1055}
1056
1057TEST(MyCodeTest, TestFooo) {
1058  TestFooHelper(false);
1059  TestFooHelper(true);
1060}
1061```
1062
1063But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred?
1064
1065Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values.
1066
1067Here are some other situations when value-parameterized tests come handy:
1068
1069  * You wan to test different implementations of an OO interface.
1070  * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it!
1071
1072## How to Write Value-Parameterized Tests ##
1073
1074To write value-parameterized tests, first you should define a fixture
1075class. It must be derived from `::testing::TestWithParam<T>`, where `T`
1076is the type of your parameter values. `TestWithParam<T>` is itself
1077derived from `::testing::Test`. `T` can be any copyable type. If it's
1078a raw pointer, you are responsible for managing the lifespan of the
1079pointed values.
1080
1081```
1082class FooTest : public ::testing::TestWithParam<const char*> {
1083  // You can implement all the usual fixture class members here.
1084  // To access the test parameter, call GetParam() from class
1085  // TestWithParam<T>.
1086};
1087```
1088
1089Then, use the `TEST_P` macro to define as many test patterns using
1090this fixture as you want.  The `_P` suffix is for "parameterized" or
1091"pattern", whichever you prefer to think.
1092
1093```
1094TEST_P(FooTest, DoesBlah) {
1095  // Inside a test, access the test parameter with the GetParam() method
1096  // of the TestWithParam<T> class:
1097  EXPECT_TRUE(foo.Blah(GetParam()));
1098  ...
1099}
1100
1101TEST_P(FooTest, HasBlahBlah) {
1102  ...
1103}
1104```
1105
1106Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test
1107case with any set of parameters you want. Google Test defines a number of
1108functions for generating test parameters. They return what we call
1109(surprise!) _parameter generators_. Here is a summary of them,
1110which are all in the `testing` namespace:
1111
1112| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
1113|:----------------------------|:------------------------------------------------------------------------------------------------------------------|
1114| `Values(v1, v2, ..., vN)`   | Yields values `{v1, v2, ..., vN}`.                                                                                |
1115| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`.                  |
1116| `Bool()`                    | Yields sequence `{false, true}`.                                                                                  |
1117| `Combine(g1, g2, ..., gN)`  | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `<tr1/tuple>` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-port.h) for more information. |
1118
1119For more details, see the comments at the definitions of these functions in the [source code](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-param-test.h).
1120
1121The following statement will instantiate tests from the `FooTest` test case
1122each with parameter values `"meeny"`, `"miny"`, and `"moe"`.
1123
1124```
1125INSTANTIATE_TEST_CASE_P(InstantiationName,
1126                        FooTest,
1127                        ::testing::Values("meeny", "miny", "moe"));
1128```
1129
1130To distinguish different instances of the pattern (yes, you can
1131instantiate it more than once), the first argument to
1132`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual
1133test case name. Remember to pick unique prefixes for different
1134instantiations. The tests from the instantiation above will have these
1135names:
1136
1137  * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
1138  * `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
1139  * `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
1140  * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
1141  * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
1142  * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
1143
1144You can use these names in [--gtest\_filter](#Running_a_Subset_of_the_Tests.md).
1145
1146This statement will instantiate all tests from `FooTest` again, each
1147with parameter values `"cat"` and `"dog"`:
1148
1149```
1150const char* pets[] = {"cat", "dog"};
1151INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest,
1152                        ::testing::ValuesIn(pets));
1153```
1154
1155The tests from the instantiation above will have these names:
1156
1157  * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
1158  * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
1159  * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
1160  * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
1161
1162Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_
1163tests in the given test case, whether their definitions come before or
1164_after_ the `INSTANTIATE_TEST_CASE_P` statement.
1165
1166You can see
1167[these](http://code.google.com/p/googletest/source/browse/trunk/samples/sample7_unittest.cc)
1168[files](http://code.google.com/p/googletest/source/browse/trunk/samples/sample8_unittest.cc) for more examples.
1169
1170_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0.
1171
1172## Creating Value-Parameterized Abstract Tests ##
1173
1174In the above, we define and instantiate `FooTest` in the same source
1175file. Sometimes you may want to define value-parameterized tests in a
1176library and let other people instantiate them later. This pattern is
1177known as <i>abstract tests</i>. As an example of its application, when you
1178are designing an interface you can write a standard suite of abstract
1179tests (perhaps using a factory function as the test parameter) that
1180all implementations of the interface are expected to pass. When
1181someone implements the interface, he can instantiate your suite to get
1182all the interface-conformance tests for free.
1183
1184To define abstract tests, you should organize your code like this:
1185
1186  1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests.
1187  1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests.
1188
1189Once they are defined, you can instantiate them by including
1190`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking
1191with `foo_param_test.cc`. You can instantiate the same abstract test
1192case multiple times, possibly in different source files.
1193
1194# Typed Tests #
1195
1196Suppose you have multiple implementations of the same interface and
1197want to make sure that all of them satisfy some common requirements.
1198Or, you may have defined several types that are supposed to conform to
1199the same "concept" and you want to verify it.  In both cases, you want
1200the same test logic repeated for different types.
1201
1202While you can write one `TEST` or `TEST_F` for each type you want to
1203test (and you may even factor the test logic into a function template
1204that you invoke from the `TEST`), it's tedious and doesn't scale:
1205if you want _m_ tests over _n_ types, you'll end up writing _m\*n_
1206`TEST`s.
1207
1208_Typed tests_ allow you to repeat the same test logic over a list of
1209types.  You only need to write the test logic once, although you must
1210know the type list when writing typed tests.  Here's how you do it:
1211
1212First, define a fixture class template.  It should be parameterized
1213by a type.  Remember to derive it from `::testing::Test`:
1214
1215```
1216template <typename T>
1217class FooTest : public ::testing::Test {
1218 public:
1219  ...
1220  typedef std::list<T> List;
1221  static T shared_;
1222  T value_;
1223};
1224```
1225
1226Next, associate a list of types with the test case, which will be
1227repeated for each type in the list:
1228
1229```
1230typedef ::testing::Types<char, int, unsigned int> MyTypes;
1231TYPED_TEST_CASE(FooTest, MyTypes);
1232```
1233
1234The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse
1235correctly.  Otherwise the compiler will think that each comma in the
1236type list introduces a new macro argument.
1237
1238Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test
1239for this test case.  You can repeat this as many times as you want:
1240
1241```
1242TYPED_TEST(FooTest, DoesBlah) {
1243  // Inside a test, refer to the special name TypeParam to get the type
1244  // parameter.  Since we are inside a derived class template, C++ requires
1245  // us to visit the members of FooTest via 'this'.
1246  TypeParam n = this->value_;
1247
1248  // To visit static members of the fixture, add the 'TestFixture::'
1249  // prefix.
1250  n += TestFixture::shared_;
1251
1252  // To refer to typedefs in the fixture, add the 'typename TestFixture::'
1253  // prefix.  The 'typename' is required to satisfy the compiler.
1254  typename TestFixture::List values;
1255  values.push_back(n);
1256  ...
1257}
1258
1259TYPED_TEST(FooTest, HasPropertyA) { ... }
1260```
1261
1262You can see `samples/sample6_unittest.cc` for a complete example.
1263
1264_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1265since version 1.1.0.
1266
1267# Type-Parameterized Tests #
1268
1269_Type-parameterized tests_ are like typed tests, except that they
1270don't require you to know the list of types ahead of time.  Instead,
1271you can define the test logic first and instantiate it with different
1272type lists later.  You can even instantiate it more than once in the
1273same program.
1274
1275If you are designing an interface or concept, you can define a suite
1276of type-parameterized tests to verify properties that any valid
1277implementation of the interface/concept should have.  Then, the author
1278of each implementation can just instantiate the test suite with his
1279type to verify that it conforms to the requirements, without having to
1280write similar tests repeatedly.  Here's an example:
1281
1282First, define a fixture class template, as we did with typed tests:
1283
1284```
1285template <typename T>
1286class FooTest : public ::testing::Test {
1287  ...
1288};
1289```
1290
1291Next, declare that you will define a type-parameterized test case:
1292
1293```
1294TYPED_TEST_CASE_P(FooTest);
1295```
1296
1297The `_P` suffix is for "parameterized" or "pattern", whichever you
1298prefer to think.
1299
1300Then, use `TYPED_TEST_P()` to define a type-parameterized test.  You
1301can repeat this as many times as you want:
1302
1303```
1304TYPED_TEST_P(FooTest, DoesBlah) {
1305  // Inside a test, refer to TypeParam to get the type parameter.
1306  TypeParam n = 0;
1307  ...
1308}
1309
1310TYPED_TEST_P(FooTest, HasPropertyA) { ... }
1311```
1312
1313Now the tricky part: you need to register all test patterns using the
1314`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them.
1315The first argument of the macro is the test case name; the rest are
1316the names of the tests in this test case:
1317
1318```
1319REGISTER_TYPED_TEST_CASE_P(FooTest,
1320                           DoesBlah, HasPropertyA);
1321```
1322
1323Finally, you are free to instantiate the pattern with the types you
1324want.  If you put the above code in a header file, you can `#include`
1325it in multiple C++ source files and instantiate it multiple times.
1326
1327```
1328typedef ::testing::Types<char, int, unsigned int> MyTypes;
1329INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
1330```
1331
1332To distinguish different instances of the pattern, the first argument
1333to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be
1334added to the actual test case name.  Remember to pick unique prefixes
1335for different instances.
1336
1337In the special case where the type list contains only one type, you
1338can write that type directly without `::testing::Types<...>`, like this:
1339
1340```
1341INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
1342```
1343
1344You can see `samples/sample6_unittest.cc` for a complete example.
1345
1346_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1347since version 1.1.0.
1348
1349# Testing Private Code #
1350
1351If you change your software's internal implementation, your tests should not
1352break as long as the change is not observable by users. Therefore, per the
1353_black-box testing principle_, most of the time you should test your code
1354through its public interfaces.
1355
1356If you still find yourself needing to test internal implementation code,
1357consider if there's a better design that wouldn't require you to do so. If you
1358absolutely have to test non-public interface code though, you can. There are
1359two cases to consider:
1360
1361  * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and
1362  * Private or protected class members
1363
1364## Static Functions ##
1365
1366Both static functions and definitions/declarations in an unnamed namespace are
1367only visible within the same translation unit. To test them, you can `#include`
1368the entire `.cc` file being tested in your `*_test.cc` file. (#including `.cc`
1369files is not a good way to reuse code - you should not do this in production
1370code!)
1371
1372However, a better approach is to move the private code into the
1373`foo::internal` namespace, where `foo` is the namespace your project normally
1374uses, and put the private declarations in a `*-internal.h` file. Your
1375production `.cc` files and your tests are allowed to include this internal
1376header, but your clients are not. This way, you can fully test your internal
1377implementation without leaking it to your clients.
1378
1379## Private Class Members ##
1380
1381Private class members are only accessible from within the class or by friends.
1382To access a class' private members, you can declare your test fixture as a
1383friend to the class and define accessors in your fixture. Tests using the
1384fixture can then access the private members of your production class via the
1385accessors in the fixture. Note that even though your fixture is a friend to
1386your production class, your tests are not automatically friends to it, as they
1387are technically defined in sub-classes of the fixture.
1388
1389Another way to test private members is to refactor them into an implementation
1390class, which is then declared in a `*-internal.h` file. Your clients aren't
1391allowed to include this header but your tests can. Such is called the Pimpl
1392(Private Implementation) idiom.
1393
1394Or, you can declare an individual test as a friend of your class by adding this
1395line in the class body:
1396
1397```
1398FRIEND_TEST(TestCaseName, TestName);
1399```
1400
1401For example,
1402```
1403// foo.h
1404#include <gtest/gtest_prod.h>
1405
1406// Defines FRIEND_TEST.
1407class Foo {
1408  ...
1409 private:
1410  FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
1411  int Bar(void* x);
1412};
1413
1414// foo_test.cc
1415...
1416TEST(FooTest, BarReturnsZeroOnNull) {
1417  Foo foo;
1418  EXPECT_EQ(0, foo.Bar(NULL));
1419  // Uses Foo's private member Bar().
1420}
1421```
1422
1423Pay special attention when your class is defined in a namespace, as you should
1424define your test fixtures and tests in the same namespace if you want them to
1425be friends of your class. For example, if the code to be tested looks like:
1426
1427```
1428namespace my_namespace {
1429
1430class Foo {
1431  friend class FooTest;
1432  FRIEND_TEST(FooTest, Bar);
1433  FRIEND_TEST(FooTest, Baz);
1434  ...
1435  definition of the class Foo
1436  ...
1437};
1438
1439}  // namespace my_namespace
1440```
1441
1442Your test code should be something like:
1443
1444```
1445namespace my_namespace {
1446class FooTest : public ::testing::Test {
1447 protected:
1448  ...
1449};
1450
1451TEST_F(FooTest, Bar) { ... }
1452TEST_F(FooTest, Baz) { ... }
1453
1454}  // namespace my_namespace
1455```
1456
1457# Catching Failures #
1458
1459If you are building a testing utility on top of Google Test, you'll
1460want to test your utility.  What framework would you use to test it?
1461Google Test, of course.
1462
1463The challenge is to verify that your testing utility reports failures
1464correctly.  In frameworks that report a failure by throwing an
1465exception, you could catch the exception and assert on it.  But Google
1466Test doesn't use exceptions, so how do we test that a piece of code
1467generates an expected failure?
1468
1469`<gtest/gtest-spi.h>` contains some constructs to do this.  After
1470#including this header, you can use
1471
1472| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` |
1473|:--------------------------------------------------|
1474
1475to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure
1476whose message contains the given _substring_, or use
1477
1478| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` |
1479|:-----------------------------------------------------|
1480
1481if you are expecting a non-fatal (e.g. `EXPECT_*`) failure.
1482
1483For technical reasons, there are some caveats:
1484
1485  1. You cannot stream a failure message to either macro.
1486  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object.
1487  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value.
1488
1489_Note:_ Google Test is designed with threads in mind.  Once the
1490synchronization primitives in `<gtest/internal/gtest-port.h>` have
1491been implemented, Google Test will become thread-safe, meaning that
1492you can then use assertions in multiple threads concurrently.  Before
1493
1494that, however, Google Test only supports single-threaded usage.  Once
1495thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()`
1496will capture failures in the current thread only. If _statement_
1497creates new threads, failures in these threads will be ignored.  If
1498you want to capture failures from all threads instead, you should use
1499the following macros:
1500
1501| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1502|:-----------------------------------------------------------------|
1503| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1504
1505# Getting the Current Test's Name #
1506
1507Sometimes a function may need to know the name of the currently running test.
1508For example, you may be using the `SetUp()` method of your test fixture to set
1509the golden file name based on which test is running. The `::testing::TestInfo`
1510class has this information:
1511
1512```
1513namespace testing {
1514
1515class TestInfo {
1516 public:
1517  // Returns the test case name and the test name, respectively.
1518  //
1519  // Do NOT delete or free the return value - it's managed by the
1520  // TestInfo class.
1521  const char* test_case_name() const;
1522  const char* name() const;
1523};
1524
1525}  // namespace testing
1526```
1527
1528
1529> To obtain a `TestInfo` object for the currently running test, call
1530`current_test_info()` on the `UnitTest` singleton object:
1531
1532```
1533// Gets information about the currently running test.
1534// Do NOT delete the returned object - it's managed by the UnitTest class.
1535const ::testing::TestInfo* const test_info =
1536  ::testing::UnitTest::GetInstance()->current_test_info();
1537printf("We are in test %s of test case %s.\n",
1538       test_info->name(), test_info->test_case_name());
1539```
1540
1541`current_test_info()` returns a null pointer if no test is running. In
1542particular, you cannot find the test case name in `TestCaseSetUp()`,
1543`TestCaseTearDown()` (where you know the test case name implicitly), or
1544functions called from them.
1545
1546_Availability:_ Linux, Windows, Mac.
1547
1548# Extending Google Test by Handling Test Events #
1549
1550Google Test provides an <b>event listener API</b> to let you receive
1551notifications about the progress of a test program and test
1552failures. The events you can listen to include the start and end of
1553the test program, a test case, or a test method, among others. You may
1554use this API to augment or replace the standard console output,
1555replace the XML output, or provide a completely different form of
1556output, such as a GUI or a database. You can also use test events as
1557checkpoints to implement a resource leak checker, for example.
1558
1559_Availability:_ Linux, Windows, Mac; since v1.4.0.
1560
1561## Defining Event Listeners ##
1562
1563To define a event listener, you subclass either
1564[testing::TestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#855)
1565or [testing::EmptyTestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#905).
1566The former is an (abstract) interface, where <i>each pure virtual method<br>
1567can be overridden to handle a test event</i> (For example, when a test
1568starts, the `OnTestStart()` method will be called.). The latter provides
1569an empty implementation of all methods in the interface, such that a
1570subclass only needs to override the methods it cares about.
1571
1572When an event is fired, its context is passed to the handler function
1573as an argument. The following argument types are used:
1574  * [UnitTest](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#1007) reflects the state of the entire test program,
1575  * [TestCase](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#689) has information about a test case, which can contain one or more tests,
1576  * [TestInfo](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#599) contains the state of a test, and
1577  * [TestPartResult](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-test-part.h#42) represents the result of a test assertion.
1578
1579An event handler function can examine the argument it receives to find
1580out interesting information about the event and the test program's
1581state.  Here's an example:
1582
1583```
1584  class MinimalistPrinter : public ::testing::EmptyTestEventListener {
1585    // Called before a test starts.
1586    virtual void OnTestStart(const ::testing::TestInfo& test_info) {
1587      printf("*** Test %s.%s starting.\n",
1588             test_info.test_case_name(), test_info.name());
1589    }
1590
1591    // Called after a failed assertion or a SUCCESS().
1592    virtual void OnTestPartResult(
1593        const ::testing::TestPartResult& test_part_result) {
1594      printf("%s in %s:%d\n%s\n",
1595             test_part_result.failed() ? "*** Failure" : "Success",
1596             test_part_result.file_name(),
1597             test_part_result.line_number(),
1598             test_part_result.summary());
1599    }
1600
1601    // Called after a test ends.
1602    virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
1603      printf("*** Test %s.%s ending.\n",
1604             test_info.test_case_name(), test_info.name());
1605    }
1606  };
1607```
1608
1609## Using Event Listeners ##
1610
1611To use the event listener you have defined, add an instance of it to
1612the Google Test event listener list (represented by class
1613[TestEventListeners](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#929)
1614- note the "s" at the end of the name) in your
1615`main()` function, before calling `RUN_ALL_TESTS()`:
1616```
1617int main(int argc, char** argv) {
1618  ::testing::InitGoogleTest(&argc, argv);
1619  // Gets hold of the event listener list.
1620  ::testing::TestEventListeners& listeners =
1621      ::testing::UnitTest::GetInstance()->listeners();
1622  // Adds a listener to the end.  Google Test takes the ownership.
1623  listeners.Append(new MinimalistPrinter);
1624  return RUN_ALL_TESTS();
1625}
1626```
1627
1628There's only one problem: the default test result printer is still in
1629effect, so its output will mingle with the output from your minimalist
1630printer. To suppress the default printer, just release it from the
1631event listener list and delete it. You can do so by adding one line:
1632```
1633  ...
1634  delete listeners.Release(listeners.default_result_printer());
1635  listeners.Append(new MinimalistPrinter);
1636  return RUN_ALL_TESTS();
1637```
1638
1639Now, sit back and enjoy a completely different output from your
1640tests. For more details, you can read this
1641[sample](http://code.google.com/p/googletest/source/browse/trunk/samples/sample9_unittest.cc).
1642
1643You may append more than one listener to the list. When an `On*Start()`
1644or `OnTestPartResult()` event is fired, the listeners will receive it in
1645the order they appear in the list (since new listeners are added to
1646the end of the list, the default text printer and the default XML
1647generator will receive the event first). An `On*End()` event will be
1648received by the listeners in the _reverse_ order. This allows output by
1649listeners added later to be framed by output from listeners added
1650earlier.
1651
1652## Generating Failures in Listeners ##
1653
1654You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`,
1655`FAIL()`, etc) when processing an event. There are some restrictions:
1656
1657  1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively).
1658  1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure.
1659
1660When you add listeners to the listener list, you should put listeners
1661that handle `OnTestPartResult()` _before_ listeners that can generate
1662failures. This ensures that failures generated by the latter are
1663attributed to the right test by the former.
1664
1665We have a sample of failure-raising listener
1666[here](http://code.google.com/p/googletest/source/browse/trunk/samples/sample10_unittest.cc).
1667
1668# Running Test Programs: Advanced Options #
1669
1670Google Test test programs are ordinary executables. Once built, you can run
1671them directly and affect their behavior via the following environment variables
1672and/or command line flags. For the flags to work, your programs must call
1673`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
1674
1675To see a list of supported flags and their usage, please run your test
1676program with the `--help` flag.  You can also use `-h`, `-?`, or `/?`
1677for short.  This feature is added in version 1.3.0.
1678
1679If an option is specified both by an environment variable and by a
1680flag, the latter takes precedence.  Most of the options can also be
1681set/read in code: to access the value of command line flag
1682`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`.  A common pattern is
1683to set the value of a flag before calling `::testing::InitGoogleTest()`
1684to change the default value of the flag:
1685```
1686int main(int argc, char** argv) {
1687  // Disables elapsed time by default.
1688  ::testing::GTEST_FLAG(print_time) = false;
1689
1690  // This allows the user to override the flag on the command line.
1691  ::testing::InitGoogleTest(&argc, argv);
1692
1693  return RUN_ALL_TESTS();
1694}
1695```
1696
1697## Selecting Tests ##
1698
1699This section shows various options for choosing which tests to run.
1700
1701### Listing Test Names ###
1702
1703Sometimes it is necessary to list the available tests in a program before
1704running them so that a filter may be applied if needed. Including the flag
1705`--gtest_list_tests` overrides all other flags and lists tests in the following
1706format:
1707```
1708TestCase1.
1709  TestName1
1710  TestName2
1711TestCase2.
1712  TestName
1713```
1714
1715None of the tests listed are actually run if the flag is provided. There is no
1716corresponding environment variable for this flag.
1717
1718_Availability:_ Linux, Windows, Mac.
1719
1720### Running a Subset of the Tests ###
1721
1722By default, a Google Test program runs all tests the user has defined.
1723Sometimes, you want to run only a subset of the tests (e.g. for debugging or
1724quickly verifying a change). If you set the `GTEST_FILTER` environment variable
1725or the `--gtest_filter` flag to a filter string, Google Test will only run the
1726tests whose full names (in the form of `TestCaseName.TestName`) match the
1727filter.
1728
1729The format of a filter is a '`:`'-separated list of wildcard patterns (called
1730the positive patterns) optionally followed by a '`-`' and another
1731'`:`'-separated pattern list (called the negative patterns). A test matches the
1732filter if and only if it matches any of the positive patterns but does not
1733match any of the negative patterns.
1734
1735A pattern may contain `'*'` (matches any string) or `'?'` (matches any single
1736character). For convenience, the filter `'*-NegativePatterns'` can be also
1737written as `'-NegativePatterns'`.
1738
1739For example:
1740
1741  * `./foo_test` Has no flag, and thus runs all its tests.
1742  * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value.
1743  * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`.
1744  * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`.
1745  * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.
1746  * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`.
1747
1748_Availability:_ Linux, Windows, Mac.
1749
1750### Temporarily Disabling Tests ###
1751
1752If you have a broken test that you cannot fix right away, you can add the
1753`DISABLED_` prefix to its name. This will exclude it from execution. This is
1754better than commenting out the code or using `#if 0`, as disabled tests are
1755still compiled (and thus won't rot).
1756
1757If you need to disable all tests in a test case, you can either add `DISABLED_`
1758to the front of the name of each test, or alternatively add it to the front of
1759the test case name.
1760
1761For example, the following tests won't be run by Google Test, even though they
1762will still be compiled:
1763
1764```
1765// Tests that Foo does Abc.
1766TEST(FooTest, DISABLED_DoesAbc) { ... }
1767
1768class DISABLED_BarTest : public ::testing::Test { ... };
1769
1770// Tests that Bar does Xyz.
1771TEST_F(DISABLED_BarTest, DoesXyz) { ... }
1772```
1773
1774_Note:_ This feature should only be used for temporary pain-relief. You still
1775have to fix the disabled tests at a later date. As a reminder, Google Test will
1776print a banner warning you if a test program contains any disabled tests.
1777
1778_Tip:_ You can easily count the number of disabled tests you have
1779using `grep`. This number can be used as a metric for improving your
1780test quality.
1781
1782_Availability:_ Linux, Windows, Mac.
1783
1784### Temporarily Enabling Disabled Tests ###
1785
1786To include [disabled tests](#Temporarily_Disabling_Tests.md) in test
1787execution, just invoke the test program with the
1788`--gtest_also_run_disabled_tests` flag or set the
1789`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other
1790than `0`.  You can combine this with the
1791[--gtest\_filter](#Running_a_Subset_of_the_Tests.md) flag to further select
1792which disabled tests to run.
1793
1794_Availability:_ Linux, Windows, Mac; since version 1.3.0.
1795
1796## Repeating the Tests ##
1797
1798Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
1799will fail only 1% of the time, making it rather hard to reproduce the bug under
1800a debugger. This can be a major source of frustration.
1801
1802The `--gtest_repeat` flag allows you to repeat all (or selected) test methods
1803in a program many times. Hopefully, a flaky test will eventually fail and give
1804you a chance to debug. Here's how to use it:
1805
1806| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. |
1807|:---------------------------------|:--------------------------------------------------------|
1808| `$ foo_test --gtest_repeat=-1`   | A negative count means repeating forever.               |
1809| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. |
1810| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. |
1811
1812If your test program contains global set-up/tear-down code registered
1813using `AddGlobalTestEnvironment()`, it will be repeated in each
1814iteration as well, as the flakiness may be in it. You can also specify
1815the repeat count by setting the `GTEST_REPEAT` environment variable.
1816
1817_Availability:_ Linux, Windows, Mac.
1818
1819## Shuffling the Tests ##
1820
1821You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
1822environment variable to `1`) to run the tests in a program in a random
1823order. This helps to reveal bad dependencies between tests.
1824
1825By default, Google Test uses a random seed calculated from the current
1826time. Therefore you'll get a different order every time. The console
1827output includes the random seed value, such that you can reproduce an
1828order-related test failure later. To specify the random seed
1829explicitly, use the `--gtest_random_seed=SEED` flag (or set the
1830`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer
1831between 0 and 99999. The seed value 0 is special: it tells Google Test
1832to do the default behavior of calculating the seed from the current
1833time.
1834
1835If you combine this with `--gtest_repeat=N`, Google Test will pick a
1836different random seed and re-shuffle the tests in each iteration.
1837
1838_Availability:_ Linux, Windows, Mac; since v1.4.0.
1839
1840## Controlling Test Output ##
1841
1842This section teaches how to tweak the way test results are reported.
1843
1844### Colored Terminal Output ###
1845
1846Google Test can use colors in its terminal output to make it easier to spot
1847the separation between tests, and whether tests passed.
1848
1849You can set the GTEST\_COLOR environment variable or set the `--gtest_color`
1850command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
1851disable colors, or let Google Test decide. When the value is `auto`, Google
1852Test will use colors if and only if the output goes to a terminal and (on
1853non-Windows platforms) the `TERM` environment variable is set to `xterm` or
1854`xterm-color`.
1855
1856_Availability:_ Linux, Windows, Mac.
1857
1858### Suppressing the Elapsed Time ###
1859
1860By default, Google Test prints the time it takes to run each test.  To
1861suppress that, run the test program with the `--gtest_print_time=0`
1862command line flag.  Setting the `GTEST_PRINT_TIME` environment
1863variable to `0` has the same effect.
1864
1865_Availability:_ Linux, Windows, Mac.  (In Google Test 1.3.0 and lower,
1866the default behavior is that the elapsed time is **not** printed.)
1867
1868### Generating an XML Report ###
1869
1870Google Test can emit a detailed XML report to a file in addition to its normal
1871textual output. The report contains the duration of each test, and thus can
1872help you identify slow tests.
1873
1874To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
1875`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will
1876create the file at the given location. You can also just use the string
1877`"xml"`, in which case the output can be found in the `test_detail.xml` file in
1878the current directory.
1879
1880If you specify a directory (for example, `"xml:output/directory/"` on Linux or
1881`"xml:output\directory\"` on Windows), Google Test will create the XML file in
1882that directory, named after the test executable (e.g. `foo_test.xml` for test
1883program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
1884over from a previous run), Google Test will pick a different name (e.g.
1885`foo_test_1.xml`) to avoid overwriting it.
1886
1887The report uses the format described here.  It is based on the
1888`junitreport` Ant task and can be parsed by popular continuous build
1889systems like [Hudson](https://hudson.dev.java.net/). Since that format
1890was originally intended for Java, a little interpretation is required
1891to make it apply to Google Test tests, as shown here:
1892
1893```
1894<testsuites name="AllTests" ...>
1895  <testsuite name="test_case_name" ...>
1896    <testcase name="test_name" ...>
1897      <failure message="..."/>
1898      <failure message="..."/>
1899      <failure message="..."/>
1900    </testcase>
1901  </testsuite>
1902</testsuites>
1903```
1904
1905  * The root `<testsuites>` element corresponds to the entire test program.
1906  * `<testsuite>` elements correspond to Google Test test cases.
1907  * `<testcase>` elements correspond to Google Test test functions.
1908
1909For instance, the following program
1910
1911```
1912TEST(MathTest, Addition) { ... }
1913TEST(MathTest, Subtraction) { ... }
1914TEST(LogicTest, NonContradiction) { ... }
1915```
1916
1917could generate this report:
1918
1919```
1920<?xml version="1.0" encoding="UTF-8"?>
1921<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests">
1922  <testsuite name="MathTest" tests="2" failures="1"* errors="0" time="15">
1923    <testcase name="Addition" status="run" time="7" classname="">
1924      <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type=""/>
1925      <failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type=""/>
1926    </testcase>
1927    <testcase name="Subtraction" status="run" time="5" classname="">
1928    </testcase>
1929  </testsuite>
1930  <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5">
1931    <testcase name="NonContradiction" status="run" time="5" classname="">
1932    </testcase>
1933  </testsuite>
1934</testsuites>
1935```
1936
1937Things to note:
1938
1939  * The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed.
1940  * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds.
1941  * Each `<failure>` element corresponds to a single failed Google Test assertion.
1942  * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts.
1943
1944_Availability:_ Linux, Windows, Mac.
1945
1946## Controlling How Failures Are Reported ##
1947
1948### Turning Assertion Failures into Break-Points ###
1949
1950When running test programs under a debugger, it's very convenient if the
1951debugger can catch an assertion failure and automatically drop into interactive
1952mode. Google Test's _break-on-failure_ mode supports this behavior.
1953
1954To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
1955other than `0` . Alternatively, you can use the `--gtest_break_on_failure`
1956command line flag.
1957
1958_Availability:_ Linux, Windows, Mac.
1959
1960### Suppressing Pop-ups Caused by Exceptions ###
1961
1962On Windows, Google Test may be used with exceptions enabled. Even when
1963exceptions are disabled, an application can still throw structured exceptions
1964(SEH's). If a test throws an exception, by default Google Test doesn't try to
1965catch it. Instead, you'll see a pop-up dialog, at which point you can attach
1966the process to a debugger and easily find out what went wrong.
1967
1968However, if you don't want to see the pop-ups (for example, if you run the
1969tests in a batch job), set the `GTEST_CATCH_EXCEPTIONS` environment variable to
1970a non- `0` value, or use the `--gtest_catch_exceptions` flag. Google Test now
1971catches all test-thrown exceptions and logs them as failures.
1972
1973_Availability:_ Windows. `GTEST_CATCH_EXCEPTIONS` and
1974`--gtest_catch_exceptions` have no effect on Google Test's behavior on Linux or
1975Mac, even if exceptions are enabled. It is possible to add support for catching
1976exceptions on these platforms, but it is not implemented yet.
1977
1978### Letting Another Testing Framework Drive ###
1979
1980If you work on a project that has already been using another testing
1981framework and is not ready to completely switch to Google Test yet,
1982you can get much of Google Test's benefit by using its assertions in
1983your existing tests.  Just change your `main()` function to look
1984like:
1985
1986```
1987#include <gtest/gtest.h>
1988
1989int main(int argc, char** argv) {
1990  ::testing::GTEST_FLAG(throw_on_failure) = true;
1991  // Important: Google Test must be initialized.
1992  ::testing::InitGoogleTest(&argc, argv);
1993
1994  ... whatever your existing testing framework requires ...
1995}
1996```
1997
1998With that, you can use Google Test assertions in addition to the
1999native assertions your testing framework provides, for example:
2000
2001```
2002void TestFooDoesBar() {
2003  Foo foo;
2004  EXPECT_LE(foo.Bar(1), 100);     // A Google Test assertion.
2005  CPPUNIT_ASSERT(foo.IsEmpty());  // A native assertion.
2006}
2007```
2008
2009If a Google Test assertion fails, it will print an error message and
2010throw an exception, which will be treated as a failure by your host
2011testing framework.  If you compile your code with exceptions disabled,
2012a failed Google Test assertion will instead exit your program with a
2013non-zero code, which will also signal a test failure to your test
2014runner.
2015
2016If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in
2017your `main()`, you can alternatively enable this feature by specifying
2018the `--gtest_throw_on_failure` flag on the command-line or setting the
2019`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value.
2020
2021_Availability:_ Linux, Windows, Mac; since v1.3.0.
2022
2023## Distributing Test Functions to Multiple Machines ##
2024
2025If you have more than one machine you can use to run a test program,
2026you might want to run the test functions in parallel and get the
2027result faster.  We call this technique _sharding_, where each machine
2028is called a _shard_.
2029
2030Google Test is compatible with test sharding.  To take advantage of
2031this feature, your test runner (not part of Google Test) needs to do
2032the following:
2033
2034  1. Allocate a number of machines (shards) to run the tests.
2035  1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards.  It must be the same for all shards.
2036  1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard.  Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`.
2037  1. Run the same test program on all shards.  When Google Test sees the above two environment variables, it will select a subset of the test functions to run.  Across all shards, each test function in the program will be run exactly once.
2038  1. Wait for all shards to finish, then collect and report the results.
2039
2040Your project may have tests that were written without Google Test and
2041thus don't understand this protocol.  In order for your test runner to
2042figure out which test supports sharding, it can set the environment
2043variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path.  If a
2044test program supports sharding, it will create this file to
2045acknowledge the fact (the actual contents of the file are not
2046important at this time; although we may stick some useful information
2047in it in the future.); otherwise it will not create it.
2048
2049Here's an example to make it clear.  Suppose you have a test program
2050`foo_test` that contains the following 5 test functions:
2051```
2052TEST(A, V)
2053TEST(A, W)
2054TEST(B, X)
2055TEST(B, Y)
2056TEST(B, Z)
2057```
2058and you have 3 machines at your disposal.  To run the test functions in
2059parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and
2060set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively.
2061Then you would run the same `foo_test` on each machine.
2062
2063Google Test reserves the right to change how the work is distributed
2064across the shards, but here's one possible scenario:
2065
2066  * Machine #0 runs `A.V` and `B.X`.
2067  * Machine #1 runs `A.W` and `B.Y`.
2068  * Machine #2 runs `B.Z`.
2069
2070_Availability:_ Linux, Windows, Mac; since version 1.3.0.
2071
2072# Fusing Google Test Source Files #
2073
2074Google Test's implementation consists of ~30 files (excluding its own
2075tests).  Sometimes you may want them to be packaged up in two files (a
2076`.h` and a `.cc`) instead, such that you can easily copy them to a new
2077machine and start hacking there.  For this we provide an experimental
2078Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0).
2079Assuming you have Python 2.4 or above installed on your machine, just
2080go to that directory and run
2081```
2082python fuse_gtest_files.py OUTPUT_DIR
2083```
2084
2085and you should see an `OUTPUT_DIR` directory being created with files
2086`gtest/gtest.h` and `gtest/gtest-all.cc` in it.  These files contain
2087everything you need to use Google Test.  Just copy them to anywhere
2088you want and you are ready to write tests.  You can use the
2089[scrpts/test/Makefile](http://code.google.com/p/googletest/source/browse/trunk/scripts/test/Makefile)
2090file as an example on how to compile your tests against them.
2091
2092# Where to Go from Here #
2093
2094Congratulations! You've now learned more advanced Google Test tools and are
2095ready to tackle more complex testing tasks. If you want to dive even deeper, you
2096can read the [FAQ](V1_5_FAQ.md).
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_5_Documentation.md
r0r249096
1This page lists all official documentation wiki pages for Google Test **1.5.0** -- **if you use a different version of Google Test, make sure to read the documentation for that version instead.**
2
3  * [Primer](V1_5_Primer.md) -- start here if you are new to Google Test.
4  * [Samples](Samples.md) -- learn from examples.
5  * [AdvancedGuide](V1_5_AdvancedGuide.md) -- learn more about Google Test.
6  * [XcodeGuide](V1_5_XcodeGuide.md) -- how to use Google Test in Xcode on Mac.
7  * [Frequently-Asked Questions](V1_5_FAQ.md) -- check here before asking a question on the mailing list.
8
9To contribute code to Google Test, read:
10
11  * DevGuide -- read this _before_ writing your first patch.
12  * [PumpManual](V1_5_PumpManual.md) -- how we generate some of Google Test's source files.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_5_FAQ.md
r0r249096
1
2
3If you cannot find the answer to your question here, and you have read
4[Primer](V1_5_Primer.md) and [AdvancedGuide](V1_5_AdvancedGuide.md), send it to
5googletestframework@googlegroups.com.
6
7## Why should I use Google Test instead of my favorite C++ testing framework? ##
8
9First, let's say clearly that we don't want to get into the debate of
10which C++ testing framework is **the best**.  There exist many fine
11frameworks for writing C++ tests, and we have tremendous respect for
12the developers and users of them.  We don't think there is (or will
13be) a single best framework - you have to pick the right tool for the
14particular task you are tackling.
15
16We created Google Test because we couldn't find the right combination
17of features and conveniences in an existing framework to satisfy _our_
18needs.  The following is a list of things that _we_ like about Google
19Test.  We don't claim them to be unique to Google Test - rather, the
20combination of them makes Google Test the choice for us.  We hope this
21list can help you decide whether it is for you too.
22
23  * Google Test is designed to be portable.  It works where many STL types (e.g. `std::string` and `std::vector`) don't compile.  It doesn't require exceptions or RTTI.  As a result, it runs on Linux, Mac OS X, Windows and several embedded operating systems.
24  * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle.
25  * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`.  It doesn't require a new set of macros or special functions.
26  * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them.
27  * No framework can anticipate all your needs, so Google Test provides `EXPECT_PRED*` to make it easy to extend your assertion vocabulary.  For a nicer syntax, you can define your own assertion macros trivially in terms of `EXPECT_PRED*`.
28  * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions.
29  * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop.
30  * You can decide which tests to run using name patterns.  This saves time when you want to quickly reproduce a test failure.
31
32## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ##
33
34(Answered by Trevor Robinson)
35
36Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or
37`msvc\gtest.sln`. Go through the migration wizard to migrate the
38solution and project files to Visual Studio 2008. Select
39`Configuration Manager...` from the `Build` menu. Select `<New...>` from
40the `Active solution platform` dropdown.  Select `x64` from the new
41platform dropdown, leave `Copy settings from` set to `Win32` and
42`Create new project platforms` checked, then click `OK`. You now have
43`Win32` and `x64` platform configurations, selectable from the
44`Standard` toolbar, which allow you to toggle between building 32-bit or
4564-bit binaries (or both at once using Batch Build).
46
47In order to prevent build output files from overwriting one another,
48you'll need to change the `Intermediate Directory` settings for the
49newly created platform configuration across all the projects. To do
50this, multi-select (e.g. using shift-click) all projects (but not the
51solution) in the `Solution Explorer`. Right-click one of them and
52select `Properties`. In the left pane, select `Configuration Properties`,
53and from the `Configuration` dropdown, select `All Configurations`.
54Make sure the selected platform is `x64`. For the
55`Intermediate Directory` setting, change the value from
56`$(PlatformName)\$(ConfigurationName)` to
57`$(OutDir)\$(ProjectName)`. Click `OK` and then build the
58solution. When the build is complete, the 64-bit binaries will be in
59the `msvc\x64\Debug` directory.
60
61## Can I use Google Test on MinGW? ##
62
63We haven't tested this ourselves, but Per Abrahamsen reported that he
64was able to compile and install Google Test successfully when using
65MinGW from Cygwin.  You'll need to configure it with:
66
67`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"`
68
69You should be able to replace the `-mno-cygwin` option with direct links
70to the real MinGW binaries, but we haven't tried that.
71
72Caveats:
73
74  * There are many warnings when compiling.
75  * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW.
76
77We also have reports on successful cross compilation of Google Test MinGW binaries on Linux using [these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows) on the WxWidgets site.
78
79Please contact `googletestframework@googlegroups.com` if you are
80interested in improving the support for MinGW.
81
82## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ##
83
84Due to some peculiarity of C++, it requires some non-trivial template
85meta programming tricks to support using `NULL` as an argument of the
86`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where
87it's most needed (otherwise we make the implementation of Google Test
88harder to maintain and more error-prone than necessary).
89
90The `EXPECT_EQ()` macro takes the _expected_ value as its first
91argument and the _actual_ value as the second. It's reasonable that
92someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this
93indeed was requested several times. Therefore we implemented it.
94
95The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the
96assertion fails, you already know that `ptr` must be `NULL`, so it
97doesn't add any information to print ptr in this case. That means
98`EXPECT_TRUE(ptr ! NULL)` works just as well.
99
100If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll
101have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`,
102we don't have a convention on the order of the two arguments for
103`EXPECT_NE`. This means using the template meta programming tricks
104twice in the implementation, making it even harder to understand and
105maintain. We believe the benefit doesn't justify the cost.
106
107Finally, with the growth of Google Mock's [matcher](http://code.google.com/p/googlemock/wiki/CookBook#Using_Matchers_in_Google_Test_Assertions) library, we are
108encouraging people to use the unified `EXPECT_THAT(value, matcher)`
109syntax more often in tests. One significant advantage of the matcher
110approach is that matchers can be easily combined to form new matchers,
111while the `EXPECT_NE`, etc, macros cannot be easily
112combined. Therefore we want to invest more in the matchers than in the
113`EXPECT_XX()` macros.
114
115## Does Google Test support running tests in parallel? ##
116
117Test runners tend to be tightly coupled with the build/test
118environment, and Google Test doesn't try to solve the problem of
119running tests in parallel.  Instead, we tried to make Google Test work
120nicely with test runners.  For example, Google Test's XML report
121contains the time spent on each test, and its `gtest_list_tests` and
122`gtest_filter` flags can be used for splitting the execution of test
123methods into multiple processes.  These functionalities can help the
124test runner run the tests in parallel.
125
126## Why don't Google Test run the tests in different threads to speed things up? ##
127
128It's difficult to write thread-safe code.  Most tests are not written
129with thread-safety in mind, and thus may not work correctly in a
130multi-threaded setting.
131
132If you think about it, it's already hard to make your code work when
133you know what other threads are doing.  It's much harder, and
134sometimes even impossible, to make your code work when you don't know
135what other threads are doing (remember that test methods can be added,
136deleted, or modified after your test was written).  If you want to run
137the tests in parallel, you'd better run them in different processes.
138
139## Why aren't Google Test assertions implemented using exceptions? ##
140
141Our original motivation was to be able to use Google Test in projects
142that disable exceptions.  Later we realized some additional benefits
143of this approach:
144
145  1. Throwing in a destructor is undefined behavior in C++.  Not using exceptions means Google Test's assertions are safe to use in destructors.
146  1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing.
147  1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code:
148```
149try { ... ASSERT_TRUE(...) ... }
150catch (...) { ... }
151```
152The above code will pass even if the `ASSERT_TRUE` throws.  While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test.
153
154The downside of not using exceptions is that `ASSERT_*` (implemented
155using `return`) will only abort the current function, not the current
156`TEST`.
157
158## Why do we use two different macros for tests with and without fixtures? ##
159
160Unfortunately, C++'s macro system doesn't allow us to use the same
161macro for both cases.  One possibility is to provide only one macro
162for tests with fixtures, and require the user to define an empty
163fixture sometimes:
164
165```
166class FooTest : public ::testing::Test {};
167
168TEST_F(FooTest, DoesThis) { ... }
169```
170or
171```
172typedef ::testing::Test FooTest;
173
174TEST_F(FooTest, DoesThat) { ... }
175```
176
177Yet, many people think this is one line too many. :-) Our goal was to
178make it really easy to write tests, so we tried to make simple tests
179trivial to create.  That means using a separate macro for such tests.
180
181We think neither approach is ideal, yet either of them is reasonable.
182In the end, it probably doesn't matter much either way.
183
184## Why don't we use structs as test fixtures? ##
185
186We like to use structs only when representing passive data.  This
187distinction between structs and classes is good for documenting the
188intent of the code's author.  Since test fixtures have logic like
189`SetUp()` and `TearDown()`, they are better defined as classes.
190
191## Why are death tests implemented as assertions instead of using a test runner? ##
192
193Our goal was to make death tests as convenient for a user as C++
194possibly allows.  In particular:
195
196  * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect.  The death test would be written in C++, while the runner spec may or may not be.  A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative.
197  * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn.
198  * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will.  You are not limited to one death test per test method. For example, you can write something like:
199```
200    if (FooCondition()) {
201      ASSERT_DEATH(Bar(), "blah");
202    } else {
203      ASSERT_EQ(5, Bar());
204    }
205```
206If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users.  The fewer artificial limitations the better.
207  * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information.  For example,
208```
209    const int count = GetCount();  // Only known at run time.
210    for (int i = 1; i <= count; i++) {
211      ASSERT_DEATH({
212        double* buffer = new double[i];
213        ... initializes buffer ...
214        Foo(buffer, i)
215      }, "blah blah");
216    }
217```
218The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility.
219
220Another interesting thing about `ASSERT_DEATH` is that it calls `fork()`
221to create a child process to run the death test.  This is lightening
222fast, as `fork()` uses copy-on-write pages and incurs almost zero
223overhead, and the child process starts from the user-supplied
224statement directly, skipping all global and local initialization and
225any code leading to the given statement.  If you launch the child
226process from scratch, it can take seconds just to load everything and
227start running if the test links to many libraries dynamically.
228
229## My death test modifies some state, but the change seems lost after the death test finishes. Why? ##
230
231Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
232expected crash won't kill the test program (i.e. the parent process). As a
233result, any in-memory side effects they incur are observable in their
234respective sub-processes, but not in the parent process. You can think of them
235as running in a parallel universe, more or less.
236
237## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ##
238
239If your class has a static data member:
240
241```
242// foo.h
243class Foo {
244  ...
245  static const int kBar = 100;
246};
247```
248
249You also need to define it _outside_ of the class body in `foo.cc`:
250
251```
252const int Foo::kBar;  // No initializer here.
253```
254
255Otherwise your code is **invalid C++**, and may break in unexpected ways. In
256particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc)
257will generate an "undefined reference" linker error.
258
259## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ##
260
261Google Test doesn't yet have good support for this kind of tests, or
262data-driven tests in general. We hope to be able to make improvements in this
263area soon.
264
265## Can I derive a test fixture from another? ##
266
267Yes.
268
269Each test fixture has a corresponding and same named test case. This means only
270one test case can use a particular fixture. Sometimes, however, multiple test
271cases may want to use the same or slightly different fixtures. For example, you
272may want to make sure that all of a GUI library's test cases don't leak
273important system resources like fonts and brushes.
274
275In Google Test, you share a fixture among test cases by putting the shared
276logic in a base test fixture, then deriving from that base a separate fixture
277for each test case that wants to use this common logic. You then use `TEST_F()`
278to write tests using each derived fixture.
279
280Typically, your code looks like this:
281
282```
283// Defines a base test fixture.
284class BaseTest : public ::testing::Test {
285  protected:
286   ...
287};
288
289// Derives a fixture FooTest from BaseTest.
290class FooTest : public BaseTest {
291  protected:
292    virtual void SetUp() {
293      BaseTest::SetUp();  // Sets up the base fixture first.
294      ... additional set-up work ...
295    }
296    virtual void TearDown() {
297      ... clean-up work for FooTest ...
298      BaseTest::TearDown();  // Remember to tear down the base fixture
299                             // after cleaning up FooTest!
300    }
301    ... functions and variables for FooTest ...
302};
303
304// Tests that use the fixture FooTest.
305TEST_F(FooTest, Bar) { ... }
306TEST_F(FooTest, Baz) { ... }
307
308... additional fixtures derived from BaseTest ...
309```
310
311If necessary, you can continue to derive test fixtures from a derived fixture.
312Google Test has no limit on how deep the hierarchy can be.
313
314For a complete example using derived test fixtures, see
315`samples/sample5_unittest.cc`.
316
317## My compiler complains "void value not ignored as it ought to be." What does this mean? ##
318
319You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
320`ASSERT_*()` can only be used in `void` functions.
321
322## My death test hangs (or seg-faults). How do I fix it? ##
323
324In Google Test, death tests are run in a child process and the way they work is
325delicate. To write death tests you really need to understand how they work.
326Please make sure you have read this.
327
328In particular, death tests don't like having multiple threads in the parent
329process. So the first thing you can try is to eliminate creating threads
330outside of `EXPECT_DEATH()`.
331
332Sometimes this is impossible as some library you must use may be creating
333threads before `main()` is even reached. In this case, you can try to minimize
334the chance of conflicts by either moving as many activities as possible inside
335`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
336leaving as few things as possible in it. Also, you can try to set the death
337test style to `"threadsafe"`, which is safer but slower, and see if it helps.
338
339If you go with thread-safe death tests, remember that they rerun the test
340program from the beginning in the child process. Therefore make sure your
341program can run side-by-side with itself and is deterministic.
342
343In the end, this boils down to good concurrent programming. You have to make
344sure that there is no race conditions or dead locks in your program. No silver
345bullet - sorry!
346
347## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ##
348
349The first thing to remember is that Google Test does not reuse the
350same test fixture object across multiple tests. For each `TEST_F`,
351Google Test will create a fresh test fixture object, _immediately_
352call `SetUp()`, run the test, call `TearDown()`, and then
353_immediately_ delete the test fixture object. Therefore, there is no
354need to write a `SetUp()` or `TearDown()` function if the constructor
355or destructor already does the job.
356
357You may still want to use `SetUp()/TearDown()` in the following cases:
358  * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions.
359  * The Google Test team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use Google Test assertions in a destructor if your code could run on such a platform.
360  * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`.
361
362## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
363
364If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
365overloaded or a template, the compiler will have trouble figuring out which
366overloaded version it should use. `ASSERT_PRED_FORMAT*` and
367`EXPECT_PRED_FORMAT*` don't have this problem.
368
369If you see this error, you might want to switch to
370`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
371message. If, however, that is not an option, you can resolve the problem by
372explicitly telling the compiler which version to pick.
373
374For example, suppose you have
375
376```
377bool IsPositive(int n) {
378  return n > 0;
379}
380bool IsPositive(double x) {
381  return x > 0;
382}
383```
384
385you will get a compiler error if you write
386
387```
388EXPECT_PRED1(IsPositive, 5);
389```
390
391However, this will work:
392
393```
394EXPECT_PRED1(*static_cast<bool (*)(int)>*(IsPositive), 5);
395```
396
397(The stuff inside the angled brackets for the `static_cast` operator is the
398type of the function pointer for the `int`-version of `IsPositive()`.)
399
400As another example, when you have a template function
401
402```
403template <typename T>
404bool IsNegative(T x) {
405  return x < 0;
406}
407```
408
409you can use it in a predicate assertion like this:
410
411```
412ASSERT_PRED1(IsNegative*<int>*, -5);
413```
414
415Things are more interesting if your template has more than one parameters. The
416following won't compile:
417
418```
419ASSERT_PRED2(*GreaterThan<int, int>*, 5, 0);
420```
421
422
423as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments,
424which is one more than expected. The workaround is to wrap the predicate
425function in parentheses:
426
427```
428ASSERT_PRED2(*(GreaterThan<int, int>)*, 5, 0);
429```
430
431
432## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ##
433
434Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
435instead of
436
437```
438return RUN_ALL_TESTS();
439```
440
441they write
442
443```
444RUN_ALL_TESTS();
445```
446
447This is wrong and dangerous. A test runner needs to see the return value of
448`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()`
449function ignores it, your test will be considered successful even if it has a
450Google Test assertion failure. Very bad.
451
452To help the users avoid this dangerous bug, the implementation of
453`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is
454ignored. If you see this warning, the fix is simple: just make sure its value
455is used as the return value of `main()`.
456
457## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ##
458
459Due to a peculiarity of C++, in order to support the syntax for streaming
460messages to an `ASSERT_*`, e.g.
461
462```
463ASSERT_EQ(1, Foo()) << "blah blah" << foo;
464```
465
466we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
467`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
468content of your constructor/destructor to a private void member function, or
469switch to `EXPECT_*()` if that works. This section in the user's guide explains
470it.
471
472## My set-up function is not called. Why? ##
473
474C++ is case-sensitive. It should be spelled as `SetUp()`.  Did you
475spell it as `Setup()`?
476
477Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
478wonder why it's never called.
479
480## How do I jump to the line of a failure in Emacs directly? ##
481
482Google Test's failure message format is understood by Emacs and many other
483IDEs, like acme and XCode. If a Google Test message is in a compilation buffer
484in Emacs, then it's clickable. You can now hit `enter` on a message to jump to
485the corresponding source code, or use `C-x `` to jump to the next failure.
486
487## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ##
488
489You don't have to. Instead of
490
491```
492class FooTest : public BaseTest {};
493
494TEST_F(FooTest, Abc) { ... }
495TEST_F(FooTest, Def) { ... }
496
497class BarTest : public BaseTest {};
498
499TEST_F(BarTest, Abc) { ... }
500TEST_F(BarTest, Def) { ... }
501```
502
503you can simply `typedef` the test fixtures:
504```
505typedef BaseTest FooTest;
506
507TEST_F(FooTest, Abc) { ... }
508TEST_F(FooTest, Def) { ... }
509
510typedef BaseTest BarTest;
511
512TEST_F(BarTest, Abc) { ... }
513TEST_F(BarTest, Def) { ... }
514```
515
516## The Google Test output is buried in a whole bunch of log messages. What do I do? ##
517
518The Google Test output is meant to be a concise and human-friendly report. If
519your test generates textual output itself, it will mix with the Google Test
520output, making it hard to read. However, there is an easy solution to this
521problem.
522
523Since most log messages go to stderr, we decided to let Google Test output go
524to stdout. This way, you can easily separate the two using redirection. For
525example:
526```
527./my_test > googletest_output.txt
528```
529
530## Why should I prefer test fixtures over global variables? ##
531
532There are several good reasons:
533  1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other.
534  1. Global variables pollute the global namespace.
535  1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common.
536
537## How do I test private class members without writing FRIEND\_TEST()s? ##
538
539You should try to write testable code, which means classes should be easily
540tested from their public interface. One way to achieve this is the Pimpl idiom:
541you move all private members of a class into a helper class, and make all
542members of the helper class public.
543
544You have several other options that don't require using `FRIEND_TEST`:
545  * Write the tests as members of the fixture class:
546```
547class Foo {
548  friend class FooTest;
549  ...
550};
551
552class FooTest : public ::testing::Test {
553 protected:
554  ...
555  void Test1() {...} // This accesses private members of class Foo.
556  void Test2() {...} // So does this one.
557};
558
559TEST_F(FooTest, Test1) {
560  Test1();
561}
562
563TEST_F(FooTest, Test2) {
564  Test2();
565}
566```
567  * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests:
568```
569class Foo {
570  friend class FooTest;
571  ...
572};
573
574class FooTest : public ::testing::Test {
575 protected:
576  ...
577  T1 get_private_member1(Foo* obj) {
578    return obj->private_member1_;
579  }
580};
581
582TEST_F(FooTest, Test1) {
583  ...
584  get_private_member1(x)
585  ...
586}
587```
588  * If the methods are declared **protected**, you can change their access level in a test-only subclass:
589```
590class YourClass {
591  ...
592 protected: // protected access for testability.
593  int DoSomethingReturningInt();
594  ...
595};
596
597// in the your_class_test.cc file:
598class TestableYourClass : public YourClass {
599  ...
600 public: using YourClass::DoSomethingReturningInt; // changes access rights
601  ...
602};
603
604TEST_F(YourClassTest, DoSomethingTest) {
605  TestableYourClass obj;
606  assertEquals(expected_value, obj.DoSomethingReturningInt());
607}
608```
609
610## How do I test private class static members without writing FRIEND\_TEST()s? ##
611
612We find private static methods clutter the header file.  They are
613implementation details and ideally should be kept out of a .h. So often I make
614them free functions instead.
615
616Instead of:
617```
618// foo.h
619class Foo {
620  ...
621 private:
622  static bool Func(int n);
623};
624
625// foo.cc
626bool Foo::Func(int n) { ... }
627
628// foo_test.cc
629EXPECT_TRUE(Foo::Func(12345));
630```
631
632You probably should better write:
633```
634// foo.h
635class Foo {
636  ...
637};
638
639// foo.cc
640namespace internal {
641  bool Func(int n) { ... }
642}
643
644// foo_test.cc
645namespace internal {
646  bool Func(int n);
647}
648
649EXPECT_TRUE(internal::Func(12345));
650```
651
652## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ##
653
654No. You can use a feature called [value-parameterized tests](V1_5_AdvancedGuide#Value_Parameterized_Tests.md) which
655lets you repeat your tests with different parameters, without defining it more than once.
656
657## How do I test a file that defines main()? ##
658
659To test a `foo.cc` file, you need to compile and link it into your unit test
660program. However, when the file contains a definition for the `main()`
661function, it will clash with the `main()` of your unit test, and will result in
662a build error.
663
664The right solution is to split it into three files:
665  1. `foo.h` which contains the declarations,
666  1. `foo.cc` which contains the definitions except `main()`, and
667  1. `foo_main.cc` which contains nothing but the definition of `main()`.
668
669Then `foo.cc` can be easily tested.
670
671If you are adding tests to an existing file and don't want an intrusive change
672like this, there is a hack: just include the entire `foo.cc` file in your unit
673test. For example:
674```
675// File foo_unittest.cc
676
677// The headers section
678...
679
680// Renames main() in foo.cc to make room for the unit test main()
681#define main FooMain
682
683#include "a/b/foo.cc"
684
685// The tests start here.
686...
687```
688
689
690However, please remember this is a hack and should only be used as the last
691resort.
692
693## What can the statement argument in ASSERT\_DEATH() be? ##
694
695`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used
696wherever `_statement_` is valid. So basically `_statement_` can be any C++
697statement that makes sense in the current context. In particular, it can
698reference global and/or local variables, and can be:
699  * a simple function call (often the case),
700  * a complex expression, or
701  * a compound statement.
702
703> Some examples are shown here:
704```
705// A death test can be a simple function call.
706TEST(MyDeathTest, FunctionCall) {
707  ASSERT_DEATH(Xyz(5), "Xyz failed");
708}
709
710// Or a complex expression that references variables and functions.
711TEST(MyDeathTest, ComplexExpression) {
712  const bool c = Condition();
713  ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
714               "(Func1|Method) failed");
715}
716
717// Death assertions can be used any where in a function. In
718// particular, they can be inside a loop.
719TEST(MyDeathTest, InsideLoop) {
720  // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
721  for (int i = 0; i < 5; i++) {
722    EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
723                   ::testing::Message() << "where i is " << i);
724  }
725}
726
727// A death assertion can contain a compound statement.
728TEST(MyDeathTest, CompoundStatement) {
729  // Verifies that at lease one of Bar(0), Bar(1), ..., and
730  // Bar(4) dies.
731  ASSERT_DEATH({
732    for (int i = 0; i < 5; i++) {
733      Bar(i);
734    }
735  },
736  "Bar has \\d+ errors");}
737```
738
739`googletest_unittest.cc` contains more examples if you are interested.
740
741## What syntax does the regular expression in ASSERT\_DEATH use? ##
742
743On POSIX systems, Google Test uses the POSIX Extended regular
744expression syntax
745(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). On
746Windows, it uses a limited variant of regular expression syntax. For
747more details, see the [regular expression syntax](V1_5_AdvancedGuide#Regular_Expression_Syntax.md).
748
749## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ##
750
751Google Test needs to be able to create objects of your test fixture class, so
752it must have a default constructor. Normally the compiler will define one for
753you. However, there are cases where you have to define your own:
754  * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty.
755  * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.)
756
757## Why does ASSERT\_DEATH complain about previous threads that were already joined? ##
758
759With the Linux pthread library, there is no turning back once you cross the
760line from single thread to multiple threads. The first time you create a
761thread, a manager thread is created in addition, so you get 3, not 2, threads.
762Later when the thread you create joins the main thread, the thread count
763decrements by 1, but the manager thread will never be killed, so you still have
7642 threads, which means you cannot safely run a death test.
765
766The new NPTL thread library doesn't suffer from this problem, as it doesn't
767create a manager thread. However, if you don't control which machine your test
768runs on, you shouldn't depend on this.
769
770## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ##
771
772Google Test does not interleave tests from different test cases. That is, it
773runs all tests in one test case first, and then runs all tests in the next test
774case, and so on. Google Test does this because it needs to set up a test case
775before the first test in it is run, and tear it down afterwords. Splitting up
776the test case would require multiple set-up and tear-down processes, which is
777inefficient and makes the semantics unclean.
778
779If we were to determine the order of tests based on test name instead of test
780case name, then we would have a problem with the following situation:
781
782```
783TEST_F(FooTest, AbcDeathTest) { ... }
784TEST_F(FooTest, Uvw) { ... }
785
786TEST_F(BarTest, DefDeathTest) { ... }
787TEST_F(BarTest, Xyz) { ... }
788```
789
790Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
791interleave tests from different test cases, we need to run all tests in the
792`FooTest` case before running any test in the `BarTest` case. This contradicts
793with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
794
795## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ##
796
797You don't have to, but if you like, you may split up the test case into
798`FooTest` and `FooDeathTest`, where the names make it clear that they are
799related:
800
801```
802class FooTest : public ::testing::Test { ... };
803
804TEST_F(FooTest, Abc) { ... }
805TEST_F(FooTest, Def) { ... }
806
807typedef FooTest FooDeathTest;
808
809TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
810TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
811```
812
813## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ##
814
815If you use a user-defined type `FooType` in an assertion, you must make sure
816there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
817defined such that we can print a value of `FooType`.
818
819In addition, if `FooType` is declared in a name space, the `<<` operator also
820needs to be defined in the _same_ name space.
821
822## How do I suppress the memory leak messages on Windows? ##
823
824Since the statically initialized Google Test singleton requires allocations on
825the heap, the Visual C++ memory leak detector will report memory leaks at the
826end of the program run. The easiest way to avoid this is to use the
827`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
828statically initialized heap objects. See MSDN for more details and additional
829heap check/debug routines.
830
831## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ##
832
833You may get a number of the following linker error or warnings if you
834attempt to link your test project with the Google Test library when
835your project and the are not built using the same compiler settings.
836
837  * LNK2005: symbol already defined in object
838  * LNK4217: locally defined symbol 'symbol' imported in function 'function'
839  * LNK4049: locally defined symbol 'symbol' imported
840
841The Google Test project (gtest.vcproj) has the Runtime Library option
842set to /MT (use multi-threaded static libraries, /MTd for debug). If
843your project uses something else, for example /MD (use multi-threaded
844DLLs, /MDd for debug), you need to change the setting in the Google
845Test project to match your project's.
846
847To update this setting open the project properties in the Visual
848Studio IDE then select the branch Configuration Properties | C/C++ |
849Code Generation and change the option "Runtime Library".  You may also try
850using gtest-md.vcproj instead of gtest.vcproj.
851
852## I put my tests in a library and Google Test doesn't run them. What's happening? ##
853Have you read a
854[warning](V1_5_Primer#Important_note_for_Visual_C++_users.md) on
855the Google Test Primer page?
856
857## I want to use Google Test with Visual Studio but don't know where to start. ##
858Many people are in your position and one of the posted his solution to
859our mailing list. Here is his link:
860http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html.
861
862## My question is not covered in your FAQ! ##
863
864If you cannot find the answer to your question in this FAQ, there are
865some other resources you can use:
866
867  1. read other [wiki pages](http://code.google.com/p/googletest/w/list),
868  1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics),
869  1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.).
870
871Please note that creating an issue in the
872[issue tracker](http://code.google.com/p/googletest/issues/list) is _not_
873a good way to get your answer, as it is monitored infrequently by a
874very small number of people.
875
876When asking a question, it's helpful to provide as much of the
877following information as possible (people cannot help you if there's
878not enough information in your question):
879
880  * the version (or the revision number if you check out from SVN directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version),
881  * your operating system,
882  * the name and version of your compiler,
883  * the complete command line flags you give to your compiler,
884  * the complete compiler error messages (if the question is about compilation),
885  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_5_Primer.md
r0r249096
1
2
3# Introduction: Why Google C++ Testing Framework? #
4
5_Google C++ Testing Framework_ helps you write better C++ tests.
6
7No matter whether you work on Linux, Windows, or a Mac, if you write C++ code,
8Google Test can help you.
9
10So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
11  1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests.  Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
12  1. Tests should be well _organized_ and reflect the structure of the tested code.  Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
13  1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral.  Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations.  (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
14  1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
15  1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_.  Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
16  1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
17
18Since Google C++ Testing Framework is based on the popular xUnit
19architecture, you'll feel right at home if you've used JUnit or PyUnit before.
20If not, it will take you about 10 minutes to learn the basics and get started.
21So let's go!
22
23_Note:_ We sometimes refer to Google C++ Testing Framework informally
24as _Google Test_.
25
26# Setting up a New Test Project #
27
28To write a test program using Google Test, you need to compile Google
29Test into a library and link your test with it.  We provide build
30files for some popular build systems (`msvc/` for Visual Studio,
31`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland
32C++ Builder, and the autotools script in the
33Google Test root directory).  If your build system is not on this
34list, you can take a look at `make/Makefile` to learn how Google Test
35should be compiled (basically you want to compile `src/gtest-all.cc`
36with `GTEST_ROOT` and `GTEST_ROOT/include` in the header search path,
37where `GTEST_ROOT` is the Google Test root directory).
38
39Once you are able to compile the Google Test library, you should
40create a project or build target for your test program.  Make sure you
41have `GTEST_ROOT/include` in the header search path so that the
42compiler can find `<gtest/gtest.h>` when compiling your test.  Set up
43your test project to link with the Google Test library (for example,
44in Visual Studio, this is done by adding a dependency on
45`gtest.vcproj`).
46
47If you still have questions, take a look at how Google Test's own
48tests are built and use them as examples.
49
50# Basic Concepts #
51
52When using Google Test, you start by writing _assertions_, which are statements
53that check whether a condition is true. An assertion's result can be _success_,
54_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts
55the current function; otherwise the program continues normally.
56
57_Tests_ use assertions to verify the tested code's behavior. If a test crashes
58or has a failed assertion, then it _fails_; otherwise it _succeeds_.
59
60A _test case_ contains one or many tests. You should group your tests into test
61cases that reflect the structure of the tested code. When multiple tests in a
62test case need to share common objects and subroutines, you can put them into a
63_test fixture_ class.
64
65A _test program_ can contain multiple test cases.
66
67We'll now explain how to write a test program, starting at the individual
68assertion level and building up to tests and test cases.
69
70# Assertions #
71
72Google Test assertions are macros that resemble function calls. You test a
73class or function by making assertions about its behavior. When an assertion
74fails, Google Test prints the assertion's source file and line number location,
75along with a failure message. You may also supply a custom failure message
76which will be appended to Google Test's message.
77
78The assertions come in pairs that test the same thing but have different
79effects on the current function. `ASSERT_*` versions generate fatal failures
80when they fail, and **abort the current function**. `EXPECT_*` versions generate
81nonfatal failures, which don't abort the current function. Usually `EXPECT_*`
82are preferred, as they allow more than one failures to be reported in a test.
83However, you should use `ASSERT_*` if it doesn't make sense to continue when
84the assertion in question fails.
85
86Since a failed `ASSERT_*` returns from the current function immediately,
87possibly skipping clean-up code that comes after it, it may cause a space leak.
88Depending on the nature of the leak, it may or may not be worth fixing - so
89keep this in mind if you get a heap checker error in addition to assertion
90errors.
91
92To provide a custom failure message, simply stream it into the macro using the
93`<<` operator, or a sequence of such operators. An example:
94```
95ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
96
97for (int i = 0; i < x.size(); ++i) {
98  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
99}
100```
101
102Anything that can be streamed to an `ostream` can be streamed to an assertion
103macro--in particular, C strings and `string` objects. If a wide string
104(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
105streamed to an assertion, it will be translated to UTF-8 when printed.
106
107## Basic Assertions ##
108
109These assertions do basic true/false condition testing.
110| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
111|:--------------------|:-----------------------|:-------------|
112| `ASSERT_TRUE(`_condition_`)`;  | `EXPECT_TRUE(`_condition_`)`;   | _condition_ is true |
113| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`;  | _condition_ is false |
114
115Remember, when they fail, `ASSERT_*` yields a fatal failure and
116returns from the current function, while `EXPECT_*` yields a nonfatal
117failure, allowing the function to continue running. In either case, an
118assertion failure means its containing test fails.
119
120_Availability_: Linux, Windows, Mac.
121
122## Binary Comparison ##
123
124This section describes assertions that compare two values.
125
126| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
127|:--------------------|:-----------------------|:-------------|
128|`ASSERT_EQ(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ |
129|`ASSERT_NE(`_val1_`, `_val2_`);`      |`EXPECT_NE(`_val1_`, `_val2_`);`      | _val1_ `!=` _val2_ |
130|`ASSERT_LT(`_val1_`, `_val2_`);`      |`EXPECT_LT(`_val1_`, `_val2_`);`      | _val1_ `<` _val2_ |
131|`ASSERT_LE(`_val1_`, `_val2_`);`      |`EXPECT_LE(`_val1_`, `_val2_`);`      | _val1_ `<=` _val2_ |
132|`ASSERT_GT(`_val1_`, `_val2_`);`      |`EXPECT_GT(`_val1_`, `_val2_`);`      | _val1_ `>` _val2_ |
133|`ASSERT_GE(`_val1_`, `_val2_`);`      |`EXPECT_GE(`_val1_`, `_val2_`);`      | _val1_ `>=` _val2_ |
134
135In the event of a failure, Google Test prints both _val1_ and _val2_
136. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions
137we'll introduce later), you should put the expression you want to test
138in the position of _actual_, and put its expected value in _expected_,
139as Google Test's failure messages are optimized for this convention.
140
141Value arguments must be comparable by the assertion's comparison operator or
142you'll get a compiler error. Values must also support the `<<` operator for
143streaming to an `ostream`. All built-in types support this.
144
145These assertions can work with a user-defined type, but only if you define the
146corresponding comparison operator (e.g. `==`, `<`, etc).  If the corresponding
147operator is defined, prefer using the `ASSERT_*()` macros because they will
148print out not only the result of the comparison, but the two operands as well.
149
150Arguments are always evaluated exactly once. Therefore, it's OK for the
151arguments to have side effects. However, as with any ordinary C/C++ function,
152the arguments' evaluation order is undefined (i.e. the compiler is free to
153choose any order) and your code should not depend on any particular argument
154evaluation order.
155
156`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
157tests if they are in the same memory location, not if they have the same value.
158Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
159`ASSERT_STREQ()` , which will be described later on. In particular, to assert
160that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to
161compare two `string` objects, you should use `ASSERT_EQ`.
162
163Macros in this section work with both narrow and wide string objects (`string`
164and `wstring`).
165
166_Availability_: Linux, Windows, Mac.
167
168## String Comparison ##
169
170The assertions in this group compare two **C strings**. If you want to compare
171two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
172
173| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
174|:--------------------|:-----------------------|:-------------|
175| `ASSERT_STREQ(`_expected\_str_`, `_actual\_str_`);`    | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);`     | the two C strings have the same content |
176| `ASSERT_STRNE(`_str1_`, `_str2_`);`    | `EXPECT_STRNE(`_str1_`, `_str2_`);`     | the two C strings have different content |
177| `ASSERT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | the two C strings have the same content, ignoring case |
178| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case |
179
180Note that "CASE" in an assertion name means that case is ignored.
181
182`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a
183comparison of two wide strings fails, their values will be printed as UTF-8
184narrow strings.
185
186A `NULL` pointer and an empty string are considered _different_.
187
188_Availability_: Linux, Windows, Mac.
189
190See also: For more string comparison tricks (substring, prefix, suffix, and
191regular expression matching, for example), see the [AdvancedGuide Advanced
192Google Test Guide].
193
194# Simple Tests #
195
196To create a test:
197  1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value.
198  1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
199  1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
200
201```
202TEST(test_case_name, test_name) {
203 ... test body ...
204}
205```
206
207
208`TEST()` arguments go from general to specific. The _first_ argument is the
209name of the test case, and the _second_ argument is the test's name within the
210test case. Remember that a test case can contain any number of individual
211tests. A test's _full name_ consists of its containing test case and its
212individual name. Tests from different test cases can have the same individual
213name.
214
215For example, let's take a simple integer function:
216```
217int Factorial(int n); // Returns the factorial of n
218```
219
220A test case for this function might look like:
221```
222// Tests factorial of 0.
223TEST(FactorialTest, HandlesZeroInput) {
224  EXPECT_EQ(1, Factorial(0));
225}
226
227// Tests factorial of positive numbers.
228TEST(FactorialTest, HandlesPositiveInput) {
229  EXPECT_EQ(1, Factorial(1));
230  EXPECT_EQ(2, Factorial(2));
231  EXPECT_EQ(6, Factorial(3));
232  EXPECT_EQ(40320, Factorial(8));
233}
234```
235
236Google Test groups the test results by test cases, so logically-related tests
237should be in the same test case; in other words, the first argument to their
238`TEST()` should be the same. In the above example, we have two tests,
239`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
240case `FactorialTest`.
241
242_Availability_: Linux, Windows, Mac.
243
244# Test Fixtures: Using the Same Data Configuration for Multiple Tests #
245
246If you find yourself writing two or more tests that operate on similar data,
247you can use a _test fixture_. It allows you to reuse the same configuration of
248objects for several different tests.
249
250To create a fixture, just:
251  1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes.
252  1. Inside the class, declare any objects you plan to use.
253  1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you.
254  1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](http://code.google.com/p/googletest/wiki/V1_5_FAQ#Should_I_use_the_constructor/destructor_of_the_test_fixture_or_t).
255  1. If needed, define subroutines for your tests to share.
256
257When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
258access objects and subroutines in the test fixture:
259```
260TEST_F(test_case_name, test_name) {
261 ... test body ...
262}
263```
264
265Like `TEST()`, the first argument is the test case name, but for `TEST_F()`
266this must be the name of the test fixture class. You've probably guessed: `_F`
267is for fixture.
268
269Unfortunately, the C++ macro system does not allow us to create a single macro
270that can handle both types of tests. Using the wrong macro causes a compiler
271error.
272
273Also, you must first define a test fixture class before using it in a
274`TEST_F()`, or you'll get the compiler error "`virtual outside class
275declaration`".
276
277For each test defined with `TEST_F()`, Google Test will:
278  1. Create a _fresh_ test fixture at runtime
279  1. Immediately initialize it via `SetUp()` ,
280  1. Run the test
281  1. Clean up by calling `TearDown()`
282  1. Delete the test fixture.  Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
283
284As an example, let's write tests for a FIFO queue class named `Queue`, which
285has the following interface:
286```
287template <typename E> // E is the element type.
288class Queue {
289 public:
290  Queue();
291  void Enqueue(const E& element);
292  E* Dequeue(); // Returns NULL if the queue is empty.
293  size_t size() const;
294  ...
295};
296```
297
298First, define a fixture class. By convention, you should give it the name
299`FooTest` where `Foo` is the class being tested.
300```
301class QueueTest : public ::testing::Test {
302 protected:
303  virtual void SetUp() {
304    q1_.Enqueue(1);
305    q2_.Enqueue(2);
306    q2_.Enqueue(3);
307  }
308
309  // virtual void TearDown() {}
310
311  Queue<int> q0_;
312  Queue<int> q1_;
313  Queue<int> q2_;
314};
315```
316
317In this case, `TearDown()` is not needed since we don't have to clean up after
318each test, other than what's already done by the destructor.
319
320Now we'll write tests using `TEST_F()` and this fixture.
321```
322TEST_F(QueueTest, IsEmptyInitially) {
323  EXPECT_EQ(0, q0_.size());
324}
325
326TEST_F(QueueTest, DequeueWorks) {
327  int* n = q0_.Dequeue();
328  EXPECT_EQ(NULL, n);
329
330  n = q1_.Dequeue();
331  ASSERT_TRUE(n != NULL);
332  EXPECT_EQ(1, *n);
333  EXPECT_EQ(0, q1_.size());
334  delete n;
335
336  n = q2_.Dequeue();
337  ASSERT_TRUE(n != NULL);
338  EXPECT_EQ(2, *n);
339  EXPECT_EQ(1, q2_.size());
340  delete n;
341}
342```
343
344The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
345to use `EXPECT_*` when you want the test to continue to reveal more errors
346after the assertion failure, and use `ASSERT_*` when continuing after failure
347doesn't make sense. For example, the second assertion in the `Dequeue` test is
348`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later,
349which would lead to a segfault when `n` is `NULL`.
350
351When these tests run, the following happens:
352  1. Google Test constructs a `QueueTest` object (let's call it `t1` ).
353  1. `t1.SetUp()` initializes `t1` .
354  1. The first test ( `IsEmptyInitially` ) runs on `t1` .
355  1. `t1.TearDown()` cleans up after the test finishes.
356  1. `t1` is destructed.
357  1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test.
358
359_Availability_: Linux, Windows, Mac.
360
361_Note_: Google Test automatically saves all _Google Test_ flags when a test
362object is constructed, and restores them when it is destructed.
363
364# Invoking the Tests #
365
366`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
367
368After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files.
369
370When invoked, the `RUN_ALL_TESTS()` macro:
371  1. Saves the state of all  Google Test flags.
372  1. Creates a test fixture object for the first test.
373  1. Initializes it via `SetUp()`.
374  1. Runs the test on the fixture object.
375  1. Cleans up the fixture via `TearDown()`.
376  1. Deletes the fixture.
377  1. Restores the state of all Google Test flags.
378  1. Repeats the above steps for the next test, until all tests have run.
379
380In addition, if the text fixture's constructor generates a fatal failure in
381step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly,
382if step 3 generates a fatal failure, step 4 will be skipped.
383
384_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc`
385will give you a compiler error. The rationale for this design is that the
386automated testing service determines whether a test has passed based on its
387exit code, not on its stdout/stderr output; thus your `main()` function must
388return the value of `RUN_ALL_TESTS()`.
389
390Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once
391conflicts with some advanced Google Test features (e.g. thread-safe death
392tests) and thus is not supported.
393
394_Availability_: Linux, Windows, Mac.
395
396# Writing the main() Function #
397
398You can start from this boilerplate:
399```
400#include "this/package/foo.h"
401#include <gtest/gtest.h>
402
403namespace {
404
405// The fixture for testing class Foo.
406class FooTest : public ::testing::Test {
407 protected:
408  // You can remove any or all of the following functions if its body
409  // is empty.
410
411  FooTest() {
412    // You can do set-up work for each test here.
413  }
414
415  virtual ~FooTest() {
416    // You can do clean-up work that doesn't throw exceptions here.
417  }
418
419  // If the constructor and destructor are not enough for setting up
420  // and cleaning up each test, you can define the following methods:
421
422  virtual void SetUp() {
423    // Code here will be called immediately after the constructor (right
424    // before each test).
425  }
426
427  virtual void TearDown() {
428    // Code here will be called immediately after each test (right
429    // before the destructor).
430  }
431
432  // Objects declared here can be used by all tests in the test case for Foo.
433};
434
435// Tests that the Foo::Bar() method does Abc.
436TEST_F(FooTest, MethodBarDoesAbc) {
437  const string input_filepath = "this/package/testdata/myinputfile.dat";
438  const string output_filepath = "this/package/testdata/myoutputfile.dat";
439  Foo f;
440  EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
441}
442
443// Tests that Foo does Xyz.
444TEST_F(FooTest, DoesXyz) {
445  // Exercises the Xyz feature of Foo.
446}
447
448}  // namespace
449
450int main(int argc, char **argv) {
451  ::testing::InitGoogleTest(&argc, argv);
452  return RUN_ALL_TESTS();
453}
454```
455
456The `::testing::InitGoogleTest()` function parses the command line for Google
457Test flags, and removes all recognized flags. This allows the user to control a
458test program's behavior via various flags, which we'll cover in [AdvancedGuide](V1_5_AdvancedGuide.md).
459You must call this function before calling `RUN_ALL_TESTS()`, or the flags
460won't be properly initialized.
461
462On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
463in programs compiled in `UNICODE` mode as well.
464
465But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go.
466
467## Important note for Visual C++ users ##
468If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:
469```
470__declspec(dllexport) int PullInMyLibrary() { return 0; }
471```
472If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function:
473```
474int PullInMyLibrary();
475static int dummy = PullInMyLibrary();
476```
477This will keep your tests referenced and will make them register themselves at startup.
478
479In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.
480
481There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!
482
483# Where to Go from Here #
484
485Congratulations! You've learned the Google Test basics. You can start writing
486and running Google Test tests, read some [samples](Samples.md), or continue with
487[AdvancedGuide](V1_5_AdvancedGuide.md), which describes many more useful Google Test features.
488
489# Known Limitations #
490
491Google Test is designed to be thread-safe.  The implementation is
492thread-safe on systems where the `pthreads` library is available.  It
493is currently _unsafe_ to use Google Test assertions from two threads
494concurrently on other systems (e.g. Windows).  In most tests this is
495not an issue as usually the assertions are done in the main thread. If
496you want to help, you can volunteer to implement the necessary
497synchronization primitives in `gtest-port.h` for your platform.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_5_PumpManual.md
r0r249096
1
2
3<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
4
5# The Problem #
6
7Template and macro libraries often need to define many classes,
8functions, or macros that vary only (or almost only) in the number of
9arguments they take. It's a lot of repetitive, mechanical, and
10error-prone work.
11
12Variadic templates and variadic macros can alleviate the problem.
13However, while both are being considered by the C++ committee, neither
14is in the standard yet or widely supported by compilers.  Thus they
15are often not a good choice, especially when your code needs to be
16portable. And their capabilities are still limited.
17
18As a result, authors of such libraries often have to write scripts to
19generate their implementation. However, our experience is that it's
20tedious to write such scripts, which tend to reflect the structure of
21the generated code poorly and are often hard to read and edit. For
22example, a small change needed in the generated code may require some
23non-intuitive, non-trivial changes in the script. This is especially
24painful when experimenting with the code.
25
26# Our Solution #
27
28Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
29Programming, or Practical Utility for Meta Programming, whichever you
30prefer) is a simple meta-programming tool for C++. The idea is that a
31programmer writes a `foo.pump` file which contains C++ code plus meta
32code that manipulates the C++ code. The meta code can handle
33iterations over a range, nested iterations, local meta variable
34definitions, simple arithmetic, and conditional expressions. You can
35view it as a small Domain-Specific Language. The meta language is
36designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode,
37for example) and concise, making Pump code intuitive and easy to
38maintain.
39
40## Highlights ##
41
42  * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms.
43  * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly.
44  * The format is human-readable and more concise than XML.
45  * The format works relatively well with Emacs' C++ mode.
46
47## Examples ##
48
49The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line):
50
51```
52$var n = 3     $$ Defines a meta variable n.
53$range i 0..n  $$ Declares the range of meta iterator i (inclusive).
54$for i [[
55               $$ Meta loop.
56// Foo$i does blah for $i-ary predicates.
57$range j 1..i
58template <size_t N $for j [[, typename A$j]]>
59class Foo$i {
60$if i == 0 [[
61  blah a;
62]] $elif i <= 2 [[
63  blah b;
64]] $else [[
65  blah c;
66]]
67};
68
69]]
70```
71
72will be translated by the Pump compiler to:
73
74```
75// Foo0 does blah for 0-ary predicates.
76template <size_t N>
77class Foo0 {
78  blah a;
79};
80
81// Foo1 does blah for 1-ary predicates.
82template <size_t N, typename A1>
83class Foo1 {
84  blah b;
85};
86
87// Foo2 does blah for 2-ary predicates.
88template <size_t N, typename A1, typename A2>
89class Foo2 {
90  blah b;
91};
92
93// Foo3 does blah for 3-ary predicates.
94template <size_t N, typename A1, typename A2, typename A3>
95class Foo3 {
96  blah c;
97};
98```
99
100In another example,
101
102```
103$range i 1..n
104Func($for i + [[a$i]]);
105$$ The text between i and [[ is the separator between iterations.
106```
107
108will generate one of the following lines (without the comments), depending on the value of `n`:
109
110```
111Func();              // If n is 0.
112Func(a1);            // If n is 1.
113Func(a1 + a2);       // If n is 2.
114Func(a1 + a2 + a3);  // If n is 3.
115// And so on...
116```
117
118## Constructs ##
119
120We support the following meta programming constructs:
121
122| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. |
123|:----------------|:-----------------------------------------------------------------------------------------------|
124| $range id exp..exp | Sets the range of an iteration variable, which can be reused in multiple loops later.          |
125| $for id sep [[code ](.md)] | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`.         |
126| `$($)`          | Generates a single `$` character.                                                              |
127| `$id`           | Value of the named constant or iteration variable.                                             |
128| `$(exp)`        | Value of the expression.                                                                       |
129| `$if exp [[ code ]] else_branch` | Conditional.                                                                                   |
130| `[[ code ]]`    | Meta lexical block.                                                                            |
131| `cpp_code`      | Raw C++ code.                                                                                  |
132| `$$ comment`    | Meta comment.                                                                                  |
133
134**Note:** To give the user some freedom in formatting the Pump source
135code, Pump ignores a new-line character if it's right after `$for foo`
136or next to `[[` or `]]`. Without this rule you'll often be forced to write
137very long lines to get the desired output. Therefore sometimes you may
138need to insert an extra new-line in such places for a new-line to show
139up in your output.
140
141## Grammar ##
142
143```
144code ::= atomic_code*
145atomic_code ::= $var id = exp
146    | $var id = [[ code ]]
147    | $range id exp..exp
148    | $for id sep [[ code ]]
149    | $($)
150    | $id
151    | $(exp)
152    | $if exp [[ code ]] else_branch
153    | [[ code ]]
154    | cpp_code
155sep ::= cpp_code | empty_string
156else_branch ::= $else [[ code ]]
157    | $elif exp [[ code ]] else_branch
158    | empty_string
159exp ::= simple_expression_in_Python_syntax
160```
161
162## Code ##
163
164You can find the source code of Pump in [scripts/pump.py](http://code.google.com/p/googletest/source/browse/trunk/scripts/pump.py). It is still
165very unpolished and lacks automated tests, although it has been
166successfully used many times. If you find a chance to use it in your
167project, please let us know what you think!  We also welcome help on
168improving Pump.
169
170## Real Examples ##
171
172You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com).  The source file `foo.h.pump` generates `foo.h`.
173
174## Tips ##
175
176  * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1.
177  * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_5_XcodeGuide.md
r0r249096
1
2
3This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step.
4
5# Quick Start #
6
7Here is the quick guide for using Google Test in your Xcode project.
8
9  1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`
10  1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework.
11  1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests"
12  1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests"
13  1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests"
14  1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable.
15  1. Build and Go
16
17The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations.
18
19# Get the Source #
20
21Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command:
22
23```
24svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only
25```
26
27Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository.
28
29To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory.
30
31The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`).
32
33Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory.
34
35```
36[Computer:svn] user$ svn propget svn:externals trunk
37externals/src/googletest http://googletest.googlecode.com/svn/trunk
38```
39
40# Add the Framework to Your Project #
41
42The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below.
43
44  * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project.
45  * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below).
46
47# Make a Test Target #
48
49To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target.
50
51Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above.
52
53  * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library.
54  * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll  want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase.
55
56# Set Up the Executable Run Environment #
57
58Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework.
59
60If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this:
61
62```
63[Session started at 2008-08-15 06:23:57 -0600.]
64  dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest
65    Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest
66    Reason: image not found
67```
68
69To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH.
70
71# Build and Go #
72
73Now, when you click "Build and Go", the test will be executed. Dumping out something like this:
74
75```
76[Session started at 2008-08-06 06:36:13 -0600.]
77[==========] Running 2 tests from 1 test case.
78[----------] Global test environment set-up.
79[----------] 2 tests from WidgetInitializerTest
80[ RUN      ] WidgetInitializerTest.TestConstructor
81[       OK ] WidgetInitializerTest.TestConstructor
82[ RUN      ] WidgetInitializerTest.TestConversion
83[       OK ] WidgetInitializerTest.TestConversion
84[----------] Global test environment tear-down
85[==========] 2 tests from 1 test case ran.
86[  PASSED  ] 2 tests.
87
88The Debugger has exited with status 0. 
89```
90
91# Summary #
92
93Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_6_AdvancedGuide.md
r0r249096
1
2
3Now that you have read [Primer](V1_6_Primer.md) and learned how to write tests
4using Google Test, it's time to learn some new tricks. This document
5will show you more assertions as well as how to construct complex
6failure messages, propagate fatal failures, reuse and speed up your
7test fixtures, and use various flags with your tests.
8
9# More Assertions #
10
11This section covers some less frequently used, but still significant,
12assertions.
13
14## Explicit Success and Failure ##
15
16These three assertions do not actually test a value or expression. Instead,
17they generate a success or failure directly. Like the macros that actually
18perform a test, you may stream a custom failure message into the them.
19
20| `SUCCEED();` |
21|:-------------|
22
23Generates a success. This does NOT make the overall test succeed. A test is
24considered successful only if none of its assertions fail during its execution.
25
26Note: `SUCCEED()` is purely documentary and currently doesn't generate any
27user-visible output. However, we may add `SUCCEED()` messages to Google Test's
28output in the future.
29
30| `FAIL();`  | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` |
31|:-----------|:-----------------|:------------------------------------------------------|
32
33`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal
34failure. These are useful when control flow, rather than a Boolean expression,
35deteremines the test's success or failure. For example, you might want to write
36something like:
37
38```
39switch(expression) {
40  case 1: ... some checks ...
41  case 2: ... some other checks
42  ...
43  default: FAIL() << "We shouldn't get here.";
44}
45```
46
47_Availability_: Linux, Windows, Mac.
48
49## Exception Assertions ##
50
51These are for verifying that a piece of code throws (or does not
52throw) an exception of the given type:
53
54| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
55|:--------------------|:-----------------------|:-------------|
56| `ASSERT_THROW(`_statement_, _exception\_type_`);`  | `EXPECT_THROW(`_statement_, _exception\_type_`);`  | _statement_ throws an exception of the given type  |
57| `ASSERT_ANY_THROW(`_statement_`);`                | `EXPECT_ANY_THROW(`_statement_`);`                | _statement_ throws an exception of any type        |
58| `ASSERT_NO_THROW(`_statement_`);`                 | `EXPECT_NO_THROW(`_statement_`);`                 | _statement_ doesn't throw any exception            |
59
60Examples:
61
62```
63ASSERT_THROW(Foo(5), bar_exception);
64
65EXPECT_NO_THROW({
66  int n = 5;
67  Bar(&n);
68});
69```
70
71_Availability_: Linux, Windows, Mac; since version 1.1.0.
72
73## Predicate Assertions for Better Error Messages ##
74
75Even though Google Test has a rich set of assertions, they can never be
76complete, as it's impossible (nor a good idea) to anticipate all the scenarios
77a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
78to check a complex expression, for lack of a better macro. This has the problem
79of not showing you the values of the parts of the expression, making it hard to
80understand what went wrong. As a workaround, some users choose to construct the
81failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
82is awkward especially when the expression has side-effects or is expensive to
83evaluate.
84
85Google Test gives you three different options to solve this problem:
86
87### Using an Existing Boolean Function ###
88
89If you already have a function or a functor that returns `bool` (or a type
90that can be implicitly converted to `bool`), you can use it in a _predicate
91assertion_ to get the function arguments printed for free:
92
93| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
94|:--------------------|:-----------------------|:-------------|
95| `ASSERT_PRED1(`_pred1, val1_`);`       | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
96| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` |  _pred2(val1, val2)_ returns true |
97|  ...                | ...                    | ...          |
98
99In the above, _predn_ is an _n_-ary predicate function or functor, where
100_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
101if the predicate returns `true` when applied to the given arguments, and fails
102otherwise. When the assertion fails, it prints the value of each argument. In
103either case, the arguments are evaluated exactly once.
104
105Here's an example. Given
106
107```
108// Returns true iff m and n have no common divisors except 1.
109bool MutuallyPrime(int m, int n) { ... }
110const int a = 3;
111const int b = 4;
112const int c = 10;
113```
114
115the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
116assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message
117
118<pre>
119!MutuallyPrime(b, c) is false, where<br>
120b is 4<br>
121c is 10<br>
122</pre>
123
124**Notes:**
125
126  1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](http://code.google.com/p/googletest/wiki/V1_6_FAQ#The_compiler_complains_%22no_matching_function_to_call%22) for how to resolve it.
127  1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.
128
129_Availability_: Linux, Windows, Mac
130
131### Using a Function That Returns an AssertionResult ###
132
133While `EXPECT_PRED*()` and friends are handy for a quick job, the
134syntax is not satisfactory: you have to use different macros for
135different arities, and it feels more like Lisp than C++.  The
136`::testing::AssertionResult` class solves this problem.
137
138An `AssertionResult` object represents the result of an assertion
139(whether it's a success or a failure, and an associated message).  You
140can create an `AssertionResult` using one of these factory
141functions:
142
143```
144namespace testing {
145
146// Returns an AssertionResult object to indicate that an assertion has
147// succeeded.
148AssertionResult AssertionSuccess();
149
150// Returns an AssertionResult object to indicate that an assertion has
151// failed.
152AssertionResult AssertionFailure();
153
154}
155```
156
157You can then use the `<<` operator to stream messages to the
158`AssertionResult` object.
159
160To provide more readable messages in Boolean assertions
161(e.g. `EXPECT_TRUE()`), write a predicate function that returns
162`AssertionResult` instead of `bool`. For example, if you define
163`IsEven()` as:
164
165```
166::testing::AssertionResult IsEven(int n) {
167  if ((n % 2) == 0)
168    return ::testing::AssertionSuccess();
169  else
170    return ::testing::AssertionFailure() << n << " is odd";
171}
172```
173
174instead of:
175
176```
177bool IsEven(int n) {
178  return (n % 2) == 0;
179}
180```
181
182the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
183
184<pre>
185Value of: !IsEven(Fib(4))<br>
186Actual: false (*3 is odd*)<br>
187Expected: true<br>
188</pre>
189
190instead of a more opaque
191
192<pre>
193Value of: !IsEven(Fib(4))<br>
194Actual: false<br>
195Expected: true<br>
196</pre>
197
198If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
199as well, and are fine with making the predicate slower in the success
200case, you can supply a success message:
201
202```
203::testing::AssertionResult IsEven(int n) {
204  if ((n % 2) == 0)
205    return ::testing::AssertionSuccess() << n << " is even";
206  else
207    return ::testing::AssertionFailure() << n << " is odd";
208}
209```
210
211Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
212
213<pre>
214Value of: !IsEven(Fib(6))<br>
215Actual: true (8 is even)<br>
216Expected: false<br>
217</pre>
218
219_Availability_: Linux, Windows, Mac; since version 1.4.1.
220
221### Using a Predicate-Formatter ###
222
223If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
224`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
225predicate do not support streaming to `ostream`, you can instead use the
226following _predicate-formatter assertions_ to _fully_ customize how the
227message is formatted:
228
229| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
230|:--------------------|:-----------------------|:-------------|
231| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);`        | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`); | _pred\_format1(val1)_ is successful |
232| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful |
233| `...`               | `...`                  | `...`        |
234
235The difference between this and the previous two groups of macros is that instead of
236a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_
237(_pred\_formatn_), which is a function or functor with the signature:
238
239`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);`
240
241where _val1_, _val2_, ..., and _valn_ are the values of the predicate
242arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding
243expressions as they appear in the source code. The types `T1`, `T2`, ..., and
244`Tn` can be either value types or reference types. For example, if an
245argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`,
246whichever is appropriate.
247
248A predicate-formatter returns a `::testing::AssertionResult` object to indicate
249whether the assertion has succeeded or not. The only way to create such an
250object is to call one of these factory functions:
251
252As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`:
253
254```
255// Returns the smallest prime common divisor of m and n,
256// or 1 when m and n are mutually prime.
257int SmallestPrimeCommonDivisor(int m, int n) { ... }
258
259// A predicate-formatter for asserting that two integers are mutually prime.
260::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
261                                               const char* n_expr,
262                                               int m,
263                                               int n) {
264  if (MutuallyPrime(m, n))
265    return ::testing::AssertionSuccess();
266 
267  return ::testing::AssertionFailure()
268      << m_expr << " and " << n_expr << " (" << m << " and " << n
269      << ") are not mutually prime, " << "as they have a common divisor "
270      << SmallestPrimeCommonDivisor(m, n);
271}
272```
273
274With this predicate-formatter, we can use
275
276```
277EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
278```
279
280to generate the message
281
282<pre>
283b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br>
284</pre>
285
286As you may have realized, many of the assertions we introduced earlier are
287special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
288indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.
289
290_Availability_: Linux, Windows, Mac.
291
292
293## Floating-Point Comparison ##
294
295Comparing floating-point numbers is tricky. Due to round-off errors, it is
296very unlikely that two floating-points will match exactly. Therefore,
297`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points
298can have a wide value range, no single fixed error bound works. It's better to
299compare by a fixed relative error bound, except for values close to 0 due to
300the loss of precision there.
301
302In general, for floating-point comparison to make sense, the user needs to
303carefully choose the error bound. If they don't want or care to, comparing in
304terms of Units in the Last Place (ULPs) is a good default, and Google Test
305provides assertions to do this. Full details about ULPs are quite long; if you
306want to learn more, see
307[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).
308
309### Floating-Point Macros ###
310
311| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
312|:--------------------|:-----------------------|:-------------|
313| `ASSERT_FLOAT_EQ(`_expected, actual_`);`  | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal |
314| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | the two `double` values are almost equal |
315
316By "almost equal", we mean the two values are within 4 ULP's from each
317other.
318
319The following assertions allow you to choose the acceptable error bound:
320
321| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
322|:--------------------|:-----------------------|:-------------|
323| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error |
324
325_Availability_: Linux, Windows, Mac.
326
327### Floating-Point Predicate-Format Functions ###
328
329Some floating-point operations are useful, but not that often used. In order
330to avoid an explosion of new macros, we provide them as predicate-format
331functions that can be used in predicate assertion macros (e.g.
332`EXPECT_PRED_FORMAT2`, etc).
333
334```
335EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
336EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
337```
338
339Verifies that _val1_ is less than, or almost equal to, _val2_. You can
340replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.
341
342_Availability_: Linux, Windows, Mac.
343
344## Windows HRESULT assertions ##
345
346These assertions test for `HRESULT` success or failure.
347
348| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
349|:--------------------|:-----------------------|:-------------|
350| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` |
351| `ASSERT_HRESULT_FAILED(`_expression_`);`    | `EXPECT_HRESULT_FAILED(`_expression_`);`    | _expression_ is a failure `HRESULT` |
352
353The generated output contains the human-readable error message
354associated with the `HRESULT` code returned by _expression_.
355
356You might use them like this:
357
358```
359CComPtr shell;
360ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
361CComVariant empty;
362ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
363```
364
365_Availability_: Windows.
366
367## Type Assertions ##
368
369You can call the function
370```
371::testing::StaticAssertTypeEq<T1, T2>();
372```
373to assert that types `T1` and `T2` are the same.  The function does
374nothing if the assertion is satisfied.  If the types are different,
375the function call will fail to compile, and the compiler error message
376will likely (depending on the compiler) show you the actual values of
377`T1` and `T2`.  This is mainly useful inside template code.
378
379_Caveat:_ When used inside a member function of a class template or a
380function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_
381the function is instantiated.  For example, given:
382```
383template <typename T> class Foo {
384 public:
385  void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
386};
387```
388the code:
389```
390void Test1() { Foo<bool> foo; }
391```
392will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never
393actually instantiated.  Instead, you need:
394```
395void Test2() { Foo<bool> foo; foo.Bar(); }
396```
397to cause a compiler error.
398
399_Availability:_ Linux, Windows, Mac; since version 1.3.0.
400
401## Assertion Placement ##
402
403You can use assertions in any C++ function. In particular, it doesn't
404have to be a method of the test fixture class. The one constraint is
405that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`)
406can only be used in void-returning functions. This is a consequence of
407Google Test not using exceptions. By placing it in a non-void function
408you'll get a confusing compile error like
409`"error: void value not ignored as it ought to be"`.
410
411If you need to use assertions in a function that returns non-void, one option
412is to make the function return the value in an out parameter instead. For
413example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
414need to make sure that `*result` contains some sensible value even when the
415function returns prematurely. As the function now returns `void`, you can use
416any assertion inside of it.
417
418If changing the function's type is not an option, you should just use
419assertions that generate non-fatal failures, such as `ADD_FAILURE*` and
420`EXPECT_*`.
421
422_Note_: Constructors and destructors are not considered void-returning
423functions, according to the C++ language specification, and so you may not use
424fatal assertions in them. You'll get a compilation error if you try. A simple
425workaround is to transfer the entire body of the constructor or destructor to a
426private void-returning method. However, you should be aware that a fatal
427assertion failure in a constructor does not terminate the current test, as your
428intuition might suggest; it merely returns from the constructor early, possibly
429leaving your object in a partially-constructed state. Likewise, a fatal
430assertion failure in a destructor may leave your object in a
431partially-destructed state. Use assertions carefully in these situations!
432
433# Teaching Google Test How to Print Your Values #
434
435When a test assertion such as `EXPECT_EQ` fails, Google Test prints the
436argument values to help you debug.  It does this using a
437user-extensible value printer.
438
439This printer knows how to print built-in C++ types, native arrays, STL
440containers, and any type that supports the `<<` operator.  For other
441types, it prints the raw bytes in the value and hopes that you the
442user can figure it out.
443
444As mentioned earlier, the printer is _extensible_.  That means
445you can teach it to do a better job at printing your particular type
446than to dump the bytes.  To do that, define `<<` for your type:
447
448```
449#include <iostream>
450
451namespace foo {
452
453class Bar { ... };  // We want Google Test to be able to print instances of this.
454
455// It's important that the << operator is defined in the SAME
456// namespace that defines Bar.  C++'s look-up rules rely on that.
457::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {
458  return os << bar.DebugString();  // whatever needed to print bar to os
459}
460
461}  // namespace foo
462```
463
464Sometimes, this might not be an option: your team may consider it bad
465style to have a `<<` operator for `Bar`, or `Bar` may already have a
466`<<` operator that doesn't do what you want (and you cannot change
467it).  If so, you can instead define a `PrintTo()` function like this:
468
469```
470#include <iostream>
471
472namespace foo {
473
474class Bar { ... };
475
476// It's important that PrintTo() is defined in the SAME
477// namespace that defines Bar.  C++'s look-up rules rely on that.
478void PrintTo(const Bar& bar, ::std::ostream* os) {
479  *os << bar.DebugString();  // whatever needed to print bar to os
480}
481
482}  // namespace foo
483```
484
485If you have defined both `<<` and `PrintTo()`, the latter will be used
486when Google Test is concerned.  This allows you to customize how the value
487appears in Google Test's output without affecting code that relies on the
488behavior of its `<<` operator.
489
490If you want to print a value `x` using Google Test's value printer
491yourself, just call `::testing::PrintToString(`_x_`)`, which
492returns an `std::string`:
493
494```
495vector<pair<Bar, int> > bar_ints = GetBarIntVector();
496
497EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
498    << "bar_ints = " << ::testing::PrintToString(bar_ints);
499```
500
501# Death Tests #
502
503In many applications, there are assertions that can cause application failure
504if a condition is not met. These sanity checks, which ensure that the program
505is in a known good state, are there to fail at the earliest possible time after
506some program state is corrupted. If the assertion checks the wrong condition,
507then the program may proceed in an erroneous state, which could lead to memory
508corruption, security holes, or worse. Hence it is vitally important to test
509that such assertion statements work as expected.
510
511Since these precondition checks cause the processes to die, we call such tests
512_death tests_. More generally, any test that checks that a program terminates
513(except by throwing an exception) in an expected fashion is also a death test.
514
515Note that if a piece of code throws an exception, we don't consider it "death"
516for the purpose of death tests, as the caller of the code could catch the exception
517and avoid the crash. If you want to verify exceptions thrown by your code,
518see [Exception Assertions](#Exception_Assertions.md).
519
520If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#Catching_Failures.md).
521
522## How to Write a Death Test ##
523
524Google Test has the following macros to support death tests:
525
526| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
527|:--------------------|:-----------------------|:-------------|
528| `ASSERT_DEATH(`_statement, regex_`); | `EXPECT_DEATH(`_statement, regex_`); | _statement_ crashes with the given error |
529| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`); | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`); | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing |
530| `ASSERT_EXIT(`_statement, predicate, regex_`); | `EXPECT_EXIT(`_statement, predicate, regex_`); |_statement_ exits with the given error and its exit code matches _predicate_ |
531
532where _statement_ is a statement that is expected to cause the process to
533die, _predicate_ is a function or function object that evaluates an integer
534exit status, and _regex_ is a regular expression that the stderr output of
535_statement_ is expected to match. Note that _statement_ can be _any valid
536statement_ (including _compound statement_) and doesn't have to be an
537expression.
538
539As usual, the `ASSERT` variants abort the current test function, while the
540`EXPECT` variants do not.
541
542**Note:** We use the word "crash" here to mean that the process
543terminates with a _non-zero_ exit status code.  There are two
544possibilities: either the process has called `exit()` or `_exit()`
545with a non-zero value, or it may be killed by a signal.
546
547This means that if _statement_ terminates the process with a 0 exit
548code, it is _not_ considered a crash by `EXPECT_DEATH`.  Use
549`EXPECT_EXIT` instead if this is the case, or if you want to restrict
550the exit code more precisely.
551
552A predicate here must accept an `int` and return a `bool`. The death test
553succeeds only if the predicate returns `true`. Google Test defines a few
554predicates that handle the most common cases:
555
556```
557::testing::ExitedWithCode(exit_code)
558```
559
560This expression is `true` if the program exited normally with the given exit
561code.
562
563```
564::testing::KilledBySignal(signal_number)  // Not available on Windows.
565```
566
567This expression is `true` if the program was killed by the given signal.
568
569The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
570that verifies the process' exit code is non-zero.
571
572Note that a death test only cares about three things:
573
574  1. does _statement_ abort or exit the process?
575  1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_?  Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero?  And
576  1. does the stderr output match _regex_?
577
578In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process.
579
580To write a death test, simply use one of the above macros inside your test
581function. For example,
582
583```
584TEST(My*DeathTest*, Foo) {
585  // This death test uses a compound statement.
586  ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()");
587}
588TEST(MyDeathTest, NormalExit) {
589  EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
590}
591TEST(MyDeathTest, KillMyself) {
592  EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal");
593}
594```
595
596verifies that:
597
598  * calling `Foo(5)` causes the process to die with the given error message,
599  * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and
600  * calling `KillMyself()` kills the process with signal `SIGKILL`.
601
602The test function body may contain other assertions and statements as well, if
603necessary.
604
605_Important:_ We strongly recommend you to follow the convention of naming your
606test case (not test) `*DeathTest` when it contains a death test, as
607demonstrated in the above example. The `Death Tests And Threads` section below
608explains why.
609
610If a test fixture class is shared by normal tests and death tests, you
611can use typedef to introduce an alias for the fixture class and avoid
612duplicating its code:
613```
614class FooTest : public ::testing::Test { ... };
615
616typedef FooTest FooDeathTest;
617
618TEST_F(FooTest, DoesThis) {
619  // normal test
620}
621
622TEST_F(FooDeathTest, DoesThat) {
623  // death test
624}
625```
626
627_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0).  `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0.
628
629## Regular Expression Syntax ##
630
631On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the
632[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
633syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
634
635On Windows, Google Test uses its own simple regular expression
636implementation. It lacks many features you can find in POSIX extended
637regular expressions.  For example, we don't support union (`"x|y"`),
638grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count
639(`"x{5,7}"`), among others. Below is what we do support (`A` denotes a
640literal character, period (`.`), or a single `\\` escape sequence; `x`
641and `y` denote regular expressions.):
642
643| `c` | matches any literal character `c` |
644|:----|:----------------------------------|
645| `\\d` | matches any decimal digit         |
646| `\\D` | matches any character that's not a decimal digit |
647| `\\f` | matches `\f`                      |
648| `\\n` | matches `\n`                      |
649| `\\r` | matches `\r`                      |
650| `\\s` | matches any ASCII whitespace, including `\n` |
651| `\\S` | matches any character that's not a whitespace |
652| `\\t` | matches `\t`                      |
653| `\\v` | matches `\v`                      |
654| `\\w` | matches any letter, `_`, or decimal digit |
655| `\\W` | matches any character that `\\w` doesn't match |
656| `\\c` | matches any literal character `c`, which must be a punctuation |
657| `.` | matches any single character except `\n` |
658| `A?` | matches 0 or 1 occurrences of `A` |
659| `A*` | matches 0 or many occurrences of `A` |
660| `A+` | matches 1 or many occurrences of `A` |
661| `^` | matches the beginning of a string (not that of each line) |
662| `$` | matches the end of a string (not that of each line) |
663| `xy` | matches `x` followed by `y`       |
664
665To help you determine which capability is available on your system,
666Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX
667extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses
668the simple version.  If you want your death tests to work in both
669cases, you can either `#if` on these macros or use the more limited
670syntax only.
671
672## How It Works ##
673
674Under the hood, `ASSERT_EXIT()` spawns a new process and executes the
675death test statement in that process. The details of of how precisely
676that happens depend on the platform and the variable
677`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the
678command-line flag `--gtest_death_test_style`).
679
680  * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which:
681    * If the variable's value is `"fast"`, the death test statement is immediately executed.
682    * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run.
683  * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX.
684
685Other values for the variable are illegal and will cause the death test to
686fail. Currently, the flag's default value is `"fast"`. However, we reserve the
687right to change it in the future. Therefore, your tests should not depend on
688this.
689
690In either case, the parent process waits for the child process to complete, and checks that
691
692  1. the child's exit status satisfies the predicate, and
693  1. the child's stderr matches the regular expression.
694
695If the death test statement runs to completion without dying, the child
696process will nonetheless terminate, and the assertion fails.
697
698## Death Tests And Threads ##
699
700The reason for the two death test styles has to do with thread safety. Due to
701well-known problems with forking in the presence of threads, death tests should
702be run in a single-threaded context. Sometimes, however, it isn't feasible to
703arrange that kind of environment. For example, statically-initialized modules
704may start threads before main is ever reached. Once threads have been created,
705it may be difficult or impossible to clean them up.
706
707Google Test has three features intended to raise awareness of threading issues.
708
709  1. A warning is emitted if multiple threads are running when a death test is encountered.
710  1. Test cases with a name ending in "DeathTest" are run before all other tests.
711  1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads.
712
713It's perfectly fine to create threads inside a death test statement; they are
714executed in a separate process and cannot affect the parent.
715
716## Death Test Styles ##
717
718The "threadsafe" death test style was introduced in order to help mitigate the
719risks of testing in a possibly multithreaded environment. It trades increased
720test execution time (potentially dramatically so) for improved thread safety.
721We suggest using the faster, default "fast" style unless your test has specific
722problems with it.
723
724You can choose a particular style of death tests by setting the flag
725programmatically:
726
727```
728::testing::FLAGS_gtest_death_test_style = "threadsafe";
729```
730
731You can do this in `main()` to set the style for all death tests in the
732binary, or in individual tests. Recall that flags are saved before running each
733test and restored afterwards, so you need not do that yourself. For example:
734
735```
736TEST(MyDeathTest, TestOne) {
737  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
738  // This test is run in the "threadsafe" style:
739  ASSERT_DEATH(ThisShouldDie(), "");
740}
741
742TEST(MyDeathTest, TestTwo) {
743  // This test is run in the "fast" style:
744  ASSERT_DEATH(ThisShouldDie(), "");
745}
746
747int main(int argc, char** argv) {
748  ::testing::InitGoogleTest(&argc, argv);
749  ::testing::FLAGS_gtest_death_test_style = "fast";
750  return RUN_ALL_TESTS();
751}
752```
753
754## Caveats ##
755
756The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement.
757If it leaves the current function via a `return` statement or by throwing an exception,
758the death test is considered to have failed.  Some Google Test macros may return
759from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_.
760
761Since _statement_ runs in the child process, any in-memory side effect (e.g.
762modifying a variable, releasing memory, etc) it causes will _not_ be observable
763in the parent process. In particular, if you release memory in a death test,
764your program will fail the heap check as the parent process will never see the
765memory reclaimed. To solve this problem, you can
766
767  1. try not to free memory in a death test;
768  1. free the memory again in the parent process; or
769  1. do not use the heap checker in your program.
770
771Due to an implementation detail, you cannot place multiple death test
772assertions on the same line; otherwise, compilation will fail with an unobvious
773error message.
774
775Despite the improved thread safety afforded by the "threadsafe" style of death
776test, thread problems such as deadlock are still possible in the presence of
777handlers registered with `pthread_atfork(3)`.
778
779# Using Assertions in Sub-routines #
780
781## Adding Traces to Assertions ##
782
783If a test sub-routine is called from several places, when an assertion
784inside it fails, it can be hard to tell which invocation of the
785sub-routine the failure is from.  You can alleviate this problem using
786extra logging or custom failure messages, but that usually clutters up
787your tests. A better solution is to use the `SCOPED_TRACE` macro:
788
789| `SCOPED_TRACE(`_message_`);` |
790|:-----------------------------|
791
792where _message_ can be anything streamable to `std::ostream`. This
793macro will cause the current file name, line number, and the given
794message to be added in every failure message. The effect will be
795undone when the control leaves the current lexical scope.
796
797For example,
798
799```
80010: void Sub1(int n) {
80111:   EXPECT_EQ(1, Bar(n));
80212:   EXPECT_EQ(2, Bar(n + 1));
80313: }
80414:
80515: TEST(FooTest, Bar) {
80616:   {
80717:     SCOPED_TRACE("A");  // This trace point will be included in
80818:                         // every failure in this scope.
80919:     Sub1(1);
81020:   }
81121:   // Now it won't.
81222:   Sub1(9);
81323: }
814```
815
816could result in messages like these:
817
818```
819path/to/foo_test.cc:11: Failure
820Value of: Bar(n)
821Expected: 1
822  Actual: 2
823   Trace:
824path/to/foo_test.cc:17: A
825
826path/to/foo_test.cc:12: Failure
827Value of: Bar(n + 1)
828Expected: 2
829  Actual: 3
830```
831
832Without the trace, it would've been difficult to know which invocation
833of `Sub1()` the two failures come from respectively. (You could add an
834extra message to each assertion in `Sub1()` to indicate the value of
835`n`, but that's tedious.)
836
837Some tips on using `SCOPED_TRACE`:
838
839  1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site.
840  1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from.
841  1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`.
842  1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered.
843  1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file!
844
845_Availability:_ Linux, Windows, Mac.
846
847## Propagating Fatal Failures ##
848
849A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
850when they fail they only abort the _current function_, not the entire test. For
851example, the following test will segfault:
852```
853void Subroutine() {
854  // Generates a fatal failure and aborts the current function.
855  ASSERT_EQ(1, 2);
856  // The following won't be executed.
857  ...
858}
859
860TEST(FooTest, Bar) {
861  Subroutine();
862  // The intended behavior is for the fatal failure
863  // in Subroutine() to abort the entire test.
864  // The actual behavior: the function goes on after Subroutine() returns.
865  int* p = NULL;
866  *p = 3; // Segfault!
867}
868```
869
870Since we don't use exceptions, it is technically impossible to
871implement the intended behavior here.  To alleviate this, Google Test
872provides two solutions.  You could use either the
873`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
874`HasFatalFailure()` function.  They are described in the following two
875subsections.
876
877### Asserting on Subroutines ###
878
879As shown above, if your test calls a subroutine that has an `ASSERT_*`
880failure in it, the test will continue after the subroutine
881returns. This may not be what you want.
882
883Often people want fatal failures to propagate like exceptions.  For
884that Google Test offers the following macros:
885
886| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
887|:--------------------|:-----------------------|:-------------|
888| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. |
889
890Only failures in the thread that executes the assertion are checked to
891determine the result of this type of assertions.  If _statement_
892creates new threads, failures in these threads are ignored.
893
894Examples:
895
896```
897ASSERT_NO_FATAL_FAILURE(Foo());
898
899int i;
900EXPECT_NO_FATAL_FAILURE({
901  i = Bar();
902});
903```
904
905_Availability:_ Linux, Windows, Mac. Assertions from multiple threads
906are currently not supported.
907
908### Checking for Failures in the Current Test ###
909
910`HasFatalFailure()` in the `::testing::Test` class returns `true` if an
911assertion in the current test has suffered a fatal failure. This
912allows functions to catch fatal failures in a sub-routine and return
913early.
914
915```
916class Test {
917 public:
918  ...
919  static bool HasFatalFailure();
920};
921```
922
923The typical usage, which basically simulates the behavior of a thrown
924exception, is:
925
926```
927TEST(FooTest, Bar) {
928  Subroutine();
929  // Aborts if Subroutine() had a fatal failure.
930  if (HasFatalFailure())
931    return;
932  // The following won't be executed.
933  ...
934}
935```
936
937If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
938fixture, you must add the `::testing::Test::` prefix, as in:
939
940```
941if (::testing::Test::HasFatalFailure())
942  return;
943```
944
945Similarly, `HasNonfatalFailure()` returns `true` if the current test
946has at least one non-fatal failure, and `HasFailure()` returns `true`
947if the current test has at least one failure of either kind.
948
949_Availability:_ Linux, Windows, Mac.  `HasNonfatalFailure()` and
950`HasFailure()` are available since version 1.4.0.
951
952# Logging Additional Information #
953
954In your test code, you can call `RecordProperty("key", value)` to log
955additional information, where `value` can be either a C string or a 32-bit
956integer. The _last_ value recorded for a key will be emitted to the XML output
957if you specify one. For example, the test
958
959```
960TEST_F(WidgetUsageTest, MinAndMaxWidgets) {
961  RecordProperty("MaximumWidgets", ComputeMaxUsage());
962  RecordProperty("MinimumWidgets", ComputeMinUsage());
963}
964```
965
966will output XML like this:
967
968```
969...
970  <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest"
971            MaximumWidgets="12"
972            MinimumWidgets="9" />
973...
974```
975
976_Note_:
977  * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class.
978  * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`,     `time`, and `classname`).
979
980_Availability_: Linux, Windows, Mac.
981
982# Sharing Resources Between Tests in the Same Test Case #
983
984
985
986Google Test creates a new test fixture object for each test in order to make
987tests independent and easier to debug. However, sometimes tests use resources
988that are expensive to set up, making the one-copy-per-test model prohibitively
989expensive.
990
991If the tests don't change the resource, there's no harm in them sharing a
992single resource copy. So, in addition to per-test set-up/tear-down, Google Test
993also supports per-test-case set-up/tear-down. To use it:
994
995  1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources.
996  1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down.
997
998That's it! Google Test automatically calls `SetUpTestCase()` before running the
999_first test_ in the `FooTest` test case (i.e. before creating the first
1000`FooTest` object), and calls `TearDownTestCase()` after running the _last test_
1001in it (i.e. after deleting the last `FooTest` object). In between, the tests
1002can use the shared resources.
1003
1004Remember that the test order is undefined, so your code can't depend on a test
1005preceding or following another. Also, the tests must either not modify the
1006state of any shared resource, or, if they do modify the state, they must
1007restore the state to its original value before passing control to the next
1008test.
1009
1010Here's an example of per-test-case set-up and tear-down:
1011```
1012class FooTest : public ::testing::Test {
1013 protected:
1014  // Per-test-case set-up.
1015  // Called before the first test in this test case.
1016  // Can be omitted if not needed.
1017  static void SetUpTestCase() {
1018    shared_resource_ = new ...;
1019  }
1020
1021  // Per-test-case tear-down.
1022  // Called after the last test in this test case.
1023  // Can be omitted if not needed.
1024  static void TearDownTestCase() {
1025    delete shared_resource_;
1026    shared_resource_ = NULL;
1027  }
1028
1029  // You can define per-test set-up and tear-down logic as usual.
1030  virtual void SetUp() { ... }
1031  virtual void TearDown() { ... }
1032
1033  // Some expensive resource shared by all tests.
1034  static T* shared_resource_;
1035};
1036
1037T* FooTest::shared_resource_ = NULL;
1038
1039TEST_F(FooTest, Test1) {
1040  ... you can refer to shared_resource here ...
1041}
1042TEST_F(FooTest, Test2) {
1043  ... you can refer to shared_resource here ...
1044}
1045```
1046
1047_Availability:_ Linux, Windows, Mac.
1048
1049# Global Set-Up and Tear-Down #
1050
1051Just as you can do set-up and tear-down at the test level and the test case
1052level, you can also do it at the test program level. Here's how.
1053
1054First, you subclass the `::testing::Environment` class to define a test
1055environment, which knows how to set-up and tear-down:
1056
1057```
1058class Environment {
1059 public:
1060  virtual ~Environment() {}
1061  // Override this to define how to set up the environment.
1062  virtual void SetUp() {}
1063  // Override this to define how to tear down the environment.
1064  virtual void TearDown() {}
1065};
1066```
1067
1068Then, you register an instance of your environment class with Google Test by
1069calling the `::testing::AddGlobalTestEnvironment()` function:
1070
1071```
1072Environment* AddGlobalTestEnvironment(Environment* env);
1073```
1074
1075Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
1076the environment object, then runs the tests if there was no fatal failures, and
1077finally calls `TearDown()` of the environment object.
1078
1079It's OK to register multiple environment objects. In this case, their `SetUp()`
1080will be called in the order they are registered, and their `TearDown()` will be
1081called in the reverse order.
1082
1083Note that Google Test takes ownership of the registered environment objects.
1084Therefore **do not delete them** by yourself.
1085
1086You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is
1087called, probably in `main()`. If you use `gtest_main`, you need to      call
1088this before `main()` starts for it to take effect. One way to do this is to
1089define a global variable like this:
1090
1091```
1092::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
1093```
1094
1095However, we strongly recommend you to write your own `main()` and call
1096`AddGlobalTestEnvironment()` there, as relying on initialization of global
1097variables makes the code harder to read and may cause problems when you
1098register multiple environments from different translation units and the
1099environments have dependencies among them (remember that the compiler doesn't
1100guarantee the order in which global variables from different translation units
1101are initialized).
1102
1103_Availability:_ Linux, Windows, Mac.
1104
1105
1106# Value Parameterized Tests #
1107
1108_Value-parameterized tests_ allow you to test your code with different
1109parameters without writing multiple copies of the same test.
1110
1111Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag.
1112
1113```
1114TEST(MyCodeTest, TestFoo) {
1115  // A code to test foo().
1116}
1117```
1118
1119Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code.
1120
1121```
1122void TestFooHelper(bool flag_value) {
1123  flag = flag_value;
1124  // A code to test foo().
1125}
1126
1127TEST(MyCodeTest, TestFooo) {
1128  TestFooHelper(false);
1129  TestFooHelper(true);
1130}
1131```
1132
1133But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred?
1134
1135Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values.
1136
1137Here are some other situations when value-parameterized tests come handy:
1138
1139  * You want to test different implementations of an OO interface.
1140  * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it!
1141
1142## How to Write Value-Parameterized Tests ##
1143
1144To write value-parameterized tests, first you should define a fixture
1145class.  It must be derived from both `::testing::Test` and
1146`::testing::WithParamInterface<T>` (the latter is a pure interface),
1147where `T` is the type of your parameter values.  For convenience, you
1148can just derive the fixture class from `::testing::TestWithParam<T>`,
1149which itself is derived from both `::testing::Test` and
1150`::testing::WithParamInterface<T>`. `T` can be any copyable type. If
1151it's a raw pointer, you are responsible for managing the lifespan of
1152the pointed values.
1153
1154```
1155class FooTest : public ::testing::TestWithParam<const char*> {
1156  // You can implement all the usual fixture class members here.
1157  // To access the test parameter, call GetParam() from class
1158  // TestWithParam<T>.
1159};
1160
1161// Or, when you want to add parameters to a pre-existing fixture class:
1162class BaseTest : public ::testing::Test {
1163  ...
1164};
1165class BarTest : public BaseTest,
1166                public ::testing::WithParamInterface<const char*> {
1167  ...
1168};
1169```
1170
1171Then, use the `TEST_P` macro to define as many test patterns using
1172this fixture as you want.  The `_P` suffix is for "parameterized" or
1173"pattern", whichever you prefer to think.
1174
1175```
1176TEST_P(FooTest, DoesBlah) {
1177  // Inside a test, access the test parameter with the GetParam() method
1178  // of the TestWithParam<T> class:
1179  EXPECT_TRUE(foo.Blah(GetParam()));
1180  ...
1181}
1182
1183TEST_P(FooTest, HasBlahBlah) {
1184  ...
1185}
1186```
1187
1188Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test
1189case with any set of parameters you want. Google Test defines a number of
1190functions for generating test parameters. They return what we call
1191(surprise!) _parameter generators_. Here is a summary of them,
1192which are all in the `testing` namespace:
1193
1194| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
1195|:----------------------------|:------------------------------------------------------------------------------------------------------------------|
1196| `Values(v1, v2, ..., vN)`   | Yields values `{v1, v2, ..., vN}`.                                                                                |
1197| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time.  |
1198| `Bool()`                    | Yields sequence `{false, true}`.                                                                                  |
1199| `Combine(g1, g2, ..., gN)`  | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `<tr1/tuple>` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-port.h) for more information. |
1200
1201For more details, see the comments at the definitions of these functions in the [source code](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-param-test.h).
1202
1203The following statement will instantiate tests from the `FooTest` test case
1204each with parameter values `"meeny"`, `"miny"`, and `"moe"`.
1205
1206```
1207INSTANTIATE_TEST_CASE_P(InstantiationName,
1208                        FooTest,
1209                        ::testing::Values("meeny", "miny", "moe"));
1210```
1211
1212To distinguish different instances of the pattern (yes, you can
1213instantiate it more than once), the first argument to
1214`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual
1215test case name. Remember to pick unique prefixes for different
1216instantiations. The tests from the instantiation above will have these
1217names:
1218
1219  * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
1220  * `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
1221  * `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
1222  * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
1223  * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
1224  * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
1225
1226You can use these names in [--gtest\_filter](#Running_a_Subset_of_the_Tests.md).
1227
1228This statement will instantiate all tests from `FooTest` again, each
1229with parameter values `"cat"` and `"dog"`:
1230
1231```
1232const char* pets[] = {"cat", "dog"};
1233INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest,
1234                        ::testing::ValuesIn(pets));
1235```
1236
1237The tests from the instantiation above will have these names:
1238
1239  * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
1240  * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
1241  * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
1242  * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
1243
1244Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_
1245tests in the given test case, whether their definitions come before or
1246_after_ the `INSTANTIATE_TEST_CASE_P` statement.
1247
1248You can see
1249[these](http://code.google.com/p/googletest/source/browse/trunk/samples/sample7_unittest.cc)
1250[files](http://code.google.com/p/googletest/source/browse/trunk/samples/sample8_unittest.cc) for more examples.
1251
1252_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0.
1253
1254## Creating Value-Parameterized Abstract Tests ##
1255
1256In the above, we define and instantiate `FooTest` in the same source
1257file. Sometimes you may want to define value-parameterized tests in a
1258library and let other people instantiate them later. This pattern is
1259known as <i>abstract tests</i>. As an example of its application, when you
1260are designing an interface you can write a standard suite of abstract
1261tests (perhaps using a factory function as the test parameter) that
1262all implementations of the interface are expected to pass. When
1263someone implements the interface, he can instantiate your suite to get
1264all the interface-conformance tests for free.
1265
1266To define abstract tests, you should organize your code like this:
1267
1268  1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests.
1269  1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests.
1270
1271Once they are defined, you can instantiate them by including
1272`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking
1273with `foo_param_test.cc`. You can instantiate the same abstract test
1274case multiple times, possibly in different source files.
1275
1276# Typed Tests #
1277
1278Suppose you have multiple implementations of the same interface and
1279want to make sure that all of them satisfy some common requirements.
1280Or, you may have defined several types that are supposed to conform to
1281the same "concept" and you want to verify it.  In both cases, you want
1282the same test logic repeated for different types.
1283
1284While you can write one `TEST` or `TEST_F` for each type you want to
1285test (and you may even factor the test logic into a function template
1286that you invoke from the `TEST`), it's tedious and doesn't scale:
1287if you want _m_ tests over _n_ types, you'll end up writing _m\*n_
1288`TEST`s.
1289
1290_Typed tests_ allow you to repeat the same test logic over a list of
1291types.  You only need to write the test logic once, although you must
1292know the type list when writing typed tests.  Here's how you do it:
1293
1294First, define a fixture class template.  It should be parameterized
1295by a type.  Remember to derive it from `::testing::Test`:
1296
1297```
1298template <typename T>
1299class FooTest : public ::testing::Test {
1300 public:
1301  ...
1302  typedef std::list<T> List;
1303  static T shared_;
1304  T value_;
1305};
1306```
1307
1308Next, associate a list of types with the test case, which will be
1309repeated for each type in the list:
1310
1311```
1312typedef ::testing::Types<char, int, unsigned int> MyTypes;
1313TYPED_TEST_CASE(FooTest, MyTypes);
1314```
1315
1316The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse
1317correctly.  Otherwise the compiler will think that each comma in the
1318type list introduces a new macro argument.
1319
1320Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test
1321for this test case.  You can repeat this as many times as you want:
1322
1323```
1324TYPED_TEST(FooTest, DoesBlah) {
1325  // Inside a test, refer to the special name TypeParam to get the type
1326  // parameter.  Since we are inside a derived class template, C++ requires
1327  // us to visit the members of FooTest via 'this'.
1328  TypeParam n = this->value_;
1329
1330  // To visit static members of the fixture, add the 'TestFixture::'
1331  // prefix.
1332  n += TestFixture::shared_;
1333
1334  // To refer to typedefs in the fixture, add the 'typename TestFixture::'
1335  // prefix.  The 'typename' is required to satisfy the compiler.
1336  typename TestFixture::List values;
1337  values.push_back(n);
1338  ...
1339}
1340
1341TYPED_TEST(FooTest, HasPropertyA) { ... }
1342```
1343
1344You can see `samples/sample6_unittest.cc` for a complete example.
1345
1346_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1347since version 1.1.0.
1348
1349# Type-Parameterized Tests #
1350
1351_Type-parameterized tests_ are like typed tests, except that they
1352don't require you to know the list of types ahead of time.  Instead,
1353you can define the test logic first and instantiate it with different
1354type lists later.  You can even instantiate it more than once in the
1355same program.
1356
1357If you are designing an interface or concept, you can define a suite
1358of type-parameterized tests to verify properties that any valid
1359implementation of the interface/concept should have.  Then, the author
1360of each implementation can just instantiate the test suite with his
1361type to verify that it conforms to the requirements, without having to
1362write similar tests repeatedly.  Here's an example:
1363
1364First, define a fixture class template, as we did with typed tests:
1365
1366```
1367template <typename T>
1368class FooTest : public ::testing::Test {
1369  ...
1370};
1371```
1372
1373Next, declare that you will define a type-parameterized test case:
1374
1375```
1376TYPED_TEST_CASE_P(FooTest);
1377```
1378
1379The `_P` suffix is for "parameterized" or "pattern", whichever you
1380prefer to think.
1381
1382Then, use `TYPED_TEST_P()` to define a type-parameterized test.  You
1383can repeat this as many times as you want:
1384
1385```
1386TYPED_TEST_P(FooTest, DoesBlah) {
1387  // Inside a test, refer to TypeParam to get the type parameter.
1388  TypeParam n = 0;
1389  ...
1390}
1391
1392TYPED_TEST_P(FooTest, HasPropertyA) { ... }
1393```
1394
1395Now the tricky part: you need to register all test patterns using the
1396`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them.
1397The first argument of the macro is the test case name; the rest are
1398the names of the tests in this test case:
1399
1400```
1401REGISTER_TYPED_TEST_CASE_P(FooTest,
1402                           DoesBlah, HasPropertyA);
1403```
1404
1405Finally, you are free to instantiate the pattern with the types you
1406want.  If you put the above code in a header file, you can `#include`
1407it in multiple C++ source files and instantiate it multiple times.
1408
1409```
1410typedef ::testing::Types<char, int, unsigned int> MyTypes;
1411INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
1412```
1413
1414To distinguish different instances of the pattern, the first argument
1415to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be
1416added to the actual test case name.  Remember to pick unique prefixes
1417for different instances.
1418
1419In the special case where the type list contains only one type, you
1420can write that type directly without `::testing::Types<...>`, like this:
1421
1422```
1423INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
1424```
1425
1426You can see `samples/sample6_unittest.cc` for a complete example.
1427
1428_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1429since version 1.1.0.
1430
1431# Testing Private Code #
1432
1433If you change your software's internal implementation, your tests should not
1434break as long as the change is not observable by users. Therefore, per the
1435_black-box testing principle_, most of the time you should test your code
1436through its public interfaces.
1437
1438If you still find yourself needing to test internal implementation code,
1439consider if there's a better design that wouldn't require you to do so. If you
1440absolutely have to test non-public interface code though, you can. There are
1441two cases to consider:
1442
1443  * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and
1444  * Private or protected class members
1445
1446## Static Functions ##
1447
1448Both static functions and definitions/declarations in an unnamed namespace are
1449only visible within the same translation unit. To test them, you can `#include`
1450the entire `.cc` file being tested in your `*_test.cc` file. (#including `.cc`
1451files is not a good way to reuse code - you should not do this in production
1452code!)
1453
1454However, a better approach is to move the private code into the
1455`foo::internal` namespace, where `foo` is the namespace your project normally
1456uses, and put the private declarations in a `*-internal.h` file. Your
1457production `.cc` files and your tests are allowed to include this internal
1458header, but your clients are not. This way, you can fully test your internal
1459implementation without leaking it to your clients.
1460
1461## Private Class Members ##
1462
1463Private class members are only accessible from within the class or by friends.
1464To access a class' private members, you can declare your test fixture as a
1465friend to the class and define accessors in your fixture. Tests using the
1466fixture can then access the private members of your production class via the
1467accessors in the fixture. Note that even though your fixture is a friend to
1468your production class, your tests are not automatically friends to it, as they
1469are technically defined in sub-classes of the fixture.
1470
1471Another way to test private members is to refactor them into an implementation
1472class, which is then declared in a `*-internal.h` file. Your clients aren't
1473allowed to include this header but your tests can. Such is called the Pimpl
1474(Private Implementation) idiom.
1475
1476Or, you can declare an individual test as a friend of your class by adding this
1477line in the class body:
1478
1479```
1480FRIEND_TEST(TestCaseName, TestName);
1481```
1482
1483For example,
1484```
1485// foo.h
1486#include "gtest/gtest_prod.h"
1487
1488// Defines FRIEND_TEST.
1489class Foo {
1490  ...
1491 private:
1492  FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
1493  int Bar(void* x);
1494};
1495
1496// foo_test.cc
1497...
1498TEST(FooTest, BarReturnsZeroOnNull) {
1499  Foo foo;
1500  EXPECT_EQ(0, foo.Bar(NULL));
1501  // Uses Foo's private member Bar().
1502}
1503```
1504
1505Pay special attention when your class is defined in a namespace, as you should
1506define your test fixtures and tests in the same namespace if you want them to
1507be friends of your class. For example, if the code to be tested looks like:
1508
1509```
1510namespace my_namespace {
1511
1512class Foo {
1513  friend class FooTest;
1514  FRIEND_TEST(FooTest, Bar);
1515  FRIEND_TEST(FooTest, Baz);
1516  ...
1517  definition of the class Foo
1518  ...
1519};
1520
1521}  // namespace my_namespace
1522```
1523
1524Your test code should be something like:
1525
1526```
1527namespace my_namespace {
1528class FooTest : public ::testing::Test {
1529 protected:
1530  ...
1531};
1532
1533TEST_F(FooTest, Bar) { ... }
1534TEST_F(FooTest, Baz) { ... }
1535
1536}  // namespace my_namespace
1537```
1538
1539# Catching Failures #
1540
1541If you are building a testing utility on top of Google Test, you'll
1542want to test your utility.  What framework would you use to test it?
1543Google Test, of course.
1544
1545The challenge is to verify that your testing utility reports failures
1546correctly.  In frameworks that report a failure by throwing an
1547exception, you could catch the exception and assert on it.  But Google
1548Test doesn't use exceptions, so how do we test that a piece of code
1549generates an expected failure?
1550
1551`"gtest/gtest-spi.h"` contains some constructs to do this.  After
1552#including this header, you can use
1553
1554| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` |
1555|:--------------------------------------------------|
1556
1557to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure
1558whose message contains the given _substring_, or use
1559
1560| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` |
1561|:-----------------------------------------------------|
1562
1563if you are expecting a non-fatal (e.g. `EXPECT_*`) failure.
1564
1565For technical reasons, there are some caveats:
1566
1567  1. You cannot stream a failure message to either macro.
1568  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object.
1569  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value.
1570
1571_Note:_ Google Test is designed with threads in mind.  Once the
1572synchronization primitives in `"gtest/internal/gtest-port.h"` have
1573been implemented, Google Test will become thread-safe, meaning that
1574you can then use assertions in multiple threads concurrently.  Before
1575
1576that, however, Google Test only supports single-threaded usage.  Once
1577thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()`
1578will capture failures in the current thread only. If _statement_
1579creates new threads, failures in these threads will be ignored.  If
1580you want to capture failures from all threads instead, you should use
1581the following macros:
1582
1583| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1584|:-----------------------------------------------------------------|
1585| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1586
1587# Getting the Current Test's Name #
1588
1589Sometimes a function may need to know the name of the currently running test.
1590For example, you may be using the `SetUp()` method of your test fixture to set
1591the golden file name based on which test is running. The `::testing::TestInfo`
1592class has this information:
1593
1594```
1595namespace testing {
1596
1597class TestInfo {
1598 public:
1599  // Returns the test case name and the test name, respectively.
1600  //
1601  // Do NOT delete or free the return value - it's managed by the
1602  // TestInfo class.
1603  const char* test_case_name() const;
1604  const char* name() const;
1605};
1606
1607}  // namespace testing
1608```
1609
1610
1611> To obtain a `TestInfo` object for the currently running test, call
1612`current_test_info()` on the `UnitTest` singleton object:
1613
1614```
1615// Gets information about the currently running test.
1616// Do NOT delete the returned object - it's managed by the UnitTest class.
1617const ::testing::TestInfo* const test_info =
1618  ::testing::UnitTest::GetInstance()->current_test_info();
1619printf("We are in test %s of test case %s.\n",
1620       test_info->name(), test_info->test_case_name());
1621```
1622
1623`current_test_info()` returns a null pointer if no test is running. In
1624particular, you cannot find the test case name in `TestCaseSetUp()`,
1625`TestCaseTearDown()` (where you know the test case name implicitly), or
1626functions called from them.
1627
1628_Availability:_ Linux, Windows, Mac.
1629
1630# Extending Google Test by Handling Test Events #
1631
1632Google Test provides an <b>event listener API</b> to let you receive
1633notifications about the progress of a test program and test
1634failures. The events you can listen to include the start and end of
1635the test program, a test case, or a test method, among others. You may
1636use this API to augment or replace the standard console output,
1637replace the XML output, or provide a completely different form of
1638output, such as a GUI or a database. You can also use test events as
1639checkpoints to implement a resource leak checker, for example.
1640
1641_Availability:_ Linux, Windows, Mac; since v1.4.0.
1642
1643## Defining Event Listeners ##
1644
1645To define a event listener, you subclass either
1646[testing::TestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#855)
1647or [testing::EmptyTestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#905).
1648The former is an (abstract) interface, where <i>each pure virtual method<br>
1649can be overridden to handle a test event</i> (For example, when a test
1650starts, the `OnTestStart()` method will be called.). The latter provides
1651an empty implementation of all methods in the interface, such that a
1652subclass only needs to override the methods it cares about.
1653
1654When an event is fired, its context is passed to the handler function
1655as an argument. The following argument types are used:
1656  * [UnitTest](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#1007) reflects the state of the entire test program,
1657  * [TestCase](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#689) has information about a test case, which can contain one or more tests,
1658  * [TestInfo](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#599) contains the state of a test, and
1659  * [TestPartResult](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-test-part.h#42) represents the result of a test assertion.
1660
1661An event handler function can examine the argument it receives to find
1662out interesting information about the event and the test program's
1663state.  Here's an example:
1664
1665```
1666  class MinimalistPrinter : public ::testing::EmptyTestEventListener {
1667    // Called before a test starts.
1668    virtual void OnTestStart(const ::testing::TestInfo& test_info) {
1669      printf("*** Test %s.%s starting.\n",
1670             test_info.test_case_name(), test_info.name());
1671    }
1672
1673    // Called after a failed assertion or a SUCCEED() invocation.
1674    virtual void OnTestPartResult(
1675        const ::testing::TestPartResult& test_part_result) {
1676      printf("%s in %s:%d\n%s\n",
1677             test_part_result.failed() ? "*** Failure" : "Success",
1678             test_part_result.file_name(),
1679             test_part_result.line_number(),
1680             test_part_result.summary());
1681    }
1682
1683    // Called after a test ends.
1684    virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
1685      printf("*** Test %s.%s ending.\n",
1686             test_info.test_case_name(), test_info.name());
1687    }
1688  };
1689```
1690
1691## Using Event Listeners ##
1692
1693To use the event listener you have defined, add an instance of it to
1694the Google Test event listener list (represented by class
1695[TestEventListeners](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#929)
1696- note the "s" at the end of the name) in your
1697`main()` function, before calling `RUN_ALL_TESTS()`:
1698```
1699int main(int argc, char** argv) {
1700  ::testing::InitGoogleTest(&argc, argv);
1701  // Gets hold of the event listener list.
1702  ::testing::TestEventListeners& listeners =
1703      ::testing::UnitTest::GetInstance()->listeners();
1704  // Adds a listener to the end.  Google Test takes the ownership.
1705  listeners.Append(new MinimalistPrinter);
1706  return RUN_ALL_TESTS();
1707}
1708```
1709
1710There's only one problem: the default test result printer is still in
1711effect, so its output will mingle with the output from your minimalist
1712printer. To suppress the default printer, just release it from the
1713event listener list and delete it. You can do so by adding one line:
1714```
1715  ...
1716  delete listeners.Release(listeners.default_result_printer());
1717  listeners.Append(new MinimalistPrinter);
1718  return RUN_ALL_TESTS();
1719```
1720
1721Now, sit back and enjoy a completely different output from your
1722tests. For more details, you can read this
1723[sample](http://code.google.com/p/googletest/source/browse/trunk/samples/sample9_unittest.cc).
1724
1725You may append more than one listener to the list. When an `On*Start()`
1726or `OnTestPartResult()` event is fired, the listeners will receive it in
1727the order they appear in the list (since new listeners are added to
1728the end of the list, the default text printer and the default XML
1729generator will receive the event first). An `On*End()` event will be
1730received by the listeners in the _reverse_ order. This allows output by
1731listeners added later to be framed by output from listeners added
1732earlier.
1733
1734## Generating Failures in Listeners ##
1735
1736You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`,
1737`FAIL()`, etc) when processing an event. There are some restrictions:
1738
1739  1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively).
1740  1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure.
1741
1742When you add listeners to the listener list, you should put listeners
1743that handle `OnTestPartResult()` _before_ listeners that can generate
1744failures. This ensures that failures generated by the latter are
1745attributed to the right test by the former.
1746
1747We have a sample of failure-raising listener
1748[here](http://code.google.com/p/googletest/source/browse/trunk/samples/sample10_unittest.cc).
1749
1750# Running Test Programs: Advanced Options #
1751
1752Google Test test programs are ordinary executables. Once built, you can run
1753them directly and affect their behavior via the following environment variables
1754and/or command line flags. For the flags to work, your programs must call
1755`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
1756
1757To see a list of supported flags and their usage, please run your test
1758program with the `--help` flag.  You can also use `-h`, `-?`, or `/?`
1759for short.  This feature is added in version 1.3.0.
1760
1761If an option is specified both by an environment variable and by a
1762flag, the latter takes precedence.  Most of the options can also be
1763set/read in code: to access the value of command line flag
1764`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`.  A common pattern is
1765to set the value of a flag before calling `::testing::InitGoogleTest()`
1766to change the default value of the flag:
1767```
1768int main(int argc, char** argv) {
1769  // Disables elapsed time by default.
1770  ::testing::GTEST_FLAG(print_time) = false;
1771
1772  // This allows the user to override the flag on the command line.
1773  ::testing::InitGoogleTest(&argc, argv);
1774
1775  return RUN_ALL_TESTS();
1776}
1777```
1778
1779## Selecting Tests ##
1780
1781This section shows various options for choosing which tests to run.
1782
1783### Listing Test Names ###
1784
1785Sometimes it is necessary to list the available tests in a program before
1786running them so that a filter may be applied if needed. Including the flag
1787`--gtest_list_tests` overrides all other flags and lists tests in the following
1788format:
1789```
1790TestCase1.
1791  TestName1
1792  TestName2
1793TestCase2.
1794  TestName
1795```
1796
1797None of the tests listed are actually run if the flag is provided. There is no
1798corresponding environment variable for this flag.
1799
1800_Availability:_ Linux, Windows, Mac.
1801
1802### Running a Subset of the Tests ###
1803
1804By default, a Google Test program runs all tests the user has defined.
1805Sometimes, you want to run only a subset of the tests (e.g. for debugging or
1806quickly verifying a change). If you set the `GTEST_FILTER` environment variable
1807or the `--gtest_filter` flag to a filter string, Google Test will only run the
1808tests whose full names (in the form of `TestCaseName.TestName`) match the
1809filter.
1810
1811The format of a filter is a '`:`'-separated list of wildcard patterns (called
1812the positive patterns) optionally followed by a '`-`' and another
1813'`:`'-separated pattern list (called the negative patterns). A test matches the
1814filter if and only if it matches any of the positive patterns but does not
1815match any of the negative patterns.
1816
1817A pattern may contain `'*'` (matches any string) or `'?'` (matches any single
1818character). For convenience, the filter `'*-NegativePatterns'` can be also
1819written as `'-NegativePatterns'`.
1820
1821For example:
1822
1823  * `./foo_test` Has no flag, and thus runs all its tests.
1824  * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value.
1825  * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`.
1826  * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`.
1827  * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.
1828  * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`.
1829
1830_Availability:_ Linux, Windows, Mac.
1831
1832### Temporarily Disabling Tests ###
1833
1834If you have a broken test that you cannot fix right away, you can add the
1835`DISABLED_` prefix to its name. This will exclude it from execution. This is
1836better than commenting out the code or using `#if 0`, as disabled tests are
1837still compiled (and thus won't rot).
1838
1839If you need to disable all tests in a test case, you can either add `DISABLED_`
1840to the front of the name of each test, or alternatively add it to the front of
1841the test case name.
1842
1843For example, the following tests won't be run by Google Test, even though they
1844will still be compiled:
1845
1846```
1847// Tests that Foo does Abc.
1848TEST(FooTest, DISABLED_DoesAbc) { ... }
1849
1850class DISABLED_BarTest : public ::testing::Test { ... };
1851
1852// Tests that Bar does Xyz.
1853TEST_F(DISABLED_BarTest, DoesXyz) { ... }
1854```
1855
1856_Note:_ This feature should only be used for temporary pain-relief. You still
1857have to fix the disabled tests at a later date. As a reminder, Google Test will
1858print a banner warning you if a test program contains any disabled tests.
1859
1860_Tip:_ You can easily count the number of disabled tests you have
1861using `grep`. This number can be used as a metric for improving your
1862test quality.
1863
1864_Availability:_ Linux, Windows, Mac.
1865
1866### Temporarily Enabling Disabled Tests ###
1867
1868To include [disabled tests](#Temporarily_Disabling_Tests.md) in test
1869execution, just invoke the test program with the
1870`--gtest_also_run_disabled_tests` flag or set the
1871`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other
1872than `0`.  You can combine this with the
1873[--gtest\_filter](#Running_a_Subset_of_the_Tests.md) flag to further select
1874which disabled tests to run.
1875
1876_Availability:_ Linux, Windows, Mac; since version 1.3.0.
1877
1878## Repeating the Tests ##
1879
1880Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
1881will fail only 1% of the time, making it rather hard to reproduce the bug under
1882a debugger. This can be a major source of frustration.
1883
1884The `--gtest_repeat` flag allows you to repeat all (or selected) test methods
1885in a program many times. Hopefully, a flaky test will eventually fail and give
1886you a chance to debug. Here's how to use it:
1887
1888| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. |
1889|:---------------------------------|:--------------------------------------------------------|
1890| `$ foo_test --gtest_repeat=-1`   | A negative count means repeating forever.               |
1891| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. |
1892| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. |
1893
1894If your test program contains global set-up/tear-down code registered
1895using `AddGlobalTestEnvironment()`, it will be repeated in each
1896iteration as well, as the flakiness may be in it. You can also specify
1897the repeat count by setting the `GTEST_REPEAT` environment variable.
1898
1899_Availability:_ Linux, Windows, Mac.
1900
1901## Shuffling the Tests ##
1902
1903You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
1904environment variable to `1`) to run the tests in a program in a random
1905order. This helps to reveal bad dependencies between tests.
1906
1907By default, Google Test uses a random seed calculated from the current
1908time. Therefore you'll get a different order every time. The console
1909output includes the random seed value, such that you can reproduce an
1910order-related test failure later. To specify the random seed
1911explicitly, use the `--gtest_random_seed=SEED` flag (or set the
1912`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer
1913between 0 and 99999. The seed value 0 is special: it tells Google Test
1914to do the default behavior of calculating the seed from the current
1915time.
1916
1917If you combine this with `--gtest_repeat=N`, Google Test will pick a
1918different random seed and re-shuffle the tests in each iteration.
1919
1920_Availability:_ Linux, Windows, Mac; since v1.4.0.
1921
1922## Controlling Test Output ##
1923
1924This section teaches how to tweak the way test results are reported.
1925
1926### Colored Terminal Output ###
1927
1928Google Test can use colors in its terminal output to make it easier to spot
1929the separation between tests, and whether tests passed.
1930
1931You can set the GTEST\_COLOR environment variable or set the `--gtest_color`
1932command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
1933disable colors, or let Google Test decide. When the value is `auto`, Google
1934Test will use colors if and only if the output goes to a terminal and (on
1935non-Windows platforms) the `TERM` environment variable is set to `xterm` or
1936`xterm-color`.
1937
1938_Availability:_ Linux, Windows, Mac.
1939
1940### Suppressing the Elapsed Time ###
1941
1942By default, Google Test prints the time it takes to run each test.  To
1943suppress that, run the test program with the `--gtest_print_time=0`
1944command line flag.  Setting the `GTEST_PRINT_TIME` environment
1945variable to `0` has the same effect.
1946
1947_Availability:_ Linux, Windows, Mac.  (In Google Test 1.3.0 and lower,
1948the default behavior is that the elapsed time is **not** printed.)
1949
1950### Generating an XML Report ###
1951
1952Google Test can emit a detailed XML report to a file in addition to its normal
1953textual output. The report contains the duration of each test, and thus can
1954help you identify slow tests.
1955
1956To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
1957`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will
1958create the file at the given location. You can also just use the string
1959`"xml"`, in which case the output can be found in the `test_detail.xml` file in
1960the current directory.
1961
1962If you specify a directory (for example, `"xml:output/directory/"` on Linux or
1963`"xml:output\directory\"` on Windows), Google Test will create the XML file in
1964that directory, named after the test executable (e.g. `foo_test.xml` for test
1965program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
1966over from a previous run), Google Test will pick a different name (e.g.
1967`foo_test_1.xml`) to avoid overwriting it.
1968
1969The report uses the format described here.  It is based on the
1970`junitreport` Ant task and can be parsed by popular continuous build
1971systems like [Hudson](https://hudson.dev.java.net/). Since that format
1972was originally intended for Java, a little interpretation is required
1973to make it apply to Google Test tests, as shown here:
1974
1975```
1976<testsuites name="AllTests" ...>
1977  <testsuite name="test_case_name" ...>
1978    <testcase name="test_name" ...>
1979      <failure message="..."/>
1980      <failure message="..."/>
1981      <failure message="..."/>
1982    </testcase>
1983  </testsuite>
1984</testsuites>
1985```
1986
1987  * The root `<testsuites>` element corresponds to the entire test program.
1988  * `<testsuite>` elements correspond to Google Test test cases.
1989  * `<testcase>` elements correspond to Google Test test functions.
1990
1991For instance, the following program
1992
1993```
1994TEST(MathTest, Addition) { ... }
1995TEST(MathTest, Subtraction) { ... }
1996TEST(LogicTest, NonContradiction) { ... }
1997```
1998
1999could generate this report:
2000
2001```
2002<?xml version="1.0" encoding="UTF-8"?>
2003<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests">
2004  <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15">
2005    <testcase name="Addition" status="run" time="7" classname="">
2006      <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type=""/>
2007      <failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type=""/>
2008    </testcase>
2009    <testcase name="Subtraction" status="run" time="5" classname="">
2010    </testcase>
2011  </testsuite>
2012  <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5">
2013    <testcase name="NonContradiction" status="run" time="5" classname="">
2014    </testcase>
2015  </testsuite>
2016</testsuites>
2017```
2018
2019Things to note:
2020
2021  * The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed.
2022  * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds.
2023  * Each `<failure>` element corresponds to a single failed Google Test assertion.
2024  * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts.
2025
2026_Availability:_ Linux, Windows, Mac.
2027
2028## Controlling How Failures Are Reported ##
2029
2030### Turning Assertion Failures into Break-Points ###
2031
2032When running test programs under a debugger, it's very convenient if the
2033debugger can catch an assertion failure and automatically drop into interactive
2034mode. Google Test's _break-on-failure_ mode supports this behavior.
2035
2036To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
2037other than `0` . Alternatively, you can use the `--gtest_break_on_failure`
2038command line flag.
2039
2040_Availability:_ Linux, Windows, Mac.
2041
2042### Disabling Catching Test-Thrown Exceptions ###
2043
2044Google Test can be used either with or without exceptions enabled.  If
2045a test throws a C++ exception or (on Windows) a structured exception
2046(SEH), by default Google Test catches it, reports it as a test
2047failure, and continues with the next test method.  This maximizes the
2048coverage of a test run.  Also, on Windows an uncaught exception will
2049cause a pop-up window, so catching the exceptions allows you to run
2050the tests automatically.
2051
2052When debugging the test failures, however, you may instead want the
2053exceptions to be handled by the debugger, such that you can examine
2054the call stack when an exception is thrown.  To achieve that, set the
2055`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the
2056`--gtest_catch_exceptions=0` flag when running the tests.
2057
2058**Availability**: Linux, Windows, Mac.
2059
2060### Letting Another Testing Framework Drive ###
2061
2062If you work on a project that has already been using another testing
2063framework and is not ready to completely switch to Google Test yet,
2064you can get much of Google Test's benefit by using its assertions in
2065your existing tests.  Just change your `main()` function to look
2066like:
2067
2068```
2069#include "gtest/gtest.h"
2070
2071int main(int argc, char** argv) {
2072  ::testing::GTEST_FLAG(throw_on_failure) = true;
2073  // Important: Google Test must be initialized.
2074  ::testing::InitGoogleTest(&argc, argv);
2075
2076  ... whatever your existing testing framework requires ...
2077}
2078```
2079
2080With that, you can use Google Test assertions in addition to the
2081native assertions your testing framework provides, for example:
2082
2083```
2084void TestFooDoesBar() {
2085  Foo foo;
2086  EXPECT_LE(foo.Bar(1), 100);     // A Google Test assertion.
2087  CPPUNIT_ASSERT(foo.IsEmpty());  // A native assertion.
2088}
2089```
2090
2091If a Google Test assertion fails, it will print an error message and
2092throw an exception, which will be treated as a failure by your host
2093testing framework.  If you compile your code with exceptions disabled,
2094a failed Google Test assertion will instead exit your program with a
2095non-zero code, which will also signal a test failure to your test
2096runner.
2097
2098If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in
2099your `main()`, you can alternatively enable this feature by specifying
2100the `--gtest_throw_on_failure` flag on the command-line or setting the
2101`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value.
2102
2103_Availability:_ Linux, Windows, Mac; since v1.3.0.
2104
2105## Distributing Test Functions to Multiple Machines ##
2106
2107If you have more than one machine you can use to run a test program,
2108you might want to run the test functions in parallel and get the
2109result faster.  We call this technique _sharding_, where each machine
2110is called a _shard_.
2111
2112Google Test is compatible with test sharding.  To take advantage of
2113this feature, your test runner (not part of Google Test) needs to do
2114the following:
2115
2116  1. Allocate a number of machines (shards) to run the tests.
2117  1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards.  It must be the same for all shards.
2118  1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard.  Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`.
2119  1. Run the same test program on all shards.  When Google Test sees the above two environment variables, it will select a subset of the test functions to run.  Across all shards, each test function in the program will be run exactly once.
2120  1. Wait for all shards to finish, then collect and report the results.
2121
2122Your project may have tests that were written without Google Test and
2123thus don't understand this protocol.  In order for your test runner to
2124figure out which test supports sharding, it can set the environment
2125variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path.  If a
2126test program supports sharding, it will create this file to
2127acknowledge the fact (the actual contents of the file are not
2128important at this time; although we may stick some useful information
2129in it in the future.); otherwise it will not create it.
2130
2131Here's an example to make it clear.  Suppose you have a test program
2132`foo_test` that contains the following 5 test functions:
2133```
2134TEST(A, V)
2135TEST(A, W)
2136TEST(B, X)
2137TEST(B, Y)
2138TEST(B, Z)
2139```
2140and you have 3 machines at your disposal.  To run the test functions in
2141parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and
2142set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively.
2143Then you would run the same `foo_test` on each machine.
2144
2145Google Test reserves the right to change how the work is distributed
2146across the shards, but here's one possible scenario:
2147
2148  * Machine #0 runs `A.V` and `B.X`.
2149  * Machine #1 runs `A.W` and `B.Y`.
2150  * Machine #2 runs `B.Z`.
2151
2152_Availability:_ Linux, Windows, Mac; since version 1.3.0.
2153
2154# Fusing Google Test Source Files #
2155
2156Google Test's implementation consists of ~30 files (excluding its own
2157tests).  Sometimes you may want them to be packaged up in two files (a
2158`.h` and a `.cc`) instead, such that you can easily copy them to a new
2159machine and start hacking there.  For this we provide an experimental
2160Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0).
2161Assuming you have Python 2.4 or above installed on your machine, just
2162go to that directory and run
2163```
2164python fuse_gtest_files.py OUTPUT_DIR
2165```
2166
2167and you should see an `OUTPUT_DIR` directory being created with files
2168`gtest/gtest.h` and `gtest/gtest-all.cc` in it.  These files contain
2169everything you need to use Google Test.  Just copy them to anywhere
2170you want and you are ready to write tests.  You can use the
2171[scripts/test/Makefile](http://code.google.com/p/googletest/source/browse/trunk/scripts/test/Makefile)
2172file as an example on how to compile your tests against them.
2173
2174# Where to Go from Here #
2175
2176Congratulations! You've now learned more advanced Google Test tools and are
2177ready to tackle more complex testing tasks. If you want to dive even deeper, you
2178can read the [Frequently-Asked Questions](V1_6_FAQ.md).
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_6_Documentation.md
r0r249096
1This page lists all documentation wiki pages for Google Test **1.6**
2-- **if you use a released version of Google Test, please read the
3documentation for that specific version instead.**
4
5  * [Primer](V1_6_Primer.md) -- start here if you are new to Google Test.
6  * [Samples](V1_6_Samples.md) -- learn from examples.
7  * [AdvancedGuide](V1_6_AdvancedGuide.md) -- learn more about Google Test.
8  * [XcodeGuide](V1_6_XcodeGuide.md) -- how to use Google Test in Xcode on Mac.
9  * [Frequently-Asked Questions](V1_6_FAQ.md) -- check here before asking a question on the mailing list.
10
11To contribute code to Google Test, read:
12
13  * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch.
14  * [PumpManual](V1_6_PumpManual.md) -- how we generate some of Google Test's source files.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_6_FAQ.md
r0r249096
1
2
3If you cannot find the answer to your question here, and you have read
4[Primer](V1_6_Primer.md) and [AdvancedGuide](V1_6_AdvancedGuide.md), send it to
5googletestframework@googlegroups.com.
6
7## Why should I use Google Test instead of my favorite C++ testing framework? ##
8
9First, let us say clearly that we don't want to get into the debate of
10which C++ testing framework is **the best**.  There exist many fine
11frameworks for writing C++ tests, and we have tremendous respect for
12the developers and users of them.  We don't think there is (or will
13be) a single best framework - you have to pick the right tool for the
14particular task you are tackling.
15
16We created Google Test because we couldn't find the right combination
17of features and conveniences in an existing framework to satisfy _our_
18needs.  The following is a list of things that _we_ like about Google
19Test.  We don't claim them to be unique to Google Test - rather, the
20combination of them makes Google Test the choice for us.  We hope this
21list can help you decide whether it is for you too.
22
23  * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc.  As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems.
24  * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle.
25  * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`.  It doesn't require a new set of macros or special functions.
26  * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them.
27  * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions.
28  * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop.
29  * You can decide which tests to run using name patterns.  This saves time when you want to quickly reproduce a test failure.
30  * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson.
31  * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Global_Set-Up_and_Tear-Down) and tests parameterized by [values](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Value_Parameterized_Tests) or [types](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Typed_Tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself.  In particular, you can:
32    * expand your testing vocabulary by defining [custom predicates](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Predicate_Assertions_for_Better_Error_Messages),
33    * teach Google Test how to [print your types](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values),
34    * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Catching_Failures), and
35    * reflect on the test cases or change the test output format by intercepting the [test events](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events).
36
37## I'm getting warnings when compiling Google Test.  Would you fix them? ##
38
39We strive to minimize compiler warnings Google Test generates.  Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS.
40
41Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment:
42
43  * You may be using a different compiler as we use, or a different version of the same compiler.  We cannot possibly test for all compilers.
44  * You may be compiling on a different platform as we do.
45  * Your project may be using different compiler flags as we do.
46
47It is not always possible to make Google Test warning-free for everyone.  Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex.
48
49If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers.  That'll suppress warnings from Google Test headers.
50
51## Why should not test case names and test names contain underscore? ##
52
53Underscore (`_`) is special, as C++ reserves the following to be used by
54the compiler and the standard library:
55
56  1. any identifier that starts with an `_` followed by an upper-case letter, and
57  1. any identifier that containers two consecutive underscores (i.e. `__`) _anywhere_ in its name.
58
59User code is _prohibited_ from using such identifiers.
60
61Now let's look at what this means for `TEST` and `TEST_F`.
62
63Currently `TEST(TestCaseName, TestName)` generates a class named
64`TestCaseName_TestName_Test`.  What happens if `TestCaseName` or `TestName`
65contains `_`?
66
67  1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid.
68  1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid.
69  1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid.
70  1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid.
71
72So clearly `TestCaseName` and `TestName` cannot start or end with `_`
73(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't
74followed by an upper-case letter.  But that's getting complicated.  So
75for simplicity we just say that it cannot start with `_`.).
76
77It may seem fine for `TestCaseName` and `TestName` to contain `_` in the
78middle.  However, consider this:
79```
80TEST(Time, Flies_Like_An_Arrow) { ... }
81TEST(Time_Flies, Like_An_Arrow) { ... }
82```
83
84Now, the two `TEST`s will both generate the same class
85(`Time_Files_Like_An_Arrow_Test`).  That's not good.
86
87So for simplicity, we just ask the users to avoid `_` in `TestCaseName`
88and `TestName`.  The rule is more constraining than necessary, but it's
89simple and easy to remember.  It also gives Google Test some wiggle
90room in case its implementation needs to change in the future.
91
92If you violate the rule, there may not be immediately consequences,
93but your test may (just may) break with a new compiler (or a new
94version of the compiler you are using) or with a new version of Google
95Test.  Therefore it's best to follow the rule.
96
97## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ##
98
99In the early days, we said that you could install
100compiled Google Test libraries on `*`nix systems using `make install`.
101Then every user of your machine can write tests without
102recompiling Google Test.
103
104This seemed like a good idea, but it has a
105got-cha: every user needs to compile his tests using the _same_ compiler
106flags used to compile the installed Google Test libraries; otherwise
107he may run into undefined behaviors (i.e. the tests can behave
108strangely and may even crash for no obvious reasons).
109
110Why?  Because C++ has this thing called the One-Definition Rule: if
111two C++ source files contain different definitions of the same
112class/function/variable, and you link them together, you violate the
113rule.  The linker may or may not catch the error (in many cases it's
114not required by the C++ standard to catch the violation).  If it
115doesn't, you get strange run-time behaviors that are unexpected and
116hard to debug.
117
118If you compile Google Test and your test code using different compiler
119flags, they may see different definitions of the same
120class/function/variable (e.g. due to the use of `#if` in Google Test).
121Therefore, for your sanity, we recommend to avoid installing pre-compiled
122Google Test libraries.  Instead, each project should compile
123Google Test itself such that it can be sure that the same flags are
124used for both Google Test and the tests.
125
126## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ##
127
128(Answered by Trevor Robinson)
129
130Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or
131`msvc\gtest.sln`. Go through the migration wizard to migrate the
132solution and project files to Visual Studio 2008. Select
133`Configuration Manager...` from the `Build` menu. Select `<New...>` from
134the `Active solution platform` dropdown.  Select `x64` from the new
135platform dropdown, leave `Copy settings from` set to `Win32` and
136`Create new project platforms` checked, then click `OK`. You now have
137`Win32` and `x64` platform configurations, selectable from the
138`Standard` toolbar, which allow you to toggle between building 32-bit or
13964-bit binaries (or both at once using Batch Build).
140
141In order to prevent build output files from overwriting one another,
142you'll need to change the `Intermediate Directory` settings for the
143newly created platform configuration across all the projects. To do
144this, multi-select (e.g. using shift-click) all projects (but not the
145solution) in the `Solution Explorer`. Right-click one of them and
146select `Properties`. In the left pane, select `Configuration Properties`,
147and from the `Configuration` dropdown, select `All Configurations`.
148Make sure the selected platform is `x64`. For the
149`Intermediate Directory` setting, change the value from
150`$(PlatformName)\$(ConfigurationName)` to
151`$(OutDir)\$(ProjectName)`. Click `OK` and then build the
152solution. When the build is complete, the 64-bit binaries will be in
153the `msvc\x64\Debug` directory.
154
155## Can I use Google Test on MinGW? ##
156
157We haven't tested this ourselves, but Per Abrahamsen reported that he
158was able to compile and install Google Test successfully when using
159MinGW from Cygwin.  You'll need to configure it with:
160
161`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"`
162
163You should be able to replace the `-mno-cygwin` option with direct links
164to the real MinGW binaries, but we haven't tried that.
165
166Caveats:
167
168  * There are many warnings when compiling.
169  * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW.
170
171We also have reports on successful cross compilation of Google Test
172MinGW binaries on Linux using
173[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows)
174on the WxWidgets site.
175
176Please contact `googletestframework@googlegroups.com` if you are
177interested in improving the support for MinGW.
178
179## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ##
180
181Due to some peculiarity of C++, it requires some non-trivial template
182meta programming tricks to support using `NULL` as an argument of the
183`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where
184it's most needed (otherwise we make the implementation of Google Test
185harder to maintain and more error-prone than necessary).
186
187The `EXPECT_EQ()` macro takes the _expected_ value as its first
188argument and the _actual_ value as the second. It's reasonable that
189someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this
190indeed was requested several times. Therefore we implemented it.
191
192The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the
193assertion fails, you already know that `ptr` must be `NULL`, so it
194doesn't add any information to print ptr in this case. That means
195`EXPECT_TRUE(ptr ! NULL)` works just as well.
196
197If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll
198have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`,
199we don't have a convention on the order of the two arguments for
200`EXPECT_NE`. This means using the template meta programming tricks
201twice in the implementation, making it even harder to understand and
202maintain. We believe the benefit doesn't justify the cost.
203
204Finally, with the growth of Google Mock's [matcher](http://code.google.com/p/googlemock/wiki/CookBook#Using_Matchers_in_Google_Test_Assertions) library, we are
205encouraging people to use the unified `EXPECT_THAT(value, matcher)`
206syntax more often in tests. One significant advantage of the matcher
207approach is that matchers can be easily combined to form new matchers,
208while the `EXPECT_NE`, etc, macros cannot be easily
209combined. Therefore we want to invest more in the matchers than in the
210`EXPECT_XX()` macros.
211
212## Does Google Test support running tests in parallel? ##
213
214Test runners tend to be tightly coupled with the build/test
215environment, and Google Test doesn't try to solve the problem of
216running tests in parallel.  Instead, we tried to make Google Test work
217nicely with test runners.  For example, Google Test's XML report
218contains the time spent on each test, and its `gtest_list_tests` and
219`gtest_filter` flags can be used for splitting the execution of test
220methods into multiple processes.  These functionalities can help the
221test runner run the tests in parallel.
222
223## Why don't Google Test run the tests in different threads to speed things up? ##
224
225It's difficult to write thread-safe code.  Most tests are not written
226with thread-safety in mind, and thus may not work correctly in a
227multi-threaded setting.
228
229If you think about it, it's already hard to make your code work when
230you know what other threads are doing.  It's much harder, and
231sometimes even impossible, to make your code work when you don't know
232what other threads are doing (remember that test methods can be added,
233deleted, or modified after your test was written).  If you want to run
234the tests in parallel, you'd better run them in different processes.
235
236## Why aren't Google Test assertions implemented using exceptions? ##
237
238Our original motivation was to be able to use Google Test in projects
239that disable exceptions.  Later we realized some additional benefits
240of this approach:
241
242  1. Throwing in a destructor is undefined behavior in C++.  Not using exceptions means Google Test's assertions are safe to use in destructors.
243  1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing.
244  1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code:
245```
246try { ... ASSERT_TRUE(...) ... }
247catch (...) { ... }
248```
249The above code will pass even if the `ASSERT_TRUE` throws.  While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test.
250
251The downside of not using exceptions is that `ASSERT_*` (implemented
252using `return`) will only abort the current function, not the current
253`TEST`.
254
255## Why do we use two different macros for tests with and without fixtures? ##
256
257Unfortunately, C++'s macro system doesn't allow us to use the same
258macro for both cases.  One possibility is to provide only one macro
259for tests with fixtures, and require the user to define an empty
260fixture sometimes:
261
262```
263class FooTest : public ::testing::Test {};
264
265TEST_F(FooTest, DoesThis) { ... }
266```
267or
268```
269typedef ::testing::Test FooTest;
270
271TEST_F(FooTest, DoesThat) { ... }
272```
273
274Yet, many people think this is one line too many. :-) Our goal was to
275make it really easy to write tests, so we tried to make simple tests
276trivial to create.  That means using a separate macro for such tests.
277
278We think neither approach is ideal, yet either of them is reasonable.
279In the end, it probably doesn't matter much either way.
280
281## Why don't we use structs as test fixtures? ##
282
283We like to use structs only when representing passive data.  This
284distinction between structs and classes is good for documenting the
285intent of the code's author.  Since test fixtures have logic like
286`SetUp()` and `TearDown()`, they are better defined as classes.
287
288## Why are death tests implemented as assertions instead of using a test runner? ##
289
290Our goal was to make death tests as convenient for a user as C++
291possibly allows.  In particular:
292
293  * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect.  The death test would be written in C++, while the runner spec may or may not be.  A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative.
294  * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn.
295  * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will.  You are not limited to one death test per test method. For example, you can write something like:
296```
297    if (FooCondition()) {
298      ASSERT_DEATH(Bar(), "blah");
299    } else {
300      ASSERT_EQ(5, Bar());
301    }
302```
303If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users.  The fewer artificial limitations the better.
304  * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information.  For example,
305```
306    const int count = GetCount();  // Only known at run time.
307    for (int i = 1; i <= count; i++) {
308      ASSERT_DEATH({
309        double* buffer = new double[i];
310        ... initializes buffer ...
311        Foo(buffer, i)
312      }, "blah blah");
313    }
314```
315The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility.
316
317Another interesting thing about `ASSERT_DEATH` is that it calls `fork()`
318to create a child process to run the death test.  This is lightening
319fast, as `fork()` uses copy-on-write pages and incurs almost zero
320overhead, and the child process starts from the user-supplied
321statement directly, skipping all global and local initialization and
322any code leading to the given statement.  If you launch the child
323process from scratch, it can take seconds just to load everything and
324start running if the test links to many libraries dynamically.
325
326## My death test modifies some state, but the change seems lost after the death test finishes. Why? ##
327
328Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
329expected crash won't kill the test program (i.e. the parent process). As a
330result, any in-memory side effects they incur are observable in their
331respective sub-processes, but not in the parent process. You can think of them
332as running in a parallel universe, more or less.
333
334## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ##
335
336If your class has a static data member:
337
338```
339// foo.h
340class Foo {
341  ...
342  static const int kBar = 100;
343};
344```
345
346You also need to define it _outside_ of the class body in `foo.cc`:
347
348```
349const int Foo::kBar;  // No initializer here.
350```
351
352Otherwise your code is **invalid C++**, and may break in unexpected ways. In
353particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc)
354will generate an "undefined reference" linker error.
355
356## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ##
357
358Google Test doesn't yet have good support for this kind of tests, or
359data-driven tests in general. We hope to be able to make improvements in this
360area soon.
361
362## Can I derive a test fixture from another? ##
363
364Yes.
365
366Each test fixture has a corresponding and same named test case. This means only
367one test case can use a particular fixture. Sometimes, however, multiple test
368cases may want to use the same or slightly different fixtures. For example, you
369may want to make sure that all of a GUI library's test cases don't leak
370important system resources like fonts and brushes.
371
372In Google Test, you share a fixture among test cases by putting the shared
373logic in a base test fixture, then deriving from that base a separate fixture
374for each test case that wants to use this common logic. You then use `TEST_F()`
375to write tests using each derived fixture.
376
377Typically, your code looks like this:
378
379```
380// Defines a base test fixture.
381class BaseTest : public ::testing::Test {
382  protected:
383   ...
384};
385
386// Derives a fixture FooTest from BaseTest.
387class FooTest : public BaseTest {
388  protected:
389    virtual void SetUp() {
390      BaseTest::SetUp();  // Sets up the base fixture first.
391      ... additional set-up work ...
392    }
393    virtual void TearDown() {
394      ... clean-up work for FooTest ...
395      BaseTest::TearDown();  // Remember to tear down the base fixture
396                             // after cleaning up FooTest!
397    }
398    ... functions and variables for FooTest ...
399};
400
401// Tests that use the fixture FooTest.
402TEST_F(FooTest, Bar) { ... }
403TEST_F(FooTest, Baz) { ... }
404
405... additional fixtures derived from BaseTest ...
406```
407
408If necessary, you can continue to derive test fixtures from a derived fixture.
409Google Test has no limit on how deep the hierarchy can be.
410
411For a complete example using derived test fixtures, see
412[sample5](http://code.google.com/p/googletest/source/browse/trunk/samples/sample5_unittest.cc).
413
414## My compiler complains "void value not ignored as it ought to be." What does this mean? ##
415
416You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
417`ASSERT_*()` can only be used in `void` functions.
418
419## My death test hangs (or seg-faults). How do I fix it? ##
420
421In Google Test, death tests are run in a child process and the way they work is
422delicate. To write death tests you really need to understand how they work.
423Please make sure you have read this.
424
425In particular, death tests don't like having multiple threads in the parent
426process. So the first thing you can try is to eliminate creating threads
427outside of `EXPECT_DEATH()`.
428
429Sometimes this is impossible as some library you must use may be creating
430threads before `main()` is even reached. In this case, you can try to minimize
431the chance of conflicts by either moving as many activities as possible inside
432`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
433leaving as few things as possible in it. Also, you can try to set the death
434test style to `"threadsafe"`, which is safer but slower, and see if it helps.
435
436If you go with thread-safe death tests, remember that they rerun the test
437program from the beginning in the child process. Therefore make sure your
438program can run side-by-side with itself and is deterministic.
439
440In the end, this boils down to good concurrent programming. You have to make
441sure that there is no race conditions or dead locks in your program. No silver
442bullet - sorry!
443
444## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ##
445
446The first thing to remember is that Google Test does not reuse the
447same test fixture object across multiple tests. For each `TEST_F`,
448Google Test will create a fresh test fixture object, _immediately_
449call `SetUp()`, run the test, call `TearDown()`, and then
450_immediately_ delete the test fixture object. Therefore, there is no
451need to write a `SetUp()` or `TearDown()` function if the constructor
452or destructor already does the job.
453
454You may still want to use `SetUp()/TearDown()` in the following cases:
455  * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions.
456  * The Google Test team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use Google Test assertions in a destructor if your code could run on such a platform.
457  * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`.
458
459## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
460
461If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
462overloaded or a template, the compiler will have trouble figuring out which
463overloaded version it should use. `ASSERT_PRED_FORMAT*` and
464`EXPECT_PRED_FORMAT*` don't have this problem.
465
466If you see this error, you might want to switch to
467`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
468message. If, however, that is not an option, you can resolve the problem by
469explicitly telling the compiler which version to pick.
470
471For example, suppose you have
472
473```
474bool IsPositive(int n) {
475  return n > 0;
476}
477bool IsPositive(double x) {
478  return x > 0;
479}
480```
481
482you will get a compiler error if you write
483
484```
485EXPECT_PRED1(IsPositive, 5);
486```
487
488However, this will work:
489
490```
491EXPECT_PRED1(*static_cast<bool (*)(int)>*(IsPositive), 5);
492```
493
494(The stuff inside the angled brackets for the `static_cast` operator is the
495type of the function pointer for the `int`-version of `IsPositive()`.)
496
497As another example, when you have a template function
498
499```
500template <typename T>
501bool IsNegative(T x) {
502  return x < 0;
503}
504```
505
506you can use it in a predicate assertion like this:
507
508```
509ASSERT_PRED1(IsNegative*<int>*, -5);
510```
511
512Things are more interesting if your template has more than one parameters. The
513following won't compile:
514
515```
516ASSERT_PRED2(*GreaterThan<int, int>*, 5, 0);
517```
518
519
520as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments,
521which is one more than expected. The workaround is to wrap the predicate
522function in parentheses:
523
524```
525ASSERT_PRED2(*(GreaterThan<int, int>)*, 5, 0);
526```
527
528
529## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ##
530
531Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
532instead of
533
534```
535return RUN_ALL_TESTS();
536```
537
538they write
539
540```
541RUN_ALL_TESTS();
542```
543
544This is wrong and dangerous. A test runner needs to see the return value of
545`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()`
546function ignores it, your test will be considered successful even if it has a
547Google Test assertion failure. Very bad.
548
549To help the users avoid this dangerous bug, the implementation of
550`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is
551ignored. If you see this warning, the fix is simple: just make sure its value
552is used as the return value of `main()`.
553
554## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ##
555
556Due to a peculiarity of C++, in order to support the syntax for streaming
557messages to an `ASSERT_*`, e.g.
558
559```
560ASSERT_EQ(1, Foo()) << "blah blah" << foo;
561```
562
563we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
564`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
565content of your constructor/destructor to a private void member function, or
566switch to `EXPECT_*()` if that works. This section in the user's guide explains
567it.
568
569## My set-up function is not called. Why? ##
570
571C++ is case-sensitive. It should be spelled as `SetUp()`.  Did you
572spell it as `Setup()`?
573
574Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
575wonder why it's never called.
576
577## How do I jump to the line of a failure in Emacs directly? ##
578
579Google Test's failure message format is understood by Emacs and many other
580IDEs, like acme and XCode. If a Google Test message is in a compilation buffer
581in Emacs, then it's clickable. You can now hit `enter` on a message to jump to
582the corresponding source code, or use `C-x `` to jump to the next failure.
583
584## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ##
585
586You don't have to. Instead of
587
588```
589class FooTest : public BaseTest {};
590
591TEST_F(FooTest, Abc) { ... }
592TEST_F(FooTest, Def) { ... }
593
594class BarTest : public BaseTest {};
595
596TEST_F(BarTest, Abc) { ... }
597TEST_F(BarTest, Def) { ... }
598```
599
600you can simply `typedef` the test fixtures:
601```
602typedef BaseTest FooTest;
603
604TEST_F(FooTest, Abc) { ... }
605TEST_F(FooTest, Def) { ... }
606
607typedef BaseTest BarTest;
608
609TEST_F(BarTest, Abc) { ... }
610TEST_F(BarTest, Def) { ... }
611```
612
613## The Google Test output is buried in a whole bunch of log messages. What do I do? ##
614
615The Google Test output is meant to be a concise and human-friendly report. If
616your test generates textual output itself, it will mix with the Google Test
617output, making it hard to read. However, there is an easy solution to this
618problem.
619
620Since most log messages go to stderr, we decided to let Google Test output go
621to stdout. This way, you can easily separate the two using redirection. For
622example:
623```
624./my_test > googletest_output.txt
625```
626
627## Why should I prefer test fixtures over global variables? ##
628
629There are several good reasons:
630  1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other.
631  1. Global variables pollute the global namespace.
632  1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common.
633
634## How do I test private class members without writing FRIEND\_TEST()s? ##
635
636You should try to write testable code, which means classes should be easily
637tested from their public interface. One way to achieve this is the Pimpl idiom:
638you move all private members of a class into a helper class, and make all
639members of the helper class public.
640
641You have several other options that don't require using `FRIEND_TEST`:
642  * Write the tests as members of the fixture class:
643```
644class Foo {
645  friend class FooTest;
646  ...
647};
648
649class FooTest : public ::testing::Test {
650 protected:
651  ...
652  void Test1() {...} // This accesses private members of class Foo.
653  void Test2() {...} // So does this one.
654};
655
656TEST_F(FooTest, Test1) {
657  Test1();
658}
659
660TEST_F(FooTest, Test2) {
661  Test2();
662}
663```
664  * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests:
665```
666class Foo {
667  friend class FooTest;
668  ...
669};
670
671class FooTest : public ::testing::Test {
672 protected:
673  ...
674  T1 get_private_member1(Foo* obj) {
675    return obj->private_member1_;
676  }
677};
678
679TEST_F(FooTest, Test1) {
680  ...
681  get_private_member1(x)
682  ...
683}
684```
685  * If the methods are declared **protected**, you can change their access level in a test-only subclass:
686```
687class YourClass {
688  ...
689 protected: // protected access for testability.
690  int DoSomethingReturningInt();
691  ...
692};
693
694// in the your_class_test.cc file:
695class TestableYourClass : public YourClass {
696  ...
697 public: using YourClass::DoSomethingReturningInt; // changes access rights
698  ...
699};
700
701TEST_F(YourClassTest, DoSomethingTest) {
702  TestableYourClass obj;
703  assertEquals(expected_value, obj.DoSomethingReturningInt());
704}
705```
706
707## How do I test private class static members without writing FRIEND\_TEST()s? ##
708
709We find private static methods clutter the header file.  They are
710implementation details and ideally should be kept out of a .h. So often I make
711them free functions instead.
712
713Instead of:
714```
715// foo.h
716class Foo {
717  ...
718 private:
719  static bool Func(int n);
720};
721
722// foo.cc
723bool Foo::Func(int n) { ... }
724
725// foo_test.cc
726EXPECT_TRUE(Foo::Func(12345));
727```
728
729You probably should better write:
730```
731// foo.h
732class Foo {
733  ...
734};
735
736// foo.cc
737namespace internal {
738  bool Func(int n) { ... }
739}
740
741// foo_test.cc
742namespace internal {
743  bool Func(int n);
744}
745
746EXPECT_TRUE(internal::Func(12345));
747```
748
749## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ##
750
751No. You can use a feature called [value-parameterized tests](V1_6_AdvancedGuide#Value_Parameterized_Tests.md) which
752lets you repeat your tests with different parameters, without defining it more than once.
753
754## How do I test a file that defines main()? ##
755
756To test a `foo.cc` file, you need to compile and link it into your unit test
757program. However, when the file contains a definition for the `main()`
758function, it will clash with the `main()` of your unit test, and will result in
759a build error.
760
761The right solution is to split it into three files:
762  1. `foo.h` which contains the declarations,
763  1. `foo.cc` which contains the definitions except `main()`, and
764  1. `foo_main.cc` which contains nothing but the definition of `main()`.
765
766Then `foo.cc` can be easily tested.
767
768If you are adding tests to an existing file and don't want an intrusive change
769like this, there is a hack: just include the entire `foo.cc` file in your unit
770test. For example:
771```
772// File foo_unittest.cc
773
774// The headers section
775...
776
777// Renames main() in foo.cc to make room for the unit test main()
778#define main FooMain
779
780#include "a/b/foo.cc"
781
782// The tests start here.
783...
784```
785
786
787However, please remember this is a hack and should only be used as the last
788resort.
789
790## What can the statement argument in ASSERT\_DEATH() be? ##
791
792`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used
793wherever `_statement_` is valid. So basically `_statement_` can be any C++
794statement that makes sense in the current context. In particular, it can
795reference global and/or local variables, and can be:
796  * a simple function call (often the case),
797  * a complex expression, or
798  * a compound statement.
799
800> Some examples are shown here:
801```
802// A death test can be a simple function call.
803TEST(MyDeathTest, FunctionCall) {
804  ASSERT_DEATH(Xyz(5), "Xyz failed");
805}
806
807// Or a complex expression that references variables and functions.
808TEST(MyDeathTest, ComplexExpression) {
809  const bool c = Condition();
810  ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
811               "(Func1|Method) failed");
812}
813
814// Death assertions can be used any where in a function. In
815// particular, they can be inside a loop.
816TEST(MyDeathTest, InsideLoop) {
817  // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
818  for (int i = 0; i < 5; i++) {
819    EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
820                   ::testing::Message() << "where i is " << i);
821  }
822}
823
824// A death assertion can contain a compound statement.
825TEST(MyDeathTest, CompoundStatement) {
826  // Verifies that at lease one of Bar(0), Bar(1), ..., and
827  // Bar(4) dies.
828  ASSERT_DEATH({
829    for (int i = 0; i < 5; i++) {
830      Bar(i);
831    }
832  },
833  "Bar has \\d+ errors");}
834```
835
836`googletest_unittest.cc` contains more examples if you are interested.
837
838## What syntax does the regular expression in ASSERT\_DEATH use? ##
839
840On POSIX systems, Google Test uses the POSIX Extended regular
841expression syntax
842(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
843On Windows, it uses a limited variant of regular expression
844syntax. For more details, see the
845[regular expression syntax](V1_6_AdvancedGuide#Regular_Expression_Syntax.md).
846
847## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ##
848
849Google Test needs to be able to create objects of your test fixture class, so
850it must have a default constructor. Normally the compiler will define one for
851you. However, there are cases where you have to define your own:
852  * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty.
853  * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.)
854
855## Why does ASSERT\_DEATH complain about previous threads that were already joined? ##
856
857With the Linux pthread library, there is no turning back once you cross the
858line from single thread to multiple threads. The first time you create a
859thread, a manager thread is created in addition, so you get 3, not 2, threads.
860Later when the thread you create joins the main thread, the thread count
861decrements by 1, but the manager thread will never be killed, so you still have
8622 threads, which means you cannot safely run a death test.
863
864The new NPTL thread library doesn't suffer from this problem, as it doesn't
865create a manager thread. However, if you don't control which machine your test
866runs on, you shouldn't depend on this.
867
868## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ##
869
870Google Test does not interleave tests from different test cases. That is, it
871runs all tests in one test case first, and then runs all tests in the next test
872case, and so on. Google Test does this because it needs to set up a test case
873before the first test in it is run, and tear it down afterwords. Splitting up
874the test case would require multiple set-up and tear-down processes, which is
875inefficient and makes the semantics unclean.
876
877If we were to determine the order of tests based on test name instead of test
878case name, then we would have a problem with the following situation:
879
880```
881TEST_F(FooTest, AbcDeathTest) { ... }
882TEST_F(FooTest, Uvw) { ... }
883
884TEST_F(BarTest, DefDeathTest) { ... }
885TEST_F(BarTest, Xyz) { ... }
886```
887
888Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
889interleave tests from different test cases, we need to run all tests in the
890`FooTest` case before running any test in the `BarTest` case. This contradicts
891with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
892
893## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ##
894
895You don't have to, but if you like, you may split up the test case into
896`FooTest` and `FooDeathTest`, where the names make it clear that they are
897related:
898
899```
900class FooTest : public ::testing::Test { ... };
901
902TEST_F(FooTest, Abc) { ... }
903TEST_F(FooTest, Def) { ... }
904
905typedef FooTest FooDeathTest;
906
907TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
908TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
909```
910
911## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ##
912
913If you use a user-defined type `FooType` in an assertion, you must make sure
914there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
915defined such that we can print a value of `FooType`.
916
917In addition, if `FooType` is declared in a name space, the `<<` operator also
918needs to be defined in the _same_ name space.
919
920## How do I suppress the memory leak messages on Windows? ##
921
922Since the statically initialized Google Test singleton requires allocations on
923the heap, the Visual C++ memory leak detector will report memory leaks at the
924end of the program run. The easiest way to avoid this is to use the
925`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
926statically initialized heap objects. See MSDN for more details and additional
927heap check/debug routines.
928
929## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ##
930
931You may get a number of the following linker error or warnings if you
932attempt to link your test project with the Google Test library when
933your project and the are not built using the same compiler settings.
934
935  * LNK2005: symbol already defined in object
936  * LNK4217: locally defined symbol 'symbol' imported in function 'function'
937  * LNK4049: locally defined symbol 'symbol' imported
938
939The Google Test project (gtest.vcproj) has the Runtime Library option
940set to /MT (use multi-threaded static libraries, /MTd for debug). If
941your project uses something else, for example /MD (use multi-threaded
942DLLs, /MDd for debug), you need to change the setting in the Google
943Test project to match your project's.
944
945To update this setting open the project properties in the Visual
946Studio IDE then select the branch Configuration Properties | C/C++ |
947Code Generation and change the option "Runtime Library".  You may also try
948using gtest-md.vcproj instead of gtest.vcproj.
949
950## I put my tests in a library and Google Test doesn't run them. What's happening? ##
951Have you read a
952[warning](http://code.google.com/p/googletest/wiki/V1_6_Primer#Important_note_for_Visual_C++_users) on
953the Google Test Primer page?
954
955## I want to use Google Test with Visual Studio but don't know where to start. ##
956Many people are in your position and one of the posted his solution to
957our mailing list. Here is his link:
958http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html.
959
960## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ##
961Google Test uses parts of the standard C++ library that SunStudio does not support.
962Our users reported success using alternative implementations. Try running the build after runing this commad:
963
964`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'`
965
966## How can my code detect if it is running in a test? ##
967
968If you write code that sniffs whether it's running in a test and does
969different things accordingly, you are leaking test-only logic into
970production code and there is no easy way to ensure that the test-only
971code paths aren't run by mistake in production.  Such cleverness also
972leads to
973[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug).
974Therefore we strongly advise against the practice, and Google Test doesn't
975provide a way to do it.
976
977In general, the recommended way to cause the code to behave
978differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html).
979You can inject different functionality from the test and from the
980production code.  Since your production code doesn't link in the
981for-test logic at all, there is no danger in accidentally running it.
982
983However, if you _really_, _really_, _really_ have no choice, and if
984you follow the rule of ending your test program names with `_test`,
985you can use the _horrible_ hack of sniffing your executable name
986(`argv[0]` in `main()`) to know whether the code is under test.
987
988## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ##
989
990In C++, macros don't obey namespaces.  Therefore two libraries that
991both define a macro of the same name will clash if you #include both
992definitions.  In case a Google Test macro clashes with another
993library, you can force Google Test to rename its macro to avoid the
994conflict.
995
996Specifically, if both Google Test and some other code define macro
997`FOO`, you can add
998```
999  -DGTEST_DONT_DEFINE_FOO=1
1000```
1001to the compiler flags to tell Google Test to change the macro's name
1002from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
1003```
1004  GTEST_TEST(SomeTest, DoesThis) { ... }
1005```
1006instead of
1007```
1008  TEST(SomeTest, DoesThis) { ... }
1009```
1010in order to define a test.
1011
1012Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file.
1013
1014## My question is not covered in your FAQ! ##
1015
1016If you cannot find the answer to your question in this FAQ, there are
1017some other resources you can use:
1018
1019  1. read other [wiki pages](http://code.google.com/p/googletest/w/list),
1020  1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics),
1021  1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.).
1022
1023Please note that creating an issue in the
1024[issue tracker](http://code.google.com/p/googletest/issues/list) is _not_
1025a good way to get your answer, as it is monitored infrequently by a
1026very small number of people.
1027
1028When asking a question, it's helpful to provide as much of the
1029following information as possible (people cannot help you if there's
1030not enough information in your question):
1031
1032  * the version (or the revision number if you check out from SVN directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version),
1033  * your operating system,
1034  * the name and version of your compiler,
1035  * the complete command line flags you give to your compiler,
1036  * the complete compiler error messages (if the question is about compilation),
1037  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_6_Primer.md
r0r249096
1
2
3# Introduction: Why Google C++ Testing Framework? #
4
5_Google C++ Testing Framework_ helps you write better C++ tests.
6
7No matter whether you work on Linux, Windows, or a Mac, if you write C++ code,
8Google Test can help you.
9
10So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
11  1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests.  Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
12  1. Tests should be well _organized_ and reflect the structure of the tested code.  Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
13  1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral.  Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations.  (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
14  1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
15  1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_.  Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
16  1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
17
18Since Google C++ Testing Framework is based on the popular xUnit
19architecture, you'll feel right at home if you've used JUnit or PyUnit before.
20If not, it will take you about 10 minutes to learn the basics and get started.
21So let's go!
22
23_Note:_ We sometimes refer to Google C++ Testing Framework informally
24as _Google Test_.
25
26# Setting up a New Test Project #
27
28To write a test program using Google Test, you need to compile Google
29Test into a library and link your test with it.  We provide build
30files for some popular build systems: `msvc/` for Visual Studio,
31`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland
32C++ Builder, and the autotools script (deprecated) and
33`CMakeLists.txt` for CMake (recommended) in the Google Test root
34directory.  If your build system is not on this list, you can take a
35look at `make/Makefile` to learn how Google Test should be compiled
36(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT`
37and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT`
38is the Google Test root directory).
39
40Once you are able to compile the Google Test library, you should
41create a project or build target for your test program.  Make sure you
42have `GTEST_ROOT/include` in the header search path so that the
43compiler can find `"gtest/gtest.h"` when compiling your test.  Set up
44your test project to link with the Google Test library (for example,
45in Visual Studio, this is done by adding a dependency on
46`gtest.vcproj`).
47
48If you still have questions, take a look at how Google Test's own
49tests are built and use them as examples.
50
51# Basic Concepts #
52
53When using Google Test, you start by writing _assertions_, which are statements
54that check whether a condition is true. An assertion's result can be _success_,
55_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts
56the current function; otherwise the program continues normally.
57
58_Tests_ use assertions to verify the tested code's behavior. If a test crashes
59or has a failed assertion, then it _fails_; otherwise it _succeeds_.
60
61A _test case_ contains one or many tests. You should group your tests into test
62cases that reflect the structure of the tested code. When multiple tests in a
63test case need to share common objects and subroutines, you can put them into a
64_test fixture_ class.
65
66A _test program_ can contain multiple test cases.
67
68We'll now explain how to write a test program, starting at the individual
69assertion level and building up to tests and test cases.
70
71# Assertions #
72
73Google Test assertions are macros that resemble function calls. You test a
74class or function by making assertions about its behavior. When an assertion
75fails, Google Test prints the assertion's source file and line number location,
76along with a failure message. You may also supply a custom failure message
77which will be appended to Google Test's message.
78
79The assertions come in pairs that test the same thing but have different
80effects on the current function. `ASSERT_*` versions generate fatal failures
81when they fail, and **abort the current function**. `EXPECT_*` versions generate
82nonfatal failures, which don't abort the current function. Usually `EXPECT_*`
83are preferred, as they allow more than one failures to be reported in a test.
84However, you should use `ASSERT_*` if it doesn't make sense to continue when
85the assertion in question fails.
86
87Since a failed `ASSERT_*` returns from the current function immediately,
88possibly skipping clean-up code that comes after it, it may cause a space leak.
89Depending on the nature of the leak, it may or may not be worth fixing - so
90keep this in mind if you get a heap checker error in addition to assertion
91errors.
92
93To provide a custom failure message, simply stream it into the macro using the
94`<<` operator, or a sequence of such operators. An example:
95```
96ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
97
98for (int i = 0; i < x.size(); ++i) {
99  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
100}
101```
102
103Anything that can be streamed to an `ostream` can be streamed to an assertion
104macro--in particular, C strings and `string` objects. If a wide string
105(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
106streamed to an assertion, it will be translated to UTF-8 when printed.
107
108## Basic Assertions ##
109
110These assertions do basic true/false condition testing.
111| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
112|:--------------------|:-----------------------|:-------------|
113| `ASSERT_TRUE(`_condition_`)`;  | `EXPECT_TRUE(`_condition_`)`;   | _condition_ is true |
114| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`;  | _condition_ is false |
115
116Remember, when they fail, `ASSERT_*` yields a fatal failure and
117returns from the current function, while `EXPECT_*` yields a nonfatal
118failure, allowing the function to continue running. In either case, an
119assertion failure means its containing test fails.
120
121_Availability_: Linux, Windows, Mac.
122
123## Binary Comparison ##
124
125This section describes assertions that compare two values.
126
127| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
128|:--------------------|:-----------------------|:-------------|
129|`ASSERT_EQ(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ |
130|`ASSERT_NE(`_val1_`, `_val2_`);`      |`EXPECT_NE(`_val1_`, `_val2_`);`      | _val1_ `!=` _val2_ |
131|`ASSERT_LT(`_val1_`, `_val2_`);`      |`EXPECT_LT(`_val1_`, `_val2_`);`      | _val1_ `<` _val2_ |
132|`ASSERT_LE(`_val1_`, `_val2_`);`      |`EXPECT_LE(`_val1_`, `_val2_`);`      | _val1_ `<=` _val2_ |
133|`ASSERT_GT(`_val1_`, `_val2_`);`      |`EXPECT_GT(`_val1_`, `_val2_`);`      | _val1_ `>` _val2_ |
134|`ASSERT_GE(`_val1_`, `_val2_`);`      |`EXPECT_GE(`_val1_`, `_val2_`);`      | _val1_ `>=` _val2_ |
135
136In the event of a failure, Google Test prints both _val1_ and _val2_
137. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions
138we'll introduce later), you should put the expression you want to test
139in the position of _actual_, and put its expected value in _expected_,
140as Google Test's failure messages are optimized for this convention.
141
142Value arguments must be comparable by the assertion's comparison
143operator or you'll get a compiler error.  We used to require the
144arguments to support the `<<` operator for streaming to an `ostream`,
145but it's no longer necessary since v1.6.0 (if `<<` is supported, it
146will be called to print the arguments when the assertion fails;
147otherwise Google Test will attempt to print them in the best way it
148can. For more details and how to customize the printing of the
149arguments, see this Google Mock [recipe](http://code.google.com/p/googlemock/wiki/CookBook#Teaching_Google_Mock_How_to_Print_Your_Values).).
150
151These assertions can work with a user-defined type, but only if you define the
152corresponding comparison operator (e.g. `==`, `<`, etc).  If the corresponding
153operator is defined, prefer using the `ASSERT_*()` macros because they will
154print out not only the result of the comparison, but the two operands as well.
155
156Arguments are always evaluated exactly once. Therefore, it's OK for the
157arguments to have side effects. However, as with any ordinary C/C++ function,
158the arguments' evaluation order is undefined (i.e. the compiler is free to
159choose any order) and your code should not depend on any particular argument
160evaluation order.
161
162`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
163tests if they are in the same memory location, not if they have the same value.
164Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
165`ASSERT_STREQ()` , which will be described later on. In particular, to assert
166that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to
167compare two `string` objects, you should use `ASSERT_EQ`.
168
169Macros in this section work with both narrow and wide string objects (`string`
170and `wstring`).
171
172_Availability_: Linux, Windows, Mac.
173
174## String Comparison ##
175
176The assertions in this group compare two **C strings**. If you want to compare
177two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
178
179| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
180|:--------------------|:-----------------------|:-------------|
181| `ASSERT_STREQ(`_expected\_str_`, `_actual\_str_`);`    | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);`     | the two C strings have the same content |
182| `ASSERT_STRNE(`_str1_`, `_str2_`);`    | `EXPECT_STRNE(`_str1_`, `_str2_`);`     | the two C strings have different content |
183| `ASSERT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | the two C strings have the same content, ignoring case |
184| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case |
185
186Note that "CASE" in an assertion name means that case is ignored.
187
188`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a
189comparison of two wide strings fails, their values will be printed as UTF-8
190narrow strings.
191
192A `NULL` pointer and an empty string are considered _different_.
193
194_Availability_: Linux, Windows, Mac.
195
196See also: For more string comparison tricks (substring, prefix, suffix, and
197regular expression matching, for example), see the [Advanced Google Test Guide](V1_6_AdvancedGuide.md).
198
199# Simple Tests #
200
201To create a test:
202  1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value.
203  1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
204  1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
205
206```
207TEST(test_case_name, test_name) {
208 ... test body ...
209}
210```
211
212
213`TEST()` arguments go from general to specific. The _first_ argument is the
214name of the test case, and the _second_ argument is the test's name within the
215test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its
216individual name. Tests from different test cases can have the same individual
217name.
218
219For example, let's take a simple integer function:
220```
221int Factorial(int n); // Returns the factorial of n
222```
223
224A test case for this function might look like:
225```
226// Tests factorial of 0.
227TEST(FactorialTest, HandlesZeroInput) {
228  EXPECT_EQ(1, Factorial(0));
229}
230
231// Tests factorial of positive numbers.
232TEST(FactorialTest, HandlesPositiveInput) {
233  EXPECT_EQ(1, Factorial(1));
234  EXPECT_EQ(2, Factorial(2));
235  EXPECT_EQ(6, Factorial(3));
236  EXPECT_EQ(40320, Factorial(8));
237}
238```
239
240Google Test groups the test results by test cases, so logically-related tests
241should be in the same test case; in other words, the first argument to their
242`TEST()` should be the same. In the above example, we have two tests,
243`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
244case `FactorialTest`.
245
246_Availability_: Linux, Windows, Mac.
247
248# Test Fixtures: Using the Same Data Configuration for Multiple Tests #
249
250If you find yourself writing two or more tests that operate on similar data,
251you can use a _test fixture_. It allows you to reuse the same configuration of
252objects for several different tests.
253
254To create a fixture, just:
255  1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes.
256  1. Inside the class, declare any objects you plan to use.
257  1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you.
258  1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](http://code.google.com/p/googletest/wiki/V1_6_FAQ#Should_I_use_the_constructor/destructor_of_the_test_fixture_or_t).
259  1. If needed, define subroutines for your tests to share.
260
261When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
262access objects and subroutines in the test fixture:
263```
264TEST_F(test_case_name, test_name) {
265 ... test body ...
266}
267```
268
269Like `TEST()`, the first argument is the test case name, but for `TEST_F()`
270this must be the name of the test fixture class. You've probably guessed: `_F`
271is for fixture.
272
273Unfortunately, the C++ macro system does not allow us to create a single macro
274that can handle both types of tests. Using the wrong macro causes a compiler
275error.
276
277Also, you must first define a test fixture class before using it in a
278`TEST_F()`, or you'll get the compiler error "`virtual outside class
279declaration`".
280
281For each test defined with `TEST_F()`, Google Test will:
282  1. Create a _fresh_ test fixture at runtime
283  1. Immediately initialize it via `SetUp()` ,
284  1. Run the test
285  1. Clean up by calling `TearDown()`
286  1. Delete the test fixture.  Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
287
288As an example, let's write tests for a FIFO queue class named `Queue`, which
289has the following interface:
290```
291template <typename E> // E is the element type.
292class Queue {
293 public:
294  Queue();
295  void Enqueue(const E& element);
296  E* Dequeue(); // Returns NULL if the queue is empty.
297  size_t size() const;
298  ...
299};
300```
301
302First, define a fixture class. By convention, you should give it the name
303`FooTest` where `Foo` is the class being tested.
304```
305class QueueTest : public ::testing::Test {
306 protected:
307  virtual void SetUp() {
308    q1_.Enqueue(1);
309    q2_.Enqueue(2);
310    q2_.Enqueue(3);
311  }
312
313  // virtual void TearDown() {}
314
315  Queue<int> q0_;
316  Queue<int> q1_;
317  Queue<int> q2_;
318};
319```
320
321In this case, `TearDown()` is not needed since we don't have to clean up after
322each test, other than what's already done by the destructor.
323
324Now we'll write tests using `TEST_F()` and this fixture.
325```
326TEST_F(QueueTest, IsEmptyInitially) {
327  EXPECT_EQ(0, q0_.size());
328}
329
330TEST_F(QueueTest, DequeueWorks) {
331  int* n = q0_.Dequeue();
332  EXPECT_EQ(NULL, n);
333
334  n = q1_.Dequeue();
335  ASSERT_TRUE(n != NULL);
336  EXPECT_EQ(1, *n);
337  EXPECT_EQ(0, q1_.size());
338  delete n;
339
340  n = q2_.Dequeue();
341  ASSERT_TRUE(n != NULL);
342  EXPECT_EQ(2, *n);
343  EXPECT_EQ(1, q2_.size());
344  delete n;
345}
346```
347
348The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
349to use `EXPECT_*` when you want the test to continue to reveal more errors
350after the assertion failure, and use `ASSERT_*` when continuing after failure
351doesn't make sense. For example, the second assertion in the `Dequeue` test is
352`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later,
353which would lead to a segfault when `n` is `NULL`.
354
355When these tests run, the following happens:
356  1. Google Test constructs a `QueueTest` object (let's call it `t1` ).
357  1. `t1.SetUp()` initializes `t1` .
358  1. The first test ( `IsEmptyInitially` ) runs on `t1` .
359  1. `t1.TearDown()` cleans up after the test finishes.
360  1. `t1` is destructed.
361  1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test.
362
363_Availability_: Linux, Windows, Mac.
364
365_Note_: Google Test automatically saves all _Google Test_ flags when a test
366object is constructed, and restores them when it is destructed.
367
368# Invoking the Tests #
369
370`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
371
372After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files.
373
374When invoked, the `RUN_ALL_TESTS()` macro:
375  1. Saves the state of all  Google Test flags.
376  1. Creates a test fixture object for the first test.
377  1. Initializes it via `SetUp()`.
378  1. Runs the test on the fixture object.
379  1. Cleans up the fixture via `TearDown()`.
380  1. Deletes the fixture.
381  1. Restores the state of all Google Test flags.
382  1. Repeats the above steps for the next test, until all tests have run.
383
384In addition, if the text fixture's constructor generates a fatal failure in
385step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly,
386if step 3 generates a fatal failure, step 4 will be skipped.
387
388_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc`
389will give you a compiler error. The rationale for this design is that the
390automated testing service determines whether a test has passed based on its
391exit code, not on its stdout/stderr output; thus your `main()` function must
392return the value of `RUN_ALL_TESTS()`.
393
394Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once
395conflicts with some advanced Google Test features (e.g. thread-safe death
396tests) and thus is not supported.
397
398_Availability_: Linux, Windows, Mac.
399
400# Writing the main() Function #
401
402You can start from this boilerplate:
403```
404#include "this/package/foo.h"
405#include "gtest/gtest.h"
406
407namespace {
408
409// The fixture for testing class Foo.
410class FooTest : public ::testing::Test {
411 protected:
412  // You can remove any or all of the following functions if its body
413  // is empty.
414
415  FooTest() {
416    // You can do set-up work for each test here.
417  }
418
419  virtual ~FooTest() {
420    // You can do clean-up work that doesn't throw exceptions here.
421  }
422
423  // If the constructor and destructor are not enough for setting up
424  // and cleaning up each test, you can define the following methods:
425
426  virtual void SetUp() {
427    // Code here will be called immediately after the constructor (right
428    // before each test).
429  }
430
431  virtual void TearDown() {
432    // Code here will be called immediately after each test (right
433    // before the destructor).
434  }
435
436  // Objects declared here can be used by all tests in the test case for Foo.
437};
438
439// Tests that the Foo::Bar() method does Abc.
440TEST_F(FooTest, MethodBarDoesAbc) {
441  const string input_filepath = "this/package/testdata/myinputfile.dat";
442  const string output_filepath = "this/package/testdata/myoutputfile.dat";
443  Foo f;
444  EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
445}
446
447// Tests that Foo does Xyz.
448TEST_F(FooTest, DoesXyz) {
449  // Exercises the Xyz feature of Foo.
450}
451
452}  // namespace
453
454int main(int argc, char **argv) {
455  ::testing::InitGoogleTest(&argc, argv);
456  return RUN_ALL_TESTS();
457}
458```
459
460The `::testing::InitGoogleTest()` function parses the command line for Google
461Test flags, and removes all recognized flags. This allows the user to control a
462test program's behavior via various flags, which we'll cover in [AdvancedGuide](V1_6_AdvancedGuide.md).
463You must call this function before calling `RUN_ALL_TESTS()`, or the flags
464won't be properly initialized.
465
466On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
467in programs compiled in `UNICODE` mode as well.
468
469But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go.
470
471## Important note for Visual C++ users ##
472If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:
473```
474__declspec(dllexport) int PullInMyLibrary() { return 0; }
475```
476If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function:
477```
478int PullInMyLibrary();
479static int dummy = PullInMyLibrary();
480```
481This will keep your tests referenced and will make them register themselves at startup.
482
483In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.
484
485There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!
486
487# Where to Go from Here #
488
489Congratulations! You've learned the Google Test basics. You can start writing
490and running Google Test tests, read some [samples](V1_6_Samples.md), or continue with
491[AdvancedGuide](V1_6_AdvancedGuide.md), which describes many more useful Google Test features.
492
493# Known Limitations #
494
495Google Test is designed to be thread-safe.  The implementation is
496thread-safe on systems where the `pthreads` library is available.  It
497is currently _unsafe_ to use Google Test assertions from two threads
498concurrently on other systems (e.g. Windows).  In most tests this is
499not an issue as usually the assertions are done in the main thread. If
500you want to help, you can volunteer to implement the necessary
501synchronization primitives in `gtest-port.h` for your platform.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_6_PumpManual.md
r0r249096
1
2
3<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
4
5# The Problem #
6
7Template and macro libraries often need to define many classes,
8functions, or macros that vary only (or almost only) in the number of
9arguments they take. It's a lot of repetitive, mechanical, and
10error-prone work.
11
12Variadic templates and variadic macros can alleviate the problem.
13However, while both are being considered by the C++ committee, neither
14is in the standard yet or widely supported by compilers.  Thus they
15are often not a good choice, especially when your code needs to be
16portable. And their capabilities are still limited.
17
18As a result, authors of such libraries often have to write scripts to
19generate their implementation. However, our experience is that it's
20tedious to write such scripts, which tend to reflect the structure of
21the generated code poorly and are often hard to read and edit. For
22example, a small change needed in the generated code may require some
23non-intuitive, non-trivial changes in the script. This is especially
24painful when experimenting with the code.
25
26# Our Solution #
27
28Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
29Programming, or Practical Utility for Meta Programming, whichever you
30prefer) is a simple meta-programming tool for C++. The idea is that a
31programmer writes a `foo.pump` file which contains C++ code plus meta
32code that manipulates the C++ code. The meta code can handle
33iterations over a range, nested iterations, local meta variable
34definitions, simple arithmetic, and conditional expressions. You can
35view it as a small Domain-Specific Language. The meta language is
36designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode,
37for example) and concise, making Pump code intuitive and easy to
38maintain.
39
40## Highlights ##
41
42  * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms.
43  * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly.
44  * The format is human-readable and more concise than XML.
45  * The format works relatively well with Emacs' C++ mode.
46
47## Examples ##
48
49The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line):
50
51```
52$var n = 3     $$ Defines a meta variable n.
53$range i 0..n  $$ Declares the range of meta iterator i (inclusive).
54$for i [[
55               $$ Meta loop.
56// Foo$i does blah for $i-ary predicates.
57$range j 1..i
58template <size_t N $for j [[, typename A$j]]>
59class Foo$i {
60$if i == 0 [[
61  blah a;
62]] $elif i <= 2 [[
63  blah b;
64]] $else [[
65  blah c;
66]]
67};
68
69]]
70```
71
72will be translated by the Pump compiler to:
73
74```
75// Foo0 does blah for 0-ary predicates.
76template <size_t N>
77class Foo0 {
78  blah a;
79};
80
81// Foo1 does blah for 1-ary predicates.
82template <size_t N, typename A1>
83class Foo1 {
84  blah b;
85};
86
87// Foo2 does blah for 2-ary predicates.
88template <size_t N, typename A1, typename A2>
89class Foo2 {
90  blah b;
91};
92
93// Foo3 does blah for 3-ary predicates.
94template <size_t N, typename A1, typename A2, typename A3>
95class Foo3 {
96  blah c;
97};
98```
99
100In another example,
101
102```
103$range i 1..n
104Func($for i + [[a$i]]);
105$$ The text between i and [[ is the separator between iterations.
106```
107
108will generate one of the following lines (without the comments), depending on the value of `n`:
109
110```
111Func();              // If n is 0.
112Func(a1);            // If n is 1.
113Func(a1 + a2);       // If n is 2.
114Func(a1 + a2 + a3);  // If n is 3.
115// And so on...
116```
117
118## Constructs ##
119
120We support the following meta programming constructs:
121
122| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. |
123|:----------------|:-----------------------------------------------------------------------------------------------|
124| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later.          |
125| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`.         |
126| `$($)`          | Generates a single `$` character.                                                              |
127| `$id`           | Value of the named constant or iteration variable.                                             |
128| `$(exp)`        | Value of the expression.                                                                       |
129| `$if exp [[ code ]] else_branch` | Conditional.                                                                                   |
130| `[[ code ]]`    | Meta lexical block.                                                                            |
131| `cpp_code`      | Raw C++ code.                                                                                  |
132| `$$ comment`    | Meta comment.                                                                                  |
133
134**Note:** To give the user some freedom in formatting the Pump source
135code, Pump ignores a new-line character if it's right after `$for foo`
136or next to `[[` or `]]`. Without this rule you'll often be forced to write
137very long lines to get the desired output. Therefore sometimes you may
138need to insert an extra new-line in such places for a new-line to show
139up in your output.
140
141## Grammar ##
142
143```
144code ::= atomic_code*
145atomic_code ::= $var id = exp
146    | $var id = [[ code ]]
147    | $range id exp..exp
148    | $for id sep [[ code ]]
149    | $($)
150    | $id
151    | $(exp)
152    | $if exp [[ code ]] else_branch
153    | [[ code ]]
154    | cpp_code
155sep ::= cpp_code | empty_string
156else_branch ::= $else [[ code ]]
157    | $elif exp [[ code ]] else_branch
158    | empty_string
159exp ::= simple_expression_in_Python_syntax
160```
161
162## Code ##
163
164You can find the source code of Pump in [scripts/pump.py](http://code.google.com/p/googletest/source/browse/trunk/scripts/pump.py). It is still
165very unpolished and lacks automated tests, although it has been
166successfully used many times. If you find a chance to use it in your
167project, please let us know what you think!  We also welcome help on
168improving Pump.
169
170## Real Examples ##
171
172You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com).  The source file `foo.h.pump` generates `foo.h`.
173
174## Tips ##
175
176  * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1.
177  * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_6_Samples.md
r0r249096
1If you're like us, you'd like to look at some Google Test sample code.  The
2[samples folder](http://code.google.com/p/googletest/source/browse/#svn/trunk/samples) has a number of well-commented samples showing how to use a
3variety of Google Test features.
4
5  * [Sample #1](http://code.google.com/p/googletest/source/browse/trunk/samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions.
6  * [Sample #2](http://code.google.com/p/googletest/source/browse/trunk/samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions.
7  * [Sample #3](http://code.google.com/p/googletest/source/browse/trunk/samples/sample3_unittest.cc) uses a test fixture.
8  * [Sample #4](http://code.google.com/p/googletest/source/browse/trunk/samples/sample4_unittest.cc) is another basic example of using Google Test.
9  * [Sample #5](http://code.google.com/p/googletest/source/browse/trunk/samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it.
10  * [Sample #6](http://code.google.com/p/googletest/source/browse/trunk/samples/sample6_unittest.cc) demonstrates type-parameterized tests.
11  * [Sample #7](http://code.google.com/p/googletest/source/browse/trunk/samples/sample7_unittest.cc) teaches the basics of value-parameterized tests.
12  * [Sample #8](http://code.google.com/p/googletest/source/browse/trunk/samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests.
13  * [Sample #9](http://code.google.com/p/googletest/source/browse/trunk/samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results.
14  * [Sample #10](http://code.google.com/p/googletest/source/browse/trunk/samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_6_XcodeGuide.md
r0r249096
1
2
3This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step.
4
5# Quick Start #
6
7Here is the quick guide for using Google Test in your Xcode project.
8
9  1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`
10  1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework.
11  1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests"
12  1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests"
13  1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests"
14  1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable.
15  1. Build and Go
16
17The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations.
18
19# Get the Source #
20
21Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command:
22
23```
24svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only
25```
26
27Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository.
28
29To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory.
30
31The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`).
32
33Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory.
34
35```
36[Computer:svn] user$ svn propget svn:externals trunk
37externals/src/googletest http://googletest.googlecode.com/svn/trunk
38```
39
40# Add the Framework to Your Project #
41
42The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below.
43
44  * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project.
45  * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below).
46
47# Make a Test Target #
48
49To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target.
50
51Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above.
52
53  * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library.
54  * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll  want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase.
55
56# Set Up the Executable Run Environment #
57
58Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework.
59
60If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this:
61
62```
63[Session started at 2008-08-15 06:23:57 -0600.]
64  dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest
65    Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest
66    Reason: image not found
67```
68
69To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH.
70
71# Build and Go #
72
73Now, when you click "Build and Go", the test will be executed. Dumping out something like this:
74
75```
76[Session started at 2008-08-06 06:36:13 -0600.]
77[==========] Running 2 tests from 1 test case.
78[----------] Global test environment set-up.
79[----------] 2 tests from WidgetInitializerTest
80[ RUN      ] WidgetInitializerTest.TestConstructor
81[       OK ] WidgetInitializerTest.TestConstructor
82[ RUN      ] WidgetInitializerTest.TestConversion
83[       OK ] WidgetInitializerTest.TestConversion
84[----------] Global test environment tear-down
85[==========] 2 tests from 1 test case ran.
86[  PASSED  ] 2 tests.
87
88The Debugger has exited with status 0. 
89```
90
91# Summary #
92
93Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_7_AdvancedGuide.md
r0r249096
1
2
3Now that you have read [Primer](V1_7_Primer.md) and learned how to write tests
4using Google Test, it's time to learn some new tricks. This document
5will show you more assertions as well as how to construct complex
6failure messages, propagate fatal failures, reuse and speed up your
7test fixtures, and use various flags with your tests.
8
9# More Assertions #
10
11This section covers some less frequently used, but still significant,
12assertions.
13
14## Explicit Success and Failure ##
15
16These three assertions do not actually test a value or expression. Instead,
17they generate a success or failure directly. Like the macros that actually
18perform a test, you may stream a custom failure message into the them.
19
20| `SUCCEED();` |
21|:-------------|
22
23Generates a success. This does NOT make the overall test succeed. A test is
24considered successful only if none of its assertions fail during its execution.
25
26Note: `SUCCEED()` is purely documentary and currently doesn't generate any
27user-visible output. However, we may add `SUCCEED()` messages to Google Test's
28output in the future.
29
30| `FAIL();`  | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` |
31|:-----------|:-----------------|:------------------------------------------------------|
32
33`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal
34failure. These are useful when control flow, rather than a Boolean expression,
35deteremines the test's success or failure. For example, you might want to write
36something like:
37
38```
39switch(expression) {
40  case 1: ... some checks ...
41  case 2: ... some other checks
42  ...
43  default: FAIL() << "We shouldn't get here.";
44}
45```
46
47_Availability_: Linux, Windows, Mac.
48
49## Exception Assertions ##
50
51These are for verifying that a piece of code throws (or does not
52throw) an exception of the given type:
53
54| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
55|:--------------------|:-----------------------|:-------------|
56| `ASSERT_THROW(`_statement_, _exception\_type_`);`  | `EXPECT_THROW(`_statement_, _exception\_type_`);`  | _statement_ throws an exception of the given type  |
57| `ASSERT_ANY_THROW(`_statement_`);`                | `EXPECT_ANY_THROW(`_statement_`);`                | _statement_ throws an exception of any type        |
58| `ASSERT_NO_THROW(`_statement_`);`                 | `EXPECT_NO_THROW(`_statement_`);`                 | _statement_ doesn't throw any exception            |
59
60Examples:
61
62```
63ASSERT_THROW(Foo(5), bar_exception);
64
65EXPECT_NO_THROW({
66  int n = 5;
67  Bar(&n);
68});
69```
70
71_Availability_: Linux, Windows, Mac; since version 1.1.0.
72
73## Predicate Assertions for Better Error Messages ##
74
75Even though Google Test has a rich set of assertions, they can never be
76complete, as it's impossible (nor a good idea) to anticipate all the scenarios
77a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
78to check a complex expression, for lack of a better macro. This has the problem
79of not showing you the values of the parts of the expression, making it hard to
80understand what went wrong. As a workaround, some users choose to construct the
81failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
82is awkward especially when the expression has side-effects or is expensive to
83evaluate.
84
85Google Test gives you three different options to solve this problem:
86
87### Using an Existing Boolean Function ###
88
89If you already have a function or a functor that returns `bool` (or a type
90that can be implicitly converted to `bool`), you can use it in a _predicate
91assertion_ to get the function arguments printed for free:
92
93| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
94|:--------------------|:-----------------------|:-------------|
95| `ASSERT_PRED1(`_pred1, val1_`);`       | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
96| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` |  _pred2(val1, val2)_ returns true |
97|  ...                | ...                    | ...          |
98
99In the above, _predn_ is an _n_-ary predicate function or functor, where
100_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
101if the predicate returns `true` when applied to the given arguments, and fails
102otherwise. When the assertion fails, it prints the value of each argument. In
103either case, the arguments are evaluated exactly once.
104
105Here's an example. Given
106
107```
108// Returns true iff m and n have no common divisors except 1.
109bool MutuallyPrime(int m, int n) { ... }
110const int a = 3;
111const int b = 4;
112const int c = 10;
113```
114
115the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
116assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message
117
118<pre>
119!MutuallyPrime(b, c) is false, where<br>
120b is 4<br>
121c is 10<br>
122</pre>
123
124**Notes:**
125
126  1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](http://code.google.com/p/googletest/wiki/V1_7_FAQ#The_compiler_complains_%22no_matching_function_to_call%22) for how to resolve it.
127  1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.
128
129_Availability_: Linux, Windows, Mac
130
131### Using a Function That Returns an AssertionResult ###
132
133While `EXPECT_PRED*()` and friends are handy for a quick job, the
134syntax is not satisfactory: you have to use different macros for
135different arities, and it feels more like Lisp than C++.  The
136`::testing::AssertionResult` class solves this problem.
137
138An `AssertionResult` object represents the result of an assertion
139(whether it's a success or a failure, and an associated message).  You
140can create an `AssertionResult` using one of these factory
141functions:
142
143```
144namespace testing {
145
146// Returns an AssertionResult object to indicate that an assertion has
147// succeeded.
148AssertionResult AssertionSuccess();
149
150// Returns an AssertionResult object to indicate that an assertion has
151// failed.
152AssertionResult AssertionFailure();
153
154}
155```
156
157You can then use the `<<` operator to stream messages to the
158`AssertionResult` object.
159
160To provide more readable messages in Boolean assertions
161(e.g. `EXPECT_TRUE()`), write a predicate function that returns
162`AssertionResult` instead of `bool`. For example, if you define
163`IsEven()` as:
164
165```
166::testing::AssertionResult IsEven(int n) {
167  if ((n % 2) == 0)
168    return ::testing::AssertionSuccess();
169  else
170    return ::testing::AssertionFailure() << n << " is odd";
171}
172```
173
174instead of:
175
176```
177bool IsEven(int n) {
178  return (n % 2) == 0;
179}
180```
181
182the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
183
184<pre>
185Value of: IsEven(Fib(4))<br>
186Actual: false (*3 is odd*)<br>
187Expected: true<br>
188</pre>
189
190instead of a more opaque
191
192<pre>
193Value of: IsEven(Fib(4))<br>
194Actual: false<br>
195Expected: true<br>
196</pre>
197
198If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
199as well, and are fine with making the predicate slower in the success
200case, you can supply a success message:
201
202```
203::testing::AssertionResult IsEven(int n) {
204  if ((n % 2) == 0)
205    return ::testing::AssertionSuccess() << n << " is even";
206  else
207    return ::testing::AssertionFailure() << n << " is odd";
208}
209```
210
211Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
212
213<pre>
214Value of: IsEven(Fib(6))<br>
215Actual: true (8 is even)<br>
216Expected: false<br>
217</pre>
218
219_Availability_: Linux, Windows, Mac; since version 1.4.1.
220
221### Using a Predicate-Formatter ###
222
223If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
224`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
225predicate do not support streaming to `ostream`, you can instead use the
226following _predicate-formatter assertions_ to _fully_ customize how the
227message is formatted:
228
229| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
230|:--------------------|:-----------------------|:-------------|
231| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);`        | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`); | _pred\_format1(val1)_ is successful |
232| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful |
233| `...`               | `...`                  | `...`        |
234
235The difference between this and the previous two groups of macros is that instead of
236a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_
237(_pred\_formatn_), which is a function or functor with the signature:
238
239`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);`
240
241where _val1_, _val2_, ..., and _valn_ are the values of the predicate
242arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding
243expressions as they appear in the source code. The types `T1`, `T2`, ..., and
244`Tn` can be either value types or reference types. For example, if an
245argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`,
246whichever is appropriate.
247
248A predicate-formatter returns a `::testing::AssertionResult` object to indicate
249whether the assertion has succeeded or not. The only way to create such an
250object is to call one of these factory functions:
251
252As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`:
253
254```
255// Returns the smallest prime common divisor of m and n,
256// or 1 when m and n are mutually prime.
257int SmallestPrimeCommonDivisor(int m, int n) { ... }
258
259// A predicate-formatter for asserting that two integers are mutually prime.
260::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
261                                               const char* n_expr,
262                                               int m,
263                                               int n) {
264  if (MutuallyPrime(m, n))
265    return ::testing::AssertionSuccess();
266 
267  return ::testing::AssertionFailure()
268      << m_expr << " and " << n_expr << " (" << m << " and " << n
269      << ") are not mutually prime, " << "as they have a common divisor "
270      << SmallestPrimeCommonDivisor(m, n);
271}
272```
273
274With this predicate-formatter, we can use
275
276```
277EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
278```
279
280to generate the message
281
282<pre>
283b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br>
284</pre>
285
286As you may have realized, many of the assertions we introduced earlier are
287special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
288indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.
289
290_Availability_: Linux, Windows, Mac.
291
292
293## Floating-Point Comparison ##
294
295Comparing floating-point numbers is tricky. Due to round-off errors, it is
296very unlikely that two floating-points will match exactly. Therefore,
297`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points
298can have a wide value range, no single fixed error bound works. It's better to
299compare by a fixed relative error bound, except for values close to 0 due to
300the loss of precision there.
301
302In general, for floating-point comparison to make sense, the user needs to
303carefully choose the error bound. If they don't want or care to, comparing in
304terms of Units in the Last Place (ULPs) is a good default, and Google Test
305provides assertions to do this. Full details about ULPs are quite long; if you
306want to learn more, see
307[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).
308
309### Floating-Point Macros ###
310
311| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
312|:--------------------|:-----------------------|:-------------|
313| `ASSERT_FLOAT_EQ(`_expected, actual_`);`  | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal |
314| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | the two `double` values are almost equal |
315
316By "almost equal", we mean the two values are within 4 ULP's from each
317other.
318
319The following assertions allow you to choose the acceptable error bound:
320
321| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
322|:--------------------|:-----------------------|:-------------|
323| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error |
324
325_Availability_: Linux, Windows, Mac.
326
327### Floating-Point Predicate-Format Functions ###
328
329Some floating-point operations are useful, but not that often used. In order
330to avoid an explosion of new macros, we provide them as predicate-format
331functions that can be used in predicate assertion macros (e.g.
332`EXPECT_PRED_FORMAT2`, etc).
333
334```
335EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
336EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
337```
338
339Verifies that _val1_ is less than, or almost equal to, _val2_. You can
340replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.
341
342_Availability_: Linux, Windows, Mac.
343
344## Windows HRESULT assertions ##
345
346These assertions test for `HRESULT` success or failure.
347
348| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
349|:--------------------|:-----------------------|:-------------|
350| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` |
351| `ASSERT_HRESULT_FAILED(`_expression_`);`    | `EXPECT_HRESULT_FAILED(`_expression_`);`    | _expression_ is a failure `HRESULT` |
352
353The generated output contains the human-readable error message
354associated with the `HRESULT` code returned by _expression_.
355
356You might use them like this:
357
358```
359CComPtr shell;
360ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
361CComVariant empty;
362ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
363```
364
365_Availability_: Windows.
366
367## Type Assertions ##
368
369You can call the function
370```
371::testing::StaticAssertTypeEq<T1, T2>();
372```
373to assert that types `T1` and `T2` are the same.  The function does
374nothing if the assertion is satisfied.  If the types are different,
375the function call will fail to compile, and the compiler error message
376will likely (depending on the compiler) show you the actual values of
377`T1` and `T2`.  This is mainly useful inside template code.
378
379_Caveat:_ When used inside a member function of a class template or a
380function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_
381the function is instantiated.  For example, given:
382```
383template <typename T> class Foo {
384 public:
385  void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
386};
387```
388the code:
389```
390void Test1() { Foo<bool> foo; }
391```
392will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never
393actually instantiated.  Instead, you need:
394```
395void Test2() { Foo<bool> foo; foo.Bar(); }
396```
397to cause a compiler error.
398
399_Availability:_ Linux, Windows, Mac; since version 1.3.0.
400
401## Assertion Placement ##
402
403You can use assertions in any C++ function. In particular, it doesn't
404have to be a method of the test fixture class. The one constraint is
405that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`)
406can only be used in void-returning functions. This is a consequence of
407Google Test not using exceptions. By placing it in a non-void function
408you'll get a confusing compile error like
409`"error: void value not ignored as it ought to be"`.
410
411If you need to use assertions in a function that returns non-void, one option
412is to make the function return the value in an out parameter instead. For
413example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
414need to make sure that `*result` contains some sensible value even when the
415function returns prematurely. As the function now returns `void`, you can use
416any assertion inside of it.
417
418If changing the function's type is not an option, you should just use
419assertions that generate non-fatal failures, such as `ADD_FAILURE*` and
420`EXPECT_*`.
421
422_Note_: Constructors and destructors are not considered void-returning
423functions, according to the C++ language specification, and so you may not use
424fatal assertions in them. You'll get a compilation error if you try. A simple
425workaround is to transfer the entire body of the constructor or destructor to a
426private void-returning method. However, you should be aware that a fatal
427assertion failure in a constructor does not terminate the current test, as your
428intuition might suggest; it merely returns from the constructor early, possibly
429leaving your object in a partially-constructed state. Likewise, a fatal
430assertion failure in a destructor may leave your object in a
431partially-destructed state. Use assertions carefully in these situations!
432
433# Teaching Google Test How to Print Your Values #
434
435When a test assertion such as `EXPECT_EQ` fails, Google Test prints the
436argument values to help you debug.  It does this using a
437user-extensible value printer.
438
439This printer knows how to print built-in C++ types, native arrays, STL
440containers, and any type that supports the `<<` operator.  For other
441types, it prints the raw bytes in the value and hopes that you the
442user can figure it out.
443
444As mentioned earlier, the printer is _extensible_.  That means
445you can teach it to do a better job at printing your particular type
446than to dump the bytes.  To do that, define `<<` for your type:
447
448```
449#include <iostream>
450
451namespace foo {
452
453class Bar { ... };  // We want Google Test to be able to print instances of this.
454
455// It's important that the << operator is defined in the SAME
456// namespace that defines Bar.  C++'s look-up rules rely on that.
457::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {
458  return os << bar.DebugString();  // whatever needed to print bar to os
459}
460
461}  // namespace foo
462```
463
464Sometimes, this might not be an option: your team may consider it bad
465style to have a `<<` operator for `Bar`, or `Bar` may already have a
466`<<` operator that doesn't do what you want (and you cannot change
467it).  If so, you can instead define a `PrintTo()` function like this:
468
469```
470#include <iostream>
471
472namespace foo {
473
474class Bar { ... };
475
476// It's important that PrintTo() is defined in the SAME
477// namespace that defines Bar.  C++'s look-up rules rely on that.
478void PrintTo(const Bar& bar, ::std::ostream* os) {
479  *os << bar.DebugString();  // whatever needed to print bar to os
480}
481
482}  // namespace foo
483```
484
485If you have defined both `<<` and `PrintTo()`, the latter will be used
486when Google Test is concerned.  This allows you to customize how the value
487appears in Google Test's output without affecting code that relies on the
488behavior of its `<<` operator.
489
490If you want to print a value `x` using Google Test's value printer
491yourself, just call `::testing::PrintToString(`_x_`)`, which
492returns an `std::string`:
493
494```
495vector<pair<Bar, int> > bar_ints = GetBarIntVector();
496
497EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
498    << "bar_ints = " << ::testing::PrintToString(bar_ints);
499```
500
501# Death Tests #
502
503In many applications, there are assertions that can cause application failure
504if a condition is not met. These sanity checks, which ensure that the program
505is in a known good state, are there to fail at the earliest possible time after
506some program state is corrupted. If the assertion checks the wrong condition,
507then the program may proceed in an erroneous state, which could lead to memory
508corruption, security holes, or worse. Hence it is vitally important to test
509that such assertion statements work as expected.
510
511Since these precondition checks cause the processes to die, we call such tests
512_death tests_. More generally, any test that checks that a program terminates
513(except by throwing an exception) in an expected fashion is also a death test.
514
515Note that if a piece of code throws an exception, we don't consider it "death"
516for the purpose of death tests, as the caller of the code could catch the exception
517and avoid the crash. If you want to verify exceptions thrown by your code,
518see [Exception Assertions](#Exception_Assertions.md).
519
520If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#Catching_Failures.md).
521
522## How to Write a Death Test ##
523
524Google Test has the following macros to support death tests:
525
526| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
527|:--------------------|:-----------------------|:-------------|
528| `ASSERT_DEATH(`_statement, regex_`); | `EXPECT_DEATH(`_statement, regex_`); | _statement_ crashes with the given error |
529| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`); | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`); | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing |
530| `ASSERT_EXIT(`_statement, predicate, regex_`); | `EXPECT_EXIT(`_statement, predicate, regex_`); |_statement_ exits with the given error and its exit code matches _predicate_ |
531
532where _statement_ is a statement that is expected to cause the process to
533die, _predicate_ is a function or function object that evaluates an integer
534exit status, and _regex_ is a regular expression that the stderr output of
535_statement_ is expected to match. Note that _statement_ can be _any valid
536statement_ (including _compound statement_) and doesn't have to be an
537expression.
538
539As usual, the `ASSERT` variants abort the current test function, while the
540`EXPECT` variants do not.
541
542**Note:** We use the word "crash" here to mean that the process
543terminates with a _non-zero_ exit status code.  There are two
544possibilities: either the process has called `exit()` or `_exit()`
545with a non-zero value, or it may be killed by a signal.
546
547This means that if _statement_ terminates the process with a 0 exit
548code, it is _not_ considered a crash by `EXPECT_DEATH`.  Use
549`EXPECT_EXIT` instead if this is the case, or if you want to restrict
550the exit code more precisely.
551
552A predicate here must accept an `int` and return a `bool`. The death test
553succeeds only if the predicate returns `true`. Google Test defines a few
554predicates that handle the most common cases:
555
556```
557::testing::ExitedWithCode(exit_code)
558```
559
560This expression is `true` if the program exited normally with the given exit
561code.
562
563```
564::testing::KilledBySignal(signal_number)  // Not available on Windows.
565```
566
567This expression is `true` if the program was killed by the given signal.
568
569The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
570that verifies the process' exit code is non-zero.
571
572Note that a death test only cares about three things:
573
574  1. does _statement_ abort or exit the process?
575  1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_?  Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero?  And
576  1. does the stderr output match _regex_?
577
578In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process.
579
580To write a death test, simply use one of the above macros inside your test
581function. For example,
582
583```
584TEST(MyDeathTest, Foo) {
585  // This death test uses a compound statement.
586  ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()");
587}
588TEST(MyDeathTest, NormalExit) {
589  EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
590}
591TEST(MyDeathTest, KillMyself) {
592  EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal");
593}
594```
595
596verifies that:
597
598  * calling `Foo(5)` causes the process to die with the given error message,
599  * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and
600  * calling `KillMyself()` kills the process with signal `SIGKILL`.
601
602The test function body may contain other assertions and statements as well, if
603necessary.
604
605_Important:_ We strongly recommend you to follow the convention of naming your
606test case (not test) `*DeathTest` when it contains a death test, as
607demonstrated in the above example. The `Death Tests And Threads` section below
608explains why.
609
610If a test fixture class is shared by normal tests and death tests, you
611can use typedef to introduce an alias for the fixture class and avoid
612duplicating its code:
613```
614class FooTest : public ::testing::Test { ... };
615
616typedef FooTest FooDeathTest;
617
618TEST_F(FooTest, DoesThis) {
619  // normal test
620}
621
622TEST_F(FooDeathTest, DoesThat) {
623  // death test
624}
625```
626
627_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0).  `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0.
628
629## Regular Expression Syntax ##
630
631On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the
632[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
633syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
634
635On Windows, Google Test uses its own simple regular expression
636implementation. It lacks many features you can find in POSIX extended
637regular expressions.  For example, we don't support union (`"x|y"`),
638grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count
639(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a
640literal character, period (`.`), or a single `\\` escape sequence; `x`
641and `y` denote regular expressions.):
642
643| `c` | matches any literal character `c` |
644|:----|:----------------------------------|
645| `\\d` | matches any decimal digit         |
646| `\\D` | matches any character that's not a decimal digit |
647| `\\f` | matches `\f`                      |
648| `\\n` | matches `\n`                      |
649| `\\r` | matches `\r`                      |
650| `\\s` | matches any ASCII whitespace, including `\n` |
651| `\\S` | matches any character that's not a whitespace |
652| `\\t` | matches `\t`                      |
653| `\\v` | matches `\v`                      |
654| `\\w` | matches any letter, `_`, or decimal digit |
655| `\\W` | matches any character that `\\w` doesn't match |
656| `\\c` | matches any literal character `c`, which must be a punctuation |
657| `\\.` | matches the `.` character         |
658| `.` | matches any single character except `\n` |
659| `A?` | matches 0 or 1 occurrences of `A` |
660| `A*` | matches 0 or many occurrences of `A` |
661| `A+` | matches 1 or many occurrences of `A` |
662| `^` | matches the beginning of a string (not that of each line) |
663| `$` | matches the end of a string (not that of each line) |
664| `xy` | matches `x` followed by `y`       |
665
666To help you determine which capability is available on your system,
667Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX
668extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses
669the simple version.  If you want your death tests to work in both
670cases, you can either `#if` on these macros or use the more limited
671syntax only.
672
673## How It Works ##
674
675Under the hood, `ASSERT_EXIT()` spawns a new process and executes the
676death test statement in that process. The details of of how precisely
677that happens depend on the platform and the variable
678`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the
679command-line flag `--gtest_death_test_style`).
680
681  * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which:
682    * If the variable's value is `"fast"`, the death test statement is immediately executed.
683    * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run.
684  * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX.
685
686Other values for the variable are illegal and will cause the death test to
687fail. Currently, the flag's default value is `"fast"`. However, we reserve the
688right to change it in the future. Therefore, your tests should not depend on
689this.
690
691In either case, the parent process waits for the child process to complete, and checks that
692
693  1. the child's exit status satisfies the predicate, and
694  1. the child's stderr matches the regular expression.
695
696If the death test statement runs to completion without dying, the child
697process will nonetheless terminate, and the assertion fails.
698
699## Death Tests And Threads ##
700
701The reason for the two death test styles has to do with thread safety. Due to
702well-known problems with forking in the presence of threads, death tests should
703be run in a single-threaded context. Sometimes, however, it isn't feasible to
704arrange that kind of environment. For example, statically-initialized modules
705may start threads before main is ever reached. Once threads have been created,
706it may be difficult or impossible to clean them up.
707
708Google Test has three features intended to raise awareness of threading issues.
709
710  1. A warning is emitted if multiple threads are running when a death test is encountered.
711  1. Test cases with a name ending in "DeathTest" are run before all other tests.
712  1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads.
713
714It's perfectly fine to create threads inside a death test statement; they are
715executed in a separate process and cannot affect the parent.
716
717## Death Test Styles ##
718
719The "threadsafe" death test style was introduced in order to help mitigate the
720risks of testing in a possibly multithreaded environment. It trades increased
721test execution time (potentially dramatically so) for improved thread safety.
722We suggest using the faster, default "fast" style unless your test has specific
723problems with it.
724
725You can choose a particular style of death tests by setting the flag
726programmatically:
727
728```
729::testing::FLAGS_gtest_death_test_style = "threadsafe";
730```
731
732You can do this in `main()` to set the style for all death tests in the
733binary, or in individual tests. Recall that flags are saved before running each
734test and restored afterwards, so you need not do that yourself. For example:
735
736```
737TEST(MyDeathTest, TestOne) {
738  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
739  // This test is run in the "threadsafe" style:
740  ASSERT_DEATH(ThisShouldDie(), "");
741}
742
743TEST(MyDeathTest, TestTwo) {
744  // This test is run in the "fast" style:
745  ASSERT_DEATH(ThisShouldDie(), "");
746}
747
748int main(int argc, char** argv) {
749  ::testing::InitGoogleTest(&argc, argv);
750  ::testing::FLAGS_gtest_death_test_style = "fast";
751  return RUN_ALL_TESTS();
752}
753```
754
755## Caveats ##
756
757The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement.
758If it leaves the current function via a `return` statement or by throwing an exception,
759the death test is considered to have failed.  Some Google Test macros may return
760from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_.
761
762Since _statement_ runs in the child process, any in-memory side effect (e.g.
763modifying a variable, releasing memory, etc) it causes will _not_ be observable
764in the parent process. In particular, if you release memory in a death test,
765your program will fail the heap check as the parent process will never see the
766memory reclaimed. To solve this problem, you can
767
768  1. try not to free memory in a death test;
769  1. free the memory again in the parent process; or
770  1. do not use the heap checker in your program.
771
772Due to an implementation detail, you cannot place multiple death test
773assertions on the same line; otherwise, compilation will fail with an unobvious
774error message.
775
776Despite the improved thread safety afforded by the "threadsafe" style of death
777test, thread problems such as deadlock are still possible in the presence of
778handlers registered with `pthread_atfork(3)`.
779
780# Using Assertions in Sub-routines #
781
782## Adding Traces to Assertions ##
783
784If a test sub-routine is called from several places, when an assertion
785inside it fails, it can be hard to tell which invocation of the
786sub-routine the failure is from.  You can alleviate this problem using
787extra logging or custom failure messages, but that usually clutters up
788your tests. A better solution is to use the `SCOPED_TRACE` macro:
789
790| `SCOPED_TRACE(`_message_`);` |
791|:-----------------------------|
792
793where _message_ can be anything streamable to `std::ostream`. This
794macro will cause the current file name, line number, and the given
795message to be added in every failure message. The effect will be
796undone when the control leaves the current lexical scope.
797
798For example,
799
800```
80110: void Sub1(int n) {
80211:   EXPECT_EQ(1, Bar(n));
80312:   EXPECT_EQ(2, Bar(n + 1));
80413: }
80514:
80615: TEST(FooTest, Bar) {
80716:   {
80817:     SCOPED_TRACE("A");  // This trace point will be included in
80918:                         // every failure in this scope.
81019:     Sub1(1);
81120:   }
81221:   // Now it won't.
81322:   Sub1(9);
81423: }
815```
816
817could result in messages like these:
818
819```
820path/to/foo_test.cc:11: Failure
821Value of: Bar(n)
822Expected: 1
823  Actual: 2
824   Trace:
825path/to/foo_test.cc:17: A
826
827path/to/foo_test.cc:12: Failure
828Value of: Bar(n + 1)
829Expected: 2
830  Actual: 3
831```
832
833Without the trace, it would've been difficult to know which invocation
834of `Sub1()` the two failures come from respectively. (You could add an
835extra message to each assertion in `Sub1()` to indicate the value of
836`n`, but that's tedious.)
837
838Some tips on using `SCOPED_TRACE`:
839
840  1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site.
841  1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from.
842  1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`.
843  1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered.
844  1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file!
845
846_Availability:_ Linux, Windows, Mac.
847
848## Propagating Fatal Failures ##
849
850A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
851when they fail they only abort the _current function_, not the entire test. For
852example, the following test will segfault:
853```
854void Subroutine() {
855  // Generates a fatal failure and aborts the current function.
856  ASSERT_EQ(1, 2);
857  // The following won't be executed.
858  ...
859}
860
861TEST(FooTest, Bar) {
862  Subroutine();
863  // The intended behavior is for the fatal failure
864  // in Subroutine() to abort the entire test.
865  // The actual behavior: the function goes on after Subroutine() returns.
866  int* p = NULL;
867  *p = 3; // Segfault!
868}
869```
870
871Since we don't use exceptions, it is technically impossible to
872implement the intended behavior here.  To alleviate this, Google Test
873provides two solutions.  You could use either the
874`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
875`HasFatalFailure()` function.  They are described in the following two
876subsections.
877
878### Asserting on Subroutines ###
879
880As shown above, if your test calls a subroutine that has an `ASSERT_*`
881failure in it, the test will continue after the subroutine
882returns. This may not be what you want.
883
884Often people want fatal failures to propagate like exceptions.  For
885that Google Test offers the following macros:
886
887| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
888|:--------------------|:-----------------------|:-------------|
889| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. |
890
891Only failures in the thread that executes the assertion are checked to
892determine the result of this type of assertions.  If _statement_
893creates new threads, failures in these threads are ignored.
894
895Examples:
896
897```
898ASSERT_NO_FATAL_FAILURE(Foo());
899
900int i;
901EXPECT_NO_FATAL_FAILURE({
902  i = Bar();
903});
904```
905
906_Availability:_ Linux, Windows, Mac. Assertions from multiple threads
907are currently not supported.
908
909### Checking for Failures in the Current Test ###
910
911`HasFatalFailure()` in the `::testing::Test` class returns `true` if an
912assertion in the current test has suffered a fatal failure. This
913allows functions to catch fatal failures in a sub-routine and return
914early.
915
916```
917class Test {
918 public:
919  ...
920  static bool HasFatalFailure();
921};
922```
923
924The typical usage, which basically simulates the behavior of a thrown
925exception, is:
926
927```
928TEST(FooTest, Bar) {
929  Subroutine();
930  // Aborts if Subroutine() had a fatal failure.
931  if (HasFatalFailure())
932    return;
933  // The following won't be executed.
934  ...
935}
936```
937
938If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
939fixture, you must add the `::testing::Test::` prefix, as in:
940
941```
942if (::testing::Test::HasFatalFailure())
943  return;
944```
945
946Similarly, `HasNonfatalFailure()` returns `true` if the current test
947has at least one non-fatal failure, and `HasFailure()` returns `true`
948if the current test has at least one failure of either kind.
949
950_Availability:_ Linux, Windows, Mac.  `HasNonfatalFailure()` and
951`HasFailure()` are available since version 1.4.0.
952
953# Logging Additional Information #
954
955In your test code, you can call `RecordProperty("key", value)` to log
956additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output
957if you specify one. For example, the test
958
959```
960TEST_F(WidgetUsageTest, MinAndMaxWidgets) {
961  RecordProperty("MaximumWidgets", ComputeMaxUsage());
962  RecordProperty("MinimumWidgets", ComputeMinUsage());
963}
964```
965
966will output XML like this:
967
968```
969...
970  <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest"
971            MaximumWidgets="12"
972            MinimumWidgets="9" />
973...
974```
975
976_Note_:
977  * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class.
978  * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`).
979  * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element.
980
981_Availability_: Linux, Windows, Mac.
982
983# Sharing Resources Between Tests in the Same Test Case #
984
985
986
987Google Test creates a new test fixture object for each test in order to make
988tests independent and easier to debug. However, sometimes tests use resources
989that are expensive to set up, making the one-copy-per-test model prohibitively
990expensive.
991
992If the tests don't change the resource, there's no harm in them sharing a
993single resource copy. So, in addition to per-test set-up/tear-down, Google Test
994also supports per-test-case set-up/tear-down. To use it:
995
996  1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources.
997  1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down.
998
999That's it! Google Test automatically calls `SetUpTestCase()` before running the
1000_first test_ in the `FooTest` test case (i.e. before creating the first
1001`FooTest` object), and calls `TearDownTestCase()` after running the _last test_
1002in it (i.e. after deleting the last `FooTest` object). In between, the tests
1003can use the shared resources.
1004
1005Remember that the test order is undefined, so your code can't depend on a test
1006preceding or following another. Also, the tests must either not modify the
1007state of any shared resource, or, if they do modify the state, they must
1008restore the state to its original value before passing control to the next
1009test.
1010
1011Here's an example of per-test-case set-up and tear-down:
1012```
1013class FooTest : public ::testing::Test {
1014 protected:
1015  // Per-test-case set-up.
1016  // Called before the first test in this test case.
1017  // Can be omitted if not needed.
1018  static void SetUpTestCase() {
1019    shared_resource_ = new ...;
1020  }
1021
1022  // Per-test-case tear-down.
1023  // Called after the last test in this test case.
1024  // Can be omitted if not needed.
1025  static void TearDownTestCase() {
1026    delete shared_resource_;
1027    shared_resource_ = NULL;
1028  }
1029
1030  // You can define per-test set-up and tear-down logic as usual.
1031  virtual void SetUp() { ... }
1032  virtual void TearDown() { ... }
1033
1034  // Some expensive resource shared by all tests.
1035  static T* shared_resource_;
1036};
1037
1038T* FooTest::shared_resource_ = NULL;
1039
1040TEST_F(FooTest, Test1) {
1041  ... you can refer to shared_resource here ...
1042}
1043TEST_F(FooTest, Test2) {
1044  ... you can refer to shared_resource here ...
1045}
1046```
1047
1048_Availability:_ Linux, Windows, Mac.
1049
1050# Global Set-Up and Tear-Down #
1051
1052Just as you can do set-up and tear-down at the test level and the test case
1053level, you can also do it at the test program level. Here's how.
1054
1055First, you subclass the `::testing::Environment` class to define a test
1056environment, which knows how to set-up and tear-down:
1057
1058```
1059class Environment {
1060 public:
1061  virtual ~Environment() {}
1062  // Override this to define how to set up the environment.
1063  virtual void SetUp() {}
1064  // Override this to define how to tear down the environment.
1065  virtual void TearDown() {}
1066};
1067```
1068
1069Then, you register an instance of your environment class with Google Test by
1070calling the `::testing::AddGlobalTestEnvironment()` function:
1071
1072```
1073Environment* AddGlobalTestEnvironment(Environment* env);
1074```
1075
1076Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
1077the environment object, then runs the tests if there was no fatal failures, and
1078finally calls `TearDown()` of the environment object.
1079
1080It's OK to register multiple environment objects. In this case, their `SetUp()`
1081will be called in the order they are registered, and their `TearDown()` will be
1082called in the reverse order.
1083
1084Note that Google Test takes ownership of the registered environment objects.
1085Therefore **do not delete them** by yourself.
1086
1087You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is
1088called, probably in `main()`. If you use `gtest_main`, you need to      call
1089this before `main()` starts for it to take effect. One way to do this is to
1090define a global variable like this:
1091
1092```
1093::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
1094```
1095
1096However, we strongly recommend you to write your own `main()` and call
1097`AddGlobalTestEnvironment()` there, as relying on initialization of global
1098variables makes the code harder to read and may cause problems when you
1099register multiple environments from different translation units and the
1100environments have dependencies among them (remember that the compiler doesn't
1101guarantee the order in which global variables from different translation units
1102are initialized).
1103
1104_Availability:_ Linux, Windows, Mac.
1105
1106
1107# Value Parameterized Tests #
1108
1109_Value-parameterized tests_ allow you to test your code with different
1110parameters without writing multiple copies of the same test.
1111
1112Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag.
1113
1114```
1115TEST(MyCodeTest, TestFoo) {
1116  // A code to test foo().
1117}
1118```
1119
1120Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code.
1121
1122```
1123void TestFooHelper(bool flag_value) {
1124  flag = flag_value;
1125  // A code to test foo().
1126}
1127
1128TEST(MyCodeTest, TestFoo) {
1129  TestFooHelper(false);
1130  TestFooHelper(true);
1131}
1132```
1133
1134But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred?
1135
1136Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values.
1137
1138Here are some other situations when value-parameterized tests come handy:
1139
1140  * You want to test different implementations of an OO interface.
1141  * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it!
1142
1143## How to Write Value-Parameterized Tests ##
1144
1145To write value-parameterized tests, first you should define a fixture
1146class.  It must be derived from both `::testing::Test` and
1147`::testing::WithParamInterface<T>` (the latter is a pure interface),
1148where `T` is the type of your parameter values.  For convenience, you
1149can just derive the fixture class from `::testing::TestWithParam<T>`,
1150which itself is derived from both `::testing::Test` and
1151`::testing::WithParamInterface<T>`. `T` can be any copyable type. If
1152it's a raw pointer, you are responsible for managing the lifespan of
1153the pointed values.
1154
1155```
1156class FooTest : public ::testing::TestWithParam<const char*> {
1157  // You can implement all the usual fixture class members here.
1158  // To access the test parameter, call GetParam() from class
1159  // TestWithParam<T>.
1160};
1161
1162// Or, when you want to add parameters to a pre-existing fixture class:
1163class BaseTest : public ::testing::Test {
1164  ...
1165};
1166class BarTest : public BaseTest,
1167                public ::testing::WithParamInterface<const char*> {
1168  ...
1169};
1170```
1171
1172Then, use the `TEST_P` macro to define as many test patterns using
1173this fixture as you want.  The `_P` suffix is for "parameterized" or
1174"pattern", whichever you prefer to think.
1175
1176```
1177TEST_P(FooTest, DoesBlah) {
1178  // Inside a test, access the test parameter with the GetParam() method
1179  // of the TestWithParam<T> class:
1180  EXPECT_TRUE(foo.Blah(GetParam()));
1181  ...
1182}
1183
1184TEST_P(FooTest, HasBlahBlah) {
1185  ...
1186}
1187```
1188
1189Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test
1190case with any set of parameters you want. Google Test defines a number of
1191functions for generating test parameters. They return what we call
1192(surprise!) _parameter generators_. Here is a summary of them,
1193which are all in the `testing` namespace:
1194
1195| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
1196|:----------------------------|:------------------------------------------------------------------------------------------------------------------|
1197| `Values(v1, v2, ..., vN)`   | Yields values `{v1, v2, ..., vN}`.                                                                                |
1198| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time.  |
1199| `Bool()`                    | Yields sequence `{false, true}`.                                                                                  |
1200| `Combine(g1, g2, ..., gN)`  | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `<tr1/tuple>` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-port.h) for more information. |
1201
1202For more details, see the comments at the definitions of these functions in the [source code](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-param-test.h).
1203
1204The following statement will instantiate tests from the `FooTest` test case
1205each with parameter values `"meeny"`, `"miny"`, and `"moe"`.
1206
1207```
1208INSTANTIATE_TEST_CASE_P(InstantiationName,
1209                        FooTest,
1210                        ::testing::Values("meeny", "miny", "moe"));
1211```
1212
1213To distinguish different instances of the pattern (yes, you can
1214instantiate it more than once), the first argument to
1215`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual
1216test case name. Remember to pick unique prefixes for different
1217instantiations. The tests from the instantiation above will have these
1218names:
1219
1220  * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
1221  * `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
1222  * `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
1223  * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
1224  * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
1225  * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
1226
1227You can use these names in [--gtest\_filter](#Running_a_Subset_of_the_Tests.md).
1228
1229This statement will instantiate all tests from `FooTest` again, each
1230with parameter values `"cat"` and `"dog"`:
1231
1232```
1233const char* pets[] = {"cat", "dog"};
1234INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest,
1235                        ::testing::ValuesIn(pets));
1236```
1237
1238The tests from the instantiation above will have these names:
1239
1240  * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
1241  * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
1242  * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
1243  * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
1244
1245Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_
1246tests in the given test case, whether their definitions come before or
1247_after_ the `INSTANTIATE_TEST_CASE_P` statement.
1248
1249You can see
1250[these](http://code.google.com/p/googletest/source/browse/trunk/samples/sample7_unittest.cc)
1251[files](http://code.google.com/p/googletest/source/browse/trunk/samples/sample8_unittest.cc) for more examples.
1252
1253_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0.
1254
1255## Creating Value-Parameterized Abstract Tests ##
1256
1257In the above, we define and instantiate `FooTest` in the same source
1258file. Sometimes you may want to define value-parameterized tests in a
1259library and let other people instantiate them later. This pattern is
1260known as <i>abstract tests</i>. As an example of its application, when you
1261are designing an interface you can write a standard suite of abstract
1262tests (perhaps using a factory function as the test parameter) that
1263all implementations of the interface are expected to pass. When
1264someone implements the interface, he can instantiate your suite to get
1265all the interface-conformance tests for free.
1266
1267To define abstract tests, you should organize your code like this:
1268
1269  1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests.
1270  1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests.
1271
1272Once they are defined, you can instantiate them by including
1273`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking
1274with `foo_param_test.cc`. You can instantiate the same abstract test
1275case multiple times, possibly in different source files.
1276
1277# Typed Tests #
1278
1279Suppose you have multiple implementations of the same interface and
1280want to make sure that all of them satisfy some common requirements.
1281Or, you may have defined several types that are supposed to conform to
1282the same "concept" and you want to verify it.  In both cases, you want
1283the same test logic repeated for different types.
1284
1285While you can write one `TEST` or `TEST_F` for each type you want to
1286test (and you may even factor the test logic into a function template
1287that you invoke from the `TEST`), it's tedious and doesn't scale:
1288if you want _m_ tests over _n_ types, you'll end up writing _m\*n_
1289`TEST`s.
1290
1291_Typed tests_ allow you to repeat the same test logic over a list of
1292types.  You only need to write the test logic once, although you must
1293know the type list when writing typed tests.  Here's how you do it:
1294
1295First, define a fixture class template.  It should be parameterized
1296by a type.  Remember to derive it from `::testing::Test`:
1297
1298```
1299template <typename T>
1300class FooTest : public ::testing::Test {
1301 public:
1302  ...
1303  typedef std::list<T> List;
1304  static T shared_;
1305  T value_;
1306};
1307```
1308
1309Next, associate a list of types with the test case, which will be
1310repeated for each type in the list:
1311
1312```
1313typedef ::testing::Types<char, int, unsigned int> MyTypes;
1314TYPED_TEST_CASE(FooTest, MyTypes);
1315```
1316
1317The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse
1318correctly.  Otherwise the compiler will think that each comma in the
1319type list introduces a new macro argument.
1320
1321Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test
1322for this test case.  You can repeat this as many times as you want:
1323
1324```
1325TYPED_TEST(FooTest, DoesBlah) {
1326  // Inside a test, refer to the special name TypeParam to get the type
1327  // parameter.  Since we are inside a derived class template, C++ requires
1328  // us to visit the members of FooTest via 'this'.
1329  TypeParam n = this->value_;
1330
1331  // To visit static members of the fixture, add the 'TestFixture::'
1332  // prefix.
1333  n += TestFixture::shared_;
1334
1335  // To refer to typedefs in the fixture, add the 'typename TestFixture::'
1336  // prefix.  The 'typename' is required to satisfy the compiler.
1337  typename TestFixture::List values;
1338  values.push_back(n);
1339  ...
1340}
1341
1342TYPED_TEST(FooTest, HasPropertyA) { ... }
1343```
1344
1345You can see `samples/sample6_unittest.cc` for a complete example.
1346
1347_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1348since version 1.1.0.
1349
1350# Type-Parameterized Tests #
1351
1352_Type-parameterized tests_ are like typed tests, except that they
1353don't require you to know the list of types ahead of time.  Instead,
1354you can define the test logic first and instantiate it with different
1355type lists later.  You can even instantiate it more than once in the
1356same program.
1357
1358If you are designing an interface or concept, you can define a suite
1359of type-parameterized tests to verify properties that any valid
1360implementation of the interface/concept should have.  Then, the author
1361of each implementation can just instantiate the test suite with his
1362type to verify that it conforms to the requirements, without having to
1363write similar tests repeatedly.  Here's an example:
1364
1365First, define a fixture class template, as we did with typed tests:
1366
1367```
1368template <typename T>
1369class FooTest : public ::testing::Test {
1370  ...
1371};
1372```
1373
1374Next, declare that you will define a type-parameterized test case:
1375
1376```
1377TYPED_TEST_CASE_P(FooTest);
1378```
1379
1380The `_P` suffix is for "parameterized" or "pattern", whichever you
1381prefer to think.
1382
1383Then, use `TYPED_TEST_P()` to define a type-parameterized test.  You
1384can repeat this as many times as you want:
1385
1386```
1387TYPED_TEST_P(FooTest, DoesBlah) {
1388  // Inside a test, refer to TypeParam to get the type parameter.
1389  TypeParam n = 0;
1390  ...
1391}
1392
1393TYPED_TEST_P(FooTest, HasPropertyA) { ... }
1394```
1395
1396Now the tricky part: you need to register all test patterns using the
1397`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them.
1398The first argument of the macro is the test case name; the rest are
1399the names of the tests in this test case:
1400
1401```
1402REGISTER_TYPED_TEST_CASE_P(FooTest,
1403                           DoesBlah, HasPropertyA);
1404```
1405
1406Finally, you are free to instantiate the pattern with the types you
1407want.  If you put the above code in a header file, you can `#include`
1408it in multiple C++ source files and instantiate it multiple times.
1409
1410```
1411typedef ::testing::Types<char, int, unsigned int> MyTypes;
1412INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
1413```
1414
1415To distinguish different instances of the pattern, the first argument
1416to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be
1417added to the actual test case name.  Remember to pick unique prefixes
1418for different instances.
1419
1420In the special case where the type list contains only one type, you
1421can write that type directly without `::testing::Types<...>`, like this:
1422
1423```
1424INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
1425```
1426
1427You can see `samples/sample6_unittest.cc` for a complete example.
1428
1429_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
1430since version 1.1.0.
1431
1432# Testing Private Code #
1433
1434If you change your software's internal implementation, your tests should not
1435break as long as the change is not observable by users. Therefore, per the
1436_black-box testing principle_, most of the time you should test your code
1437through its public interfaces.
1438
1439If you still find yourself needing to test internal implementation code,
1440consider if there's a better design that wouldn't require you to do so. If you
1441absolutely have to test non-public interface code though, you can. There are
1442two cases to consider:
1443
1444  * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and
1445  * Private or protected class members
1446
1447## Static Functions ##
1448
1449Both static functions and definitions/declarations in an unnamed namespace are
1450only visible within the same translation unit. To test them, you can `#include`
1451the entire `.cc` file being tested in your `*_test.cc` file. (#including `.cc`
1452files is not a good way to reuse code - you should not do this in production
1453code!)
1454
1455However, a better approach is to move the private code into the
1456`foo::internal` namespace, where `foo` is the namespace your project normally
1457uses, and put the private declarations in a `*-internal.h` file. Your
1458production `.cc` files and your tests are allowed to include this internal
1459header, but your clients are not. This way, you can fully test your internal
1460implementation without leaking it to your clients.
1461
1462## Private Class Members ##
1463
1464Private class members are only accessible from within the class or by friends.
1465To access a class' private members, you can declare your test fixture as a
1466friend to the class and define accessors in your fixture. Tests using the
1467fixture can then access the private members of your production class via the
1468accessors in the fixture. Note that even though your fixture is a friend to
1469your production class, your tests are not automatically friends to it, as they
1470are technically defined in sub-classes of the fixture.
1471
1472Another way to test private members is to refactor them into an implementation
1473class, which is then declared in a `*-internal.h` file. Your clients aren't
1474allowed to include this header but your tests can. Such is called the Pimpl
1475(Private Implementation) idiom.
1476
1477Or, you can declare an individual test as a friend of your class by adding this
1478line in the class body:
1479
1480```
1481FRIEND_TEST(TestCaseName, TestName);
1482```
1483
1484For example,
1485```
1486// foo.h
1487#include "gtest/gtest_prod.h"
1488
1489// Defines FRIEND_TEST.
1490class Foo {
1491  ...
1492 private:
1493  FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
1494  int Bar(void* x);
1495};
1496
1497// foo_test.cc
1498...
1499TEST(FooTest, BarReturnsZeroOnNull) {
1500  Foo foo;
1501  EXPECT_EQ(0, foo.Bar(NULL));
1502  // Uses Foo's private member Bar().
1503}
1504```
1505
1506Pay special attention when your class is defined in a namespace, as you should
1507define your test fixtures and tests in the same namespace if you want them to
1508be friends of your class. For example, if the code to be tested looks like:
1509
1510```
1511namespace my_namespace {
1512
1513class Foo {
1514  friend class FooTest;
1515  FRIEND_TEST(FooTest, Bar);
1516  FRIEND_TEST(FooTest, Baz);
1517  ...
1518  definition of the class Foo
1519  ...
1520};
1521
1522}  // namespace my_namespace
1523```
1524
1525Your test code should be something like:
1526
1527```
1528namespace my_namespace {
1529class FooTest : public ::testing::Test {
1530 protected:
1531  ...
1532};
1533
1534TEST_F(FooTest, Bar) { ... }
1535TEST_F(FooTest, Baz) { ... }
1536
1537}  // namespace my_namespace
1538```
1539
1540# Catching Failures #
1541
1542If you are building a testing utility on top of Google Test, you'll
1543want to test your utility.  What framework would you use to test it?
1544Google Test, of course.
1545
1546The challenge is to verify that your testing utility reports failures
1547correctly.  In frameworks that report a failure by throwing an
1548exception, you could catch the exception and assert on it.  But Google
1549Test doesn't use exceptions, so how do we test that a piece of code
1550generates an expected failure?
1551
1552`"gtest/gtest-spi.h"` contains some constructs to do this.  After
1553#including this header, you can use
1554
1555| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` |
1556|:--------------------------------------------------|
1557
1558to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure
1559whose message contains the given _substring_, or use
1560
1561| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` |
1562|:-----------------------------------------------------|
1563
1564if you are expecting a non-fatal (e.g. `EXPECT_*`) failure.
1565
1566For technical reasons, there are some caveats:
1567
1568  1. You cannot stream a failure message to either macro.
1569  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object.
1570  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value.
1571
1572_Note:_ Google Test is designed with threads in mind.  Once the
1573synchronization primitives in `"gtest/internal/gtest-port.h"` have
1574been implemented, Google Test will become thread-safe, meaning that
1575you can then use assertions in multiple threads concurrently.  Before
1576
1577that, however, Google Test only supports single-threaded usage.  Once
1578thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()`
1579will capture failures in the current thread only. If _statement_
1580creates new threads, failures in these threads will be ignored.  If
1581you want to capture failures from all threads instead, you should use
1582the following macros:
1583
1584| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1585|:-----------------------------------------------------------------|
1586| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
1587
1588# Getting the Current Test's Name #
1589
1590Sometimes a function may need to know the name of the currently running test.
1591For example, you may be using the `SetUp()` method of your test fixture to set
1592the golden file name based on which test is running. The `::testing::TestInfo`
1593class has this information:
1594
1595```
1596namespace testing {
1597
1598class TestInfo {
1599 public:
1600  // Returns the test case name and the test name, respectively.
1601  //
1602  // Do NOT delete or free the return value - it's managed by the
1603  // TestInfo class.
1604  const char* test_case_name() const;
1605  const char* name() const;
1606};
1607
1608}  // namespace testing
1609```
1610
1611
1612> To obtain a `TestInfo` object for the currently running test, call
1613`current_test_info()` on the `UnitTest` singleton object:
1614
1615```
1616// Gets information about the currently running test.
1617// Do NOT delete the returned object - it's managed by the UnitTest class.
1618const ::testing::TestInfo* const test_info =
1619  ::testing::UnitTest::GetInstance()->current_test_info();
1620printf("We are in test %s of test case %s.\n",
1621       test_info->name(), test_info->test_case_name());
1622```
1623
1624`current_test_info()` returns a null pointer if no test is running. In
1625particular, you cannot find the test case name in `TestCaseSetUp()`,
1626`TestCaseTearDown()` (where you know the test case name implicitly), or
1627functions called from them.
1628
1629_Availability:_ Linux, Windows, Mac.
1630
1631# Extending Google Test by Handling Test Events #
1632
1633Google Test provides an <b>event listener API</b> to let you receive
1634notifications about the progress of a test program and test
1635failures. The events you can listen to include the start and end of
1636the test program, a test case, or a test method, among others. You may
1637use this API to augment or replace the standard console output,
1638replace the XML output, or provide a completely different form of
1639output, such as a GUI or a database. You can also use test events as
1640checkpoints to implement a resource leak checker, for example.
1641
1642_Availability:_ Linux, Windows, Mac; since v1.4.0.
1643
1644## Defining Event Listeners ##
1645
1646To define a event listener, you subclass either
1647[testing::TestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#855)
1648or [testing::EmptyTestEventListener](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#905).
1649The former is an (abstract) interface, where <i>each pure virtual method<br>
1650can be overridden to handle a test event</i> (For example, when a test
1651starts, the `OnTestStart()` method will be called.). The latter provides
1652an empty implementation of all methods in the interface, such that a
1653subclass only needs to override the methods it cares about.
1654
1655When an event is fired, its context is passed to the handler function
1656as an argument. The following argument types are used:
1657  * [UnitTest](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#1007) reflects the state of the entire test program,
1658  * [TestCase](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#689) has information about a test case, which can contain one or more tests,
1659  * [TestInfo](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#599) contains the state of a test, and
1660  * [TestPartResult](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest-test-part.h#42) represents the result of a test assertion.
1661
1662An event handler function can examine the argument it receives to find
1663out interesting information about the event and the test program's
1664state.  Here's an example:
1665
1666```
1667  class MinimalistPrinter : public ::testing::EmptyTestEventListener {
1668    // Called before a test starts.
1669    virtual void OnTestStart(const ::testing::TestInfo& test_info) {
1670      printf("*** Test %s.%s starting.\n",
1671             test_info.test_case_name(), test_info.name());
1672    }
1673
1674    // Called after a failed assertion or a SUCCEED() invocation.
1675    virtual void OnTestPartResult(
1676        const ::testing::TestPartResult& test_part_result) {
1677      printf("%s in %s:%d\n%s\n",
1678             test_part_result.failed() ? "*** Failure" : "Success",
1679             test_part_result.file_name(),
1680             test_part_result.line_number(),
1681             test_part_result.summary());
1682    }
1683
1684    // Called after a test ends.
1685    virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
1686      printf("*** Test %s.%s ending.\n",
1687             test_info.test_case_name(), test_info.name());
1688    }
1689  };
1690```
1691
1692## Using Event Listeners ##
1693
1694To use the event listener you have defined, add an instance of it to
1695the Google Test event listener list (represented by class
1696[TestEventListeners](http://code.google.com/p/googletest/source/browse/trunk/include/gtest/gtest.h#929)
1697- note the "s" at the end of the name) in your
1698`main()` function, before calling `RUN_ALL_TESTS()`:
1699```
1700int main(int argc, char** argv) {
1701  ::testing::InitGoogleTest(&argc, argv);
1702  // Gets hold of the event listener list.
1703  ::testing::TestEventListeners& listeners =
1704      ::testing::UnitTest::GetInstance()->listeners();
1705  // Adds a listener to the end.  Google Test takes the ownership.
1706  listeners.Append(new MinimalistPrinter);
1707  return RUN_ALL_TESTS();
1708}
1709```
1710
1711There's only one problem: the default test result printer is still in
1712effect, so its output will mingle with the output from your minimalist
1713printer. To suppress the default printer, just release it from the
1714event listener list and delete it. You can do so by adding one line:
1715```
1716  ...
1717  delete listeners.Release(listeners.default_result_printer());
1718  listeners.Append(new MinimalistPrinter);
1719  return RUN_ALL_TESTS();
1720```
1721
1722Now, sit back and enjoy a completely different output from your
1723tests. For more details, you can read this
1724[sample](http://code.google.com/p/googletest/source/browse/trunk/samples/sample9_unittest.cc).
1725
1726You may append more than one listener to the list. When an `On*Start()`
1727or `OnTestPartResult()` event is fired, the listeners will receive it in
1728the order they appear in the list (since new listeners are added to
1729the end of the list, the default text printer and the default XML
1730generator will receive the event first). An `On*End()` event will be
1731received by the listeners in the _reverse_ order. This allows output by
1732listeners added later to be framed by output from listeners added
1733earlier.
1734
1735## Generating Failures in Listeners ##
1736
1737You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`,
1738`FAIL()`, etc) when processing an event. There are some restrictions:
1739
1740  1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively).
1741  1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure.
1742
1743When you add listeners to the listener list, you should put listeners
1744that handle `OnTestPartResult()` _before_ listeners that can generate
1745failures. This ensures that failures generated by the latter are
1746attributed to the right test by the former.
1747
1748We have a sample of failure-raising listener
1749[here](http://code.google.com/p/googletest/source/browse/trunk/samples/sample10_unittest.cc).
1750
1751# Running Test Programs: Advanced Options #
1752
1753Google Test test programs are ordinary executables. Once built, you can run
1754them directly and affect their behavior via the following environment variables
1755and/or command line flags. For the flags to work, your programs must call
1756`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
1757
1758To see a list of supported flags and their usage, please run your test
1759program with the `--help` flag.  You can also use `-h`, `-?`, or `/?`
1760for short.  This feature is added in version 1.3.0.
1761
1762If an option is specified both by an environment variable and by a
1763flag, the latter takes precedence.  Most of the options can also be
1764set/read in code: to access the value of command line flag
1765`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`.  A common pattern is
1766to set the value of a flag before calling `::testing::InitGoogleTest()`
1767to change the default value of the flag:
1768```
1769int main(int argc, char** argv) {
1770  // Disables elapsed time by default.
1771  ::testing::GTEST_FLAG(print_time) = false;
1772
1773  // This allows the user to override the flag on the command line.
1774  ::testing::InitGoogleTest(&argc, argv);
1775
1776  return RUN_ALL_TESTS();
1777}
1778```
1779
1780## Selecting Tests ##
1781
1782This section shows various options for choosing which tests to run.
1783
1784### Listing Test Names ###
1785
1786Sometimes it is necessary to list the available tests in a program before
1787running them so that a filter may be applied if needed. Including the flag
1788`--gtest_list_tests` overrides all other flags and lists tests in the following
1789format:
1790```
1791TestCase1.
1792  TestName1
1793  TestName2
1794TestCase2.
1795  TestName
1796```
1797
1798None of the tests listed are actually run if the flag is provided. There is no
1799corresponding environment variable for this flag.
1800
1801_Availability:_ Linux, Windows, Mac.
1802
1803### Running a Subset of the Tests ###
1804
1805By default, a Google Test program runs all tests the user has defined.
1806Sometimes, you want to run only a subset of the tests (e.g. for debugging or
1807quickly verifying a change). If you set the `GTEST_FILTER` environment variable
1808or the `--gtest_filter` flag to a filter string, Google Test will only run the
1809tests whose full names (in the form of `TestCaseName.TestName`) match the
1810filter.
1811
1812The format of a filter is a '`:`'-separated list of wildcard patterns (called
1813the positive patterns) optionally followed by a '`-`' and another
1814'`:`'-separated pattern list (called the negative patterns). A test matches the
1815filter if and only if it matches any of the positive patterns but does not
1816match any of the negative patterns.
1817
1818A pattern may contain `'*'` (matches any string) or `'?'` (matches any single
1819character). For convenience, the filter `'*-NegativePatterns'` can be also
1820written as `'-NegativePatterns'`.
1821
1822For example:
1823
1824  * `./foo_test` Has no flag, and thus runs all its tests.
1825  * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value.
1826  * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`.
1827  * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`.
1828  * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.
1829  * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`.
1830
1831_Availability:_ Linux, Windows, Mac.
1832
1833### Temporarily Disabling Tests ###
1834
1835If you have a broken test that you cannot fix right away, you can add the
1836`DISABLED_` prefix to its name. This will exclude it from execution. This is
1837better than commenting out the code or using `#if 0`, as disabled tests are
1838still compiled (and thus won't rot).
1839
1840If you need to disable all tests in a test case, you can either add `DISABLED_`
1841to the front of the name of each test, or alternatively add it to the front of
1842the test case name.
1843
1844For example, the following tests won't be run by Google Test, even though they
1845will still be compiled:
1846
1847```
1848// Tests that Foo does Abc.
1849TEST(FooTest, DISABLED_DoesAbc) { ... }
1850
1851class DISABLED_BarTest : public ::testing::Test { ... };
1852
1853// Tests that Bar does Xyz.
1854TEST_F(DISABLED_BarTest, DoesXyz) { ... }
1855```
1856
1857_Note:_ This feature should only be used for temporary pain-relief. You still
1858have to fix the disabled tests at a later date. As a reminder, Google Test will
1859print a banner warning you if a test program contains any disabled tests.
1860
1861_Tip:_ You can easily count the number of disabled tests you have
1862using `grep`. This number can be used as a metric for improving your
1863test quality.
1864
1865_Availability:_ Linux, Windows, Mac.
1866
1867### Temporarily Enabling Disabled Tests ###
1868
1869To include [disabled tests](#Temporarily_Disabling_Tests.md) in test
1870execution, just invoke the test program with the
1871`--gtest_also_run_disabled_tests` flag or set the
1872`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other
1873than `0`.  You can combine this with the
1874[--gtest\_filter](#Running_a_Subset_of_the_Tests.md) flag to further select
1875which disabled tests to run.
1876
1877_Availability:_ Linux, Windows, Mac; since version 1.3.0.
1878
1879## Repeating the Tests ##
1880
1881Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
1882will fail only 1% of the time, making it rather hard to reproduce the bug under
1883a debugger. This can be a major source of frustration.
1884
1885The `--gtest_repeat` flag allows you to repeat all (or selected) test methods
1886in a program many times. Hopefully, a flaky test will eventually fail and give
1887you a chance to debug. Here's how to use it:
1888
1889| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. |
1890|:---------------------------------|:--------------------------------------------------------|
1891| `$ foo_test --gtest_repeat=-1`   | A negative count means repeating forever.               |
1892| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. |
1893| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. |
1894
1895If your test program contains global set-up/tear-down code registered
1896using `AddGlobalTestEnvironment()`, it will be repeated in each
1897iteration as well, as the flakiness may be in it. You can also specify
1898the repeat count by setting the `GTEST_REPEAT` environment variable.
1899
1900_Availability:_ Linux, Windows, Mac.
1901
1902## Shuffling the Tests ##
1903
1904You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
1905environment variable to `1`) to run the tests in a program in a random
1906order. This helps to reveal bad dependencies between tests.
1907
1908By default, Google Test uses a random seed calculated from the current
1909time. Therefore you'll get a different order every time. The console
1910output includes the random seed value, such that you can reproduce an
1911order-related test failure later. To specify the random seed
1912explicitly, use the `--gtest_random_seed=SEED` flag (or set the
1913`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer
1914between 0 and 99999. The seed value 0 is special: it tells Google Test
1915to do the default behavior of calculating the seed from the current
1916time.
1917
1918If you combine this with `--gtest_repeat=N`, Google Test will pick a
1919different random seed and re-shuffle the tests in each iteration.
1920
1921_Availability:_ Linux, Windows, Mac; since v1.4.0.
1922
1923## Controlling Test Output ##
1924
1925This section teaches how to tweak the way test results are reported.
1926
1927### Colored Terminal Output ###
1928
1929Google Test can use colors in its terminal output to make it easier to spot
1930the separation between tests, and whether tests passed.
1931
1932You can set the GTEST\_COLOR environment variable or set the `--gtest_color`
1933command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
1934disable colors, or let Google Test decide. When the value is `auto`, Google
1935Test will use colors if and only if the output goes to a terminal and (on
1936non-Windows platforms) the `TERM` environment variable is set to `xterm` or
1937`xterm-color`.
1938
1939_Availability:_ Linux, Windows, Mac.
1940
1941### Suppressing the Elapsed Time ###
1942
1943By default, Google Test prints the time it takes to run each test.  To
1944suppress that, run the test program with the `--gtest_print_time=0`
1945command line flag.  Setting the `GTEST_PRINT_TIME` environment
1946variable to `0` has the same effect.
1947
1948_Availability:_ Linux, Windows, Mac.  (In Google Test 1.3.0 and lower,
1949the default behavior is that the elapsed time is **not** printed.)
1950
1951### Generating an XML Report ###
1952
1953Google Test can emit a detailed XML report to a file in addition to its normal
1954textual output. The report contains the duration of each test, and thus can
1955help you identify slow tests.
1956
1957To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
1958`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will
1959create the file at the given location. You can also just use the string
1960`"xml"`, in which case the output can be found in the `test_detail.xml` file in
1961the current directory.
1962
1963If you specify a directory (for example, `"xml:output/directory/"` on Linux or
1964`"xml:output\directory\"` on Windows), Google Test will create the XML file in
1965that directory, named after the test executable (e.g. `foo_test.xml` for test
1966program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
1967over from a previous run), Google Test will pick a different name (e.g.
1968`foo_test_1.xml`) to avoid overwriting it.
1969
1970The report uses the format described here.  It is based on the
1971`junitreport` Ant task and can be parsed by popular continuous build
1972systems like [Jenkins](http://jenkins-ci.org/). Since that format
1973was originally intended for Java, a little interpretation is required
1974to make it apply to Google Test tests, as shown here:
1975
1976```
1977<testsuites name="AllTests" ...>
1978  <testsuite name="test_case_name" ...>
1979    <testcase name="test_name" ...>
1980      <failure message="..."/>
1981      <failure message="..."/>
1982      <failure message="..."/>
1983    </testcase>
1984  </testsuite>
1985</testsuites>
1986```
1987
1988  * The root `<testsuites>` element corresponds to the entire test program.
1989  * `<testsuite>` elements correspond to Google Test test cases.
1990  * `<testcase>` elements correspond to Google Test test functions.
1991
1992For instance, the following program
1993
1994```
1995TEST(MathTest, Addition) { ... }
1996TEST(MathTest, Subtraction) { ... }
1997TEST(LogicTest, NonContradiction) { ... }
1998```
1999
2000could generate this report:
2001
2002```
2003<?xml version="1.0" encoding="UTF-8"?>
2004<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests">
2005  <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15">
2006    <testcase name="Addition" status="run" time="7" classname="">
2007      <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type=""/>
2008      <failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type=""/>
2009    </testcase>
2010    <testcase name="Subtraction" status="run" time="5" classname="">
2011    </testcase>
2012  </testsuite>
2013  <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5">
2014    <testcase name="NonContradiction" status="run" time="5" classname="">
2015    </testcase>
2016  </testsuite>
2017</testsuites>
2018```
2019
2020Things to note:
2021
2022  * The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed.
2023  * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds.
2024  * Each `<failure>` element corresponds to a single failed Google Test assertion.
2025  * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts.
2026
2027_Availability:_ Linux, Windows, Mac.
2028
2029## Controlling How Failures Are Reported ##
2030
2031### Turning Assertion Failures into Break-Points ###
2032
2033When running test programs under a debugger, it's very convenient if the
2034debugger can catch an assertion failure and automatically drop into interactive
2035mode. Google Test's _break-on-failure_ mode supports this behavior.
2036
2037To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
2038other than `0` . Alternatively, you can use the `--gtest_break_on_failure`
2039command line flag.
2040
2041_Availability:_ Linux, Windows, Mac.
2042
2043### Disabling Catching Test-Thrown Exceptions ###
2044
2045Google Test can be used either with or without exceptions enabled.  If
2046a test throws a C++ exception or (on Windows) a structured exception
2047(SEH), by default Google Test catches it, reports it as a test
2048failure, and continues with the next test method.  This maximizes the
2049coverage of a test run.  Also, on Windows an uncaught exception will
2050cause a pop-up window, so catching the exceptions allows you to run
2051the tests automatically.
2052
2053When debugging the test failures, however, you may instead want the
2054exceptions to be handled by the debugger, such that you can examine
2055the call stack when an exception is thrown.  To achieve that, set the
2056`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the
2057`--gtest_catch_exceptions=0` flag when running the tests.
2058
2059**Availability**: Linux, Windows, Mac.
2060
2061### Letting Another Testing Framework Drive ###
2062
2063If you work on a project that has already been using another testing
2064framework and is not ready to completely switch to Google Test yet,
2065you can get much of Google Test's benefit by using its assertions in
2066your existing tests.  Just change your `main()` function to look
2067like:
2068
2069```
2070#include "gtest/gtest.h"
2071
2072int main(int argc, char** argv) {
2073  ::testing::GTEST_FLAG(throw_on_failure) = true;
2074  // Important: Google Test must be initialized.
2075  ::testing::InitGoogleTest(&argc, argv);
2076
2077  ... whatever your existing testing framework requires ...
2078}
2079```
2080
2081With that, you can use Google Test assertions in addition to the
2082native assertions your testing framework provides, for example:
2083
2084```
2085void TestFooDoesBar() {
2086  Foo foo;
2087  EXPECT_LE(foo.Bar(1), 100);     // A Google Test assertion.
2088  CPPUNIT_ASSERT(foo.IsEmpty());  // A native assertion.
2089}
2090```
2091
2092If a Google Test assertion fails, it will print an error message and
2093throw an exception, which will be treated as a failure by your host
2094testing framework.  If you compile your code with exceptions disabled,
2095a failed Google Test assertion will instead exit your program with a
2096non-zero code, which will also signal a test failure to your test
2097runner.
2098
2099If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in
2100your `main()`, you can alternatively enable this feature by specifying
2101the `--gtest_throw_on_failure` flag on the command-line or setting the
2102`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value.
2103
2104Death tests are _not_ supported when other test framework is used to organize tests.
2105
2106_Availability:_ Linux, Windows, Mac; since v1.3.0.
2107
2108## Distributing Test Functions to Multiple Machines ##
2109
2110If you have more than one machine you can use to run a test program,
2111you might want to run the test functions in parallel and get the
2112result faster.  We call this technique _sharding_, where each machine
2113is called a _shard_.
2114
2115Google Test is compatible with test sharding.  To take advantage of
2116this feature, your test runner (not part of Google Test) needs to do
2117the following:
2118
2119  1. Allocate a number of machines (shards) to run the tests.
2120  1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards.  It must be the same for all shards.
2121  1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard.  Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`.
2122  1. Run the same test program on all shards.  When Google Test sees the above two environment variables, it will select a subset of the test functions to run.  Across all shards, each test function in the program will be run exactly once.
2123  1. Wait for all shards to finish, then collect and report the results.
2124
2125Your project may have tests that were written without Google Test and
2126thus don't understand this protocol.  In order for your test runner to
2127figure out which test supports sharding, it can set the environment
2128variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path.  If a
2129test program supports sharding, it will create this file to
2130acknowledge the fact (the actual contents of the file are not
2131important at this time; although we may stick some useful information
2132in it in the future.); otherwise it will not create it.
2133
2134Here's an example to make it clear.  Suppose you have a test program
2135`foo_test` that contains the following 5 test functions:
2136```
2137TEST(A, V)
2138TEST(A, W)
2139TEST(B, X)
2140TEST(B, Y)
2141TEST(B, Z)
2142```
2143and you have 3 machines at your disposal.  To run the test functions in
2144parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and
2145set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively.
2146Then you would run the same `foo_test` on each machine.
2147
2148Google Test reserves the right to change how the work is distributed
2149across the shards, but here's one possible scenario:
2150
2151  * Machine #0 runs `A.V` and `B.X`.
2152  * Machine #1 runs `A.W` and `B.Y`.
2153  * Machine #2 runs `B.Z`.
2154
2155_Availability:_ Linux, Windows, Mac; since version 1.3.0.
2156
2157# Fusing Google Test Source Files #
2158
2159Google Test's implementation consists of ~30 files (excluding its own
2160tests).  Sometimes you may want them to be packaged up in two files (a
2161`.h` and a `.cc`) instead, such that you can easily copy them to a new
2162machine and start hacking there.  For this we provide an experimental
2163Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0).
2164Assuming you have Python 2.4 or above installed on your machine, just
2165go to that directory and run
2166```
2167python fuse_gtest_files.py OUTPUT_DIR
2168```
2169
2170and you should see an `OUTPUT_DIR` directory being created with files
2171`gtest/gtest.h` and `gtest/gtest-all.cc` in it.  These files contain
2172everything you need to use Google Test.  Just copy them to anywhere
2173you want and you are ready to write tests.  You can use the
2174[scripts/test/Makefile](http://code.google.com/p/googletest/source/browse/trunk/scripts/test/Makefile)
2175file as an example on how to compile your tests against them.
2176
2177# Where to Go from Here #
2178
2179Congratulations! You've now learned more advanced Google Test tools and are
2180ready to tackle more complex testing tasks. If you want to dive even deeper, you
2181can read the [Frequently-Asked Questions](V1_7_FAQ.md).
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_7_Documentation.md
r0r249096
1This page lists all documentation wiki pages for Google Test **(the SVN trunk version)**
2-- **if you use a released version of Google Test, please read the
3documentation for that specific version instead.**
4
5  * [Primer](V1_7_Primer.md) -- start here if you are new to Google Test.
6  * [Samples](V1_7_Samples.md) -- learn from examples.
7  * [AdvancedGuide](V1_7_AdvancedGuide.md) -- learn more about Google Test.
8  * [XcodeGuide](V1_7_XcodeGuide.md) -- how to use Google Test in Xcode on Mac.
9  * [Frequently-Asked Questions](V1_7_FAQ.md) -- check here before asking a question on the mailing list.
10
11To contribute code to Google Test, read:
12
13  * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch.
14  * [PumpManual](V1_7_PumpManual.md) -- how we generate some of Google Test's source files.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_7_FAQ.md
r0r249096
1
2
3If you cannot find the answer to your question here, and you have read
4[Primer](V1_7_Primer.md) and [AdvancedGuide](V1_7_AdvancedGuide.md), send it to
5googletestframework@googlegroups.com.
6
7## Why should I use Google Test instead of my favorite C++ testing framework? ##
8
9First, let us say clearly that we don't want to get into the debate of
10which C++ testing framework is **the best**.  There exist many fine
11frameworks for writing C++ tests, and we have tremendous respect for
12the developers and users of them.  We don't think there is (or will
13be) a single best framework - you have to pick the right tool for the
14particular task you are tackling.
15
16We created Google Test because we couldn't find the right combination
17of features and conveniences in an existing framework to satisfy _our_
18needs.  The following is a list of things that _we_ like about Google
19Test.  We don't claim them to be unique to Google Test - rather, the
20combination of them makes Google Test the choice for us.  We hope this
21list can help you decide whether it is for you too.
22
23  * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc.  As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems.
24  * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle.
25  * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`.  It doesn't require a new set of macros or special functions.
26  * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them.
27  * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions.
28  * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop.
29  * You can decide which tests to run using name patterns.  This saves time when you want to quickly reproduce a test failure.
30  * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson.
31  * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Global_Set-Up_and_Tear-Down) and tests parameterized by [values](http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Value_Parameterized_Tests) or [types](http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Typed_Tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself.  In particular, you can:
32    * expand your testing vocabulary by defining [custom predicates](http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Predicate_Assertions_for_Better_Error_Messages),
33    * teach Google Test how to [print your types](http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values),
34    * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Catching_Failures), and
35    * reflect on the test cases or change the test output format by intercepting the [test events](http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events).
36
37## I'm getting warnings when compiling Google Test.  Would you fix them? ##
38
39We strive to minimize compiler warnings Google Test generates.  Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS.
40
41Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment:
42
43  * You may be using a different compiler as we use, or a different version of the same compiler.  We cannot possibly test for all compilers.
44  * You may be compiling on a different platform as we do.
45  * Your project may be using different compiler flags as we do.
46
47It is not always possible to make Google Test warning-free for everyone.  Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex.
48
49If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers.  That'll suppress warnings from Google Test headers.
50
51## Why should not test case names and test names contain underscore? ##
52
53Underscore (`_`) is special, as C++ reserves the following to be used by
54the compiler and the standard library:
55
56  1. any identifier that starts with an `_` followed by an upper-case letter, and
57  1. any identifier that containers two consecutive underscores (i.e. `__`) _anywhere_ in its name.
58
59User code is _prohibited_ from using such identifiers.
60
61Now let's look at what this means for `TEST` and `TEST_F`.
62
63Currently `TEST(TestCaseName, TestName)` generates a class named
64`TestCaseName_TestName_Test`.  What happens if `TestCaseName` or `TestName`
65contains `_`?
66
67  1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid.
68  1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid.
69  1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid.
70  1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid.
71
72So clearly `TestCaseName` and `TestName` cannot start or end with `_`
73(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't
74followed by an upper-case letter.  But that's getting complicated.  So
75for simplicity we just say that it cannot start with `_`.).
76
77It may seem fine for `TestCaseName` and `TestName` to contain `_` in the
78middle.  However, consider this:
79```
80TEST(Time, Flies_Like_An_Arrow) { ... }
81TEST(Time_Flies, Like_An_Arrow) { ... }
82```
83
84Now, the two `TEST`s will both generate the same class
85(`Time_Files_Like_An_Arrow_Test`).  That's not good.
86
87So for simplicity, we just ask the users to avoid `_` in `TestCaseName`
88and `TestName`.  The rule is more constraining than necessary, but it's
89simple and easy to remember.  It also gives Google Test some wiggle
90room in case its implementation needs to change in the future.
91
92If you violate the rule, there may not be immediately consequences,
93but your test may (just may) break with a new compiler (or a new
94version of the compiler you are using) or with a new version of Google
95Test.  Therefore it's best to follow the rule.
96
97## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ##
98
99In the early days, we said that you could install
100compiled Google Test libraries on `*`nix systems using `make install`.
101Then every user of your machine can write tests without
102recompiling Google Test.
103
104This seemed like a good idea, but it has a
105got-cha: every user needs to compile his tests using the _same_ compiler
106flags used to compile the installed Google Test libraries; otherwise
107he may run into undefined behaviors (i.e. the tests can behave
108strangely and may even crash for no obvious reasons).
109
110Why?  Because C++ has this thing called the One-Definition Rule: if
111two C++ source files contain different definitions of the same
112class/function/variable, and you link them together, you violate the
113rule.  The linker may or may not catch the error (in many cases it's
114not required by the C++ standard to catch the violation).  If it
115doesn't, you get strange run-time behaviors that are unexpected and
116hard to debug.
117
118If you compile Google Test and your test code using different compiler
119flags, they may see different definitions of the same
120class/function/variable (e.g. due to the use of `#if` in Google Test).
121Therefore, for your sanity, we recommend to avoid installing pre-compiled
122Google Test libraries.  Instead, each project should compile
123Google Test itself such that it can be sure that the same flags are
124used for both Google Test and the tests.
125
126## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ##
127
128(Answered by Trevor Robinson)
129
130Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or
131`msvc\gtest.sln`. Go through the migration wizard to migrate the
132solution and project files to Visual Studio 2008. Select
133`Configuration Manager...` from the `Build` menu. Select `<New...>` from
134the `Active solution platform` dropdown.  Select `x64` from the new
135platform dropdown, leave `Copy settings from` set to `Win32` and
136`Create new project platforms` checked, then click `OK`. You now have
137`Win32` and `x64` platform configurations, selectable from the
138`Standard` toolbar, which allow you to toggle between building 32-bit or
13964-bit binaries (or both at once using Batch Build).
140
141In order to prevent build output files from overwriting one another,
142you'll need to change the `Intermediate Directory` settings for the
143newly created platform configuration across all the projects. To do
144this, multi-select (e.g. using shift-click) all projects (but not the
145solution) in the `Solution Explorer`. Right-click one of them and
146select `Properties`. In the left pane, select `Configuration Properties`,
147and from the `Configuration` dropdown, select `All Configurations`.
148Make sure the selected platform is `x64`. For the
149`Intermediate Directory` setting, change the value from
150`$(PlatformName)\$(ConfigurationName)` to
151`$(OutDir)\$(ProjectName)`. Click `OK` and then build the
152solution. When the build is complete, the 64-bit binaries will be in
153the `msvc\x64\Debug` directory.
154
155## Can I use Google Test on MinGW? ##
156
157We haven't tested this ourselves, but Per Abrahamsen reported that he
158was able to compile and install Google Test successfully when using
159MinGW from Cygwin.  You'll need to configure it with:
160
161`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"`
162
163You should be able to replace the `-mno-cygwin` option with direct links
164to the real MinGW binaries, but we haven't tried that.
165
166Caveats:
167
168  * There are many warnings when compiling.
169  * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW.
170
171We also have reports on successful cross compilation of Google Test
172MinGW binaries on Linux using
173[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows)
174on the WxWidgets site.
175
176Please contact `googletestframework@googlegroups.com` if you are
177interested in improving the support for MinGW.
178
179## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ##
180
181Due to some peculiarity of C++, it requires some non-trivial template
182meta programming tricks to support using `NULL` as an argument of the
183`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where
184it's most needed (otherwise we make the implementation of Google Test
185harder to maintain and more error-prone than necessary).
186
187The `EXPECT_EQ()` macro takes the _expected_ value as its first
188argument and the _actual_ value as the second. It's reasonable that
189someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this
190indeed was requested several times. Therefore we implemented it.
191
192The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the
193assertion fails, you already know that `ptr` must be `NULL`, so it
194doesn't add any information to print ptr in this case. That means
195`EXPECT_TRUE(ptr != NULL)` works just as well.
196
197If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll
198have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`,
199we don't have a convention on the order of the two arguments for
200`EXPECT_NE`. This means using the template meta programming tricks
201twice in the implementation, making it even harder to understand and
202maintain. We believe the benefit doesn't justify the cost.
203
204Finally, with the growth of Google Mock's [matcher](http://code.google.com/p/googlemock/wiki/CookBook#Using_Matchers_in_Google_Test_Assertions) library, we are
205encouraging people to use the unified `EXPECT_THAT(value, matcher)`
206syntax more often in tests. One significant advantage of the matcher
207approach is that matchers can be easily combined to form new matchers,
208while the `EXPECT_NE`, etc, macros cannot be easily
209combined. Therefore we want to invest more in the matchers than in the
210`EXPECT_XX()` macros.
211
212## Does Google Test support running tests in parallel? ##
213
214Test runners tend to be tightly coupled with the build/test
215environment, and Google Test doesn't try to solve the problem of
216running tests in parallel.  Instead, we tried to make Google Test work
217nicely with test runners.  For example, Google Test's XML report
218contains the time spent on each test, and its `gtest_list_tests` and
219`gtest_filter` flags can be used for splitting the execution of test
220methods into multiple processes.  These functionalities can help the
221test runner run the tests in parallel.
222
223## Why don't Google Test run the tests in different threads to speed things up? ##
224
225It's difficult to write thread-safe code.  Most tests are not written
226with thread-safety in mind, and thus may not work correctly in a
227multi-threaded setting.
228
229If you think about it, it's already hard to make your code work when
230you know what other threads are doing.  It's much harder, and
231sometimes even impossible, to make your code work when you don't know
232what other threads are doing (remember that test methods can be added,
233deleted, or modified after your test was written).  If you want to run
234the tests in parallel, you'd better run them in different processes.
235
236## Why aren't Google Test assertions implemented using exceptions? ##
237
238Our original motivation was to be able to use Google Test in projects
239that disable exceptions.  Later we realized some additional benefits
240of this approach:
241
242  1. Throwing in a destructor is undefined behavior in C++.  Not using exceptions means Google Test's assertions are safe to use in destructors.
243  1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing.
244  1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code:
245```
246try { ... ASSERT_TRUE(...) ... }
247catch (...) { ... }
248```
249The above code will pass even if the `ASSERT_TRUE` throws.  While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test.
250
251The downside of not using exceptions is that `ASSERT_*` (implemented
252using `return`) will only abort the current function, not the current
253`TEST`.
254
255## Why do we use two different macros for tests with and without fixtures? ##
256
257Unfortunately, C++'s macro system doesn't allow us to use the same
258macro for both cases.  One possibility is to provide only one macro
259for tests with fixtures, and require the user to define an empty
260fixture sometimes:
261
262```
263class FooTest : public ::testing::Test {};
264
265TEST_F(FooTest, DoesThis) { ... }
266```
267or
268```
269typedef ::testing::Test FooTest;
270
271TEST_F(FooTest, DoesThat) { ... }
272```
273
274Yet, many people think this is one line too many. :-) Our goal was to
275make it really easy to write tests, so we tried to make simple tests
276trivial to create.  That means using a separate macro for such tests.
277
278We think neither approach is ideal, yet either of them is reasonable.
279In the end, it probably doesn't matter much either way.
280
281## Why don't we use structs as test fixtures? ##
282
283We like to use structs only when representing passive data.  This
284distinction between structs and classes is good for documenting the
285intent of the code's author.  Since test fixtures have logic like
286`SetUp()` and `TearDown()`, they are better defined as classes.
287
288## Why are death tests implemented as assertions instead of using a test runner? ##
289
290Our goal was to make death tests as convenient for a user as C++
291possibly allows.  In particular:
292
293  * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect.  The death test would be written in C++, while the runner spec may or may not be.  A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative.
294  * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn.
295  * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will.  You are not limited to one death test per test method. For example, you can write something like:
296```
297    if (FooCondition()) {
298      ASSERT_DEATH(Bar(), "blah");
299    } else {
300      ASSERT_EQ(5, Bar());
301    }
302```
303If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users.  The fewer artificial limitations the better.
304  * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information.  For example,
305```
306    const int count = GetCount();  // Only known at run time.
307    for (int i = 1; i <= count; i++) {
308      ASSERT_DEATH({
309        double* buffer = new double[i];
310        ... initializes buffer ...
311        Foo(buffer, i)
312      }, "blah blah");
313    }
314```
315The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility.
316
317Another interesting thing about `ASSERT_DEATH` is that it calls `fork()`
318to create a child process to run the death test.  This is lightening
319fast, as `fork()` uses copy-on-write pages and incurs almost zero
320overhead, and the child process starts from the user-supplied
321statement directly, skipping all global and local initialization and
322any code leading to the given statement.  If you launch the child
323process from scratch, it can take seconds just to load everything and
324start running if the test links to many libraries dynamically.
325
326## My death test modifies some state, but the change seems lost after the death test finishes. Why? ##
327
328Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
329expected crash won't kill the test program (i.e. the parent process). As a
330result, any in-memory side effects they incur are observable in their
331respective sub-processes, but not in the parent process. You can think of them
332as running in a parallel universe, more or less.
333
334## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ##
335
336If your class has a static data member:
337
338```
339// foo.h
340class Foo {
341  ...
342  static const int kBar = 100;
343};
344```
345
346You also need to define it _outside_ of the class body in `foo.cc`:
347
348```
349const int Foo::kBar;  // No initializer here.
350```
351
352Otherwise your code is **invalid C++**, and may break in unexpected ways. In
353particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc)
354will generate an "undefined reference" linker error.
355
356## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ##
357
358Google Test doesn't yet have good support for this kind of tests, or
359data-driven tests in general. We hope to be able to make improvements in this
360area soon.
361
362## Can I derive a test fixture from another? ##
363
364Yes.
365
366Each test fixture has a corresponding and same named test case. This means only
367one test case can use a particular fixture. Sometimes, however, multiple test
368cases may want to use the same or slightly different fixtures. For example, you
369may want to make sure that all of a GUI library's test cases don't leak
370important system resources like fonts and brushes.
371
372In Google Test, you share a fixture among test cases by putting the shared
373logic in a base test fixture, then deriving from that base a separate fixture
374for each test case that wants to use this common logic. You then use `TEST_F()`
375to write tests using each derived fixture.
376
377Typically, your code looks like this:
378
379```
380// Defines a base test fixture.
381class BaseTest : public ::testing::Test {
382  protected:
383   ...
384};
385
386// Derives a fixture FooTest from BaseTest.
387class FooTest : public BaseTest {
388  protected:
389    virtual void SetUp() {
390      BaseTest::SetUp();  // Sets up the base fixture first.
391      ... additional set-up work ...
392    }
393    virtual void TearDown() {
394      ... clean-up work for FooTest ...
395      BaseTest::TearDown();  // Remember to tear down the base fixture
396                             // after cleaning up FooTest!
397    }
398    ... functions and variables for FooTest ...
399};
400
401// Tests that use the fixture FooTest.
402TEST_F(FooTest, Bar) { ... }
403TEST_F(FooTest, Baz) { ... }
404
405... additional fixtures derived from BaseTest ...
406```
407
408If necessary, you can continue to derive test fixtures from a derived fixture.
409Google Test has no limit on how deep the hierarchy can be.
410
411For a complete example using derived test fixtures, see
412[sample5](http://code.google.com/p/googletest/source/browse/trunk/samples/sample5_unittest.cc).
413
414## My compiler complains "void value not ignored as it ought to be." What does this mean? ##
415
416You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
417`ASSERT_*()` can only be used in `void` functions.
418
419## My death test hangs (or seg-faults). How do I fix it? ##
420
421In Google Test, death tests are run in a child process and the way they work is
422delicate. To write death tests you really need to understand how they work.
423Please make sure you have read this.
424
425In particular, death tests don't like having multiple threads in the parent
426process. So the first thing you can try is to eliminate creating threads
427outside of `EXPECT_DEATH()`.
428
429Sometimes this is impossible as some library you must use may be creating
430threads before `main()` is even reached. In this case, you can try to minimize
431the chance of conflicts by either moving as many activities as possible inside
432`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
433leaving as few things as possible in it. Also, you can try to set the death
434test style to `"threadsafe"`, which is safer but slower, and see if it helps.
435
436If you go with thread-safe death tests, remember that they rerun the test
437program from the beginning in the child process. Therefore make sure your
438program can run side-by-side with itself and is deterministic.
439
440In the end, this boils down to good concurrent programming. You have to make
441sure that there is no race conditions or dead locks in your program. No silver
442bullet - sorry!
443
444## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ##
445
446The first thing to remember is that Google Test does not reuse the
447same test fixture object across multiple tests. For each `TEST_F`,
448Google Test will create a fresh test fixture object, _immediately_
449call `SetUp()`, run the test, call `TearDown()`, and then
450_immediately_ delete the test fixture object. Therefore, there is no
451need to write a `SetUp()` or `TearDown()` function if the constructor
452or destructor already does the job.
453
454You may still want to use `SetUp()/TearDown()` in the following cases:
455  * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions.
456  * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag.
457  * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`.
458
459## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
460
461If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
462overloaded or a template, the compiler will have trouble figuring out which
463overloaded version it should use. `ASSERT_PRED_FORMAT*` and
464`EXPECT_PRED_FORMAT*` don't have this problem.
465
466If you see this error, you might want to switch to
467`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
468message. If, however, that is not an option, you can resolve the problem by
469explicitly telling the compiler which version to pick.
470
471For example, suppose you have
472
473```
474bool IsPositive(int n) {
475  return n > 0;
476}
477bool IsPositive(double x) {
478  return x > 0;
479}
480```
481
482you will get a compiler error if you write
483
484```
485EXPECT_PRED1(IsPositive, 5);
486```
487
488However, this will work:
489
490```
491EXPECT_PRED1(*static_cast<bool (*)(int)>*(IsPositive), 5);
492```
493
494(The stuff inside the angled brackets for the `static_cast` operator is the
495type of the function pointer for the `int`-version of `IsPositive()`.)
496
497As another example, when you have a template function
498
499```
500template <typename T>
501bool IsNegative(T x) {
502  return x < 0;
503}
504```
505
506you can use it in a predicate assertion like this:
507
508```
509ASSERT_PRED1(IsNegative*<int>*, -5);
510```
511
512Things are more interesting if your template has more than one parameters. The
513following won't compile:
514
515```
516ASSERT_PRED2(*GreaterThan<int, int>*, 5, 0);
517```
518
519
520as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments,
521which is one more than expected. The workaround is to wrap the predicate
522function in parentheses:
523
524```
525ASSERT_PRED2(*(GreaterThan<int, int>)*, 5, 0);
526```
527
528
529## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ##
530
531Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
532instead of
533
534```
535return RUN_ALL_TESTS();
536```
537
538they write
539
540```
541RUN_ALL_TESTS();
542```
543
544This is wrong and dangerous. A test runner needs to see the return value of
545`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()`
546function ignores it, your test will be considered successful even if it has a
547Google Test assertion failure. Very bad.
548
549To help the users avoid this dangerous bug, the implementation of
550`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is
551ignored. If you see this warning, the fix is simple: just make sure its value
552is used as the return value of `main()`.
553
554## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ##
555
556Due to a peculiarity of C++, in order to support the syntax for streaming
557messages to an `ASSERT_*`, e.g.
558
559```
560ASSERT_EQ(1, Foo()) << "blah blah" << foo;
561```
562
563we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
564`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
565content of your constructor/destructor to a private void member function, or
566switch to `EXPECT_*()` if that works. This section in the user's guide explains
567it.
568
569## My set-up function is not called. Why? ##
570
571C++ is case-sensitive. It should be spelled as `SetUp()`.  Did you
572spell it as `Setup()`?
573
574Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
575wonder why it's never called.
576
577## How do I jump to the line of a failure in Emacs directly? ##
578
579Google Test's failure message format is understood by Emacs and many other
580IDEs, like acme and XCode. If a Google Test message is in a compilation buffer
581in Emacs, then it's clickable. You can now hit `enter` on a message to jump to
582the corresponding source code, or use `C-x `` to jump to the next failure.
583
584## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ##
585
586You don't have to. Instead of
587
588```
589class FooTest : public BaseTest {};
590
591TEST_F(FooTest, Abc) { ... }
592TEST_F(FooTest, Def) { ... }
593
594class BarTest : public BaseTest {};
595
596TEST_F(BarTest, Abc) { ... }
597TEST_F(BarTest, Def) { ... }
598```
599
600you can simply `typedef` the test fixtures:
601```
602typedef BaseTest FooTest;
603
604TEST_F(FooTest, Abc) { ... }
605TEST_F(FooTest, Def) { ... }
606
607typedef BaseTest BarTest;
608
609TEST_F(BarTest, Abc) { ... }
610TEST_F(BarTest, Def) { ... }
611```
612
613## The Google Test output is buried in a whole bunch of log messages. What do I do? ##
614
615The Google Test output is meant to be a concise and human-friendly report. If
616your test generates textual output itself, it will mix with the Google Test
617output, making it hard to read. However, there is an easy solution to this
618problem.
619
620Since most log messages go to stderr, we decided to let Google Test output go
621to stdout. This way, you can easily separate the two using redirection. For
622example:
623```
624./my_test > googletest_output.txt
625```
626
627## Why should I prefer test fixtures over global variables? ##
628
629There are several good reasons:
630  1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other.
631  1. Global variables pollute the global namespace.
632  1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common.
633
634## How do I test private class members without writing FRIEND\_TEST()s? ##
635
636You should try to write testable code, which means classes should be easily
637tested from their public interface. One way to achieve this is the Pimpl idiom:
638you move all private members of a class into a helper class, and make all
639members of the helper class public.
640
641You have several other options that don't require using `FRIEND_TEST`:
642  * Write the tests as members of the fixture class:
643```
644class Foo {
645  friend class FooTest;
646  ...
647};
648
649class FooTest : public ::testing::Test {
650 protected:
651  ...
652  void Test1() {...} // This accesses private members of class Foo.
653  void Test2() {...} // So does this one.
654};
655
656TEST_F(FooTest, Test1) {
657  Test1();
658}
659
660TEST_F(FooTest, Test2) {
661  Test2();
662}
663```
664  * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests:
665```
666class Foo {
667  friend class FooTest;
668  ...
669};
670
671class FooTest : public ::testing::Test {
672 protected:
673  ...
674  T1 get_private_member1(Foo* obj) {
675    return obj->private_member1_;
676  }
677};
678
679TEST_F(FooTest, Test1) {
680  ...
681  get_private_member1(x)
682  ...
683}
684```
685  * If the methods are declared **protected**, you can change their access level in a test-only subclass:
686```
687class YourClass {
688  ...
689 protected: // protected access for testability.
690  int DoSomethingReturningInt();
691  ...
692};
693
694// in the your_class_test.cc file:
695class TestableYourClass : public YourClass {
696  ...
697 public: using YourClass::DoSomethingReturningInt; // changes access rights
698  ...
699};
700
701TEST_F(YourClassTest, DoSomethingTest) {
702  TestableYourClass obj;
703  assertEquals(expected_value, obj.DoSomethingReturningInt());
704}
705```
706
707## How do I test private class static members without writing FRIEND\_TEST()s? ##
708
709We find private static methods clutter the header file.  They are
710implementation details and ideally should be kept out of a .h. So often I make
711them free functions instead.
712
713Instead of:
714```
715// foo.h
716class Foo {
717  ...
718 private:
719  static bool Func(int n);
720};
721
722// foo.cc
723bool Foo::Func(int n) { ... }
724
725// foo_test.cc
726EXPECT_TRUE(Foo::Func(12345));
727```
728
729You probably should better write:
730```
731// foo.h
732class Foo {
733  ...
734};
735
736// foo.cc
737namespace internal {
738  bool Func(int n) { ... }
739}
740
741// foo_test.cc
742namespace internal {
743  bool Func(int n);
744}
745
746EXPECT_TRUE(internal::Func(12345));
747```
748
749## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ##
750
751No. You can use a feature called [value-parameterized tests](V1_7_AdvancedGuide#Value_Parameterized_Tests.md) which
752lets you repeat your tests with different parameters, without defining it more than once.
753
754## How do I test a file that defines main()? ##
755
756To test a `foo.cc` file, you need to compile and link it into your unit test
757program. However, when the file contains a definition for the `main()`
758function, it will clash with the `main()` of your unit test, and will result in
759a build error.
760
761The right solution is to split it into three files:
762  1. `foo.h` which contains the declarations,
763  1. `foo.cc` which contains the definitions except `main()`, and
764  1. `foo_main.cc` which contains nothing but the definition of `main()`.
765
766Then `foo.cc` can be easily tested.
767
768If you are adding tests to an existing file and don't want an intrusive change
769like this, there is a hack: just include the entire `foo.cc` file in your unit
770test. For example:
771```
772// File foo_unittest.cc
773
774// The headers section
775...
776
777// Renames main() in foo.cc to make room for the unit test main()
778#define main FooMain
779
780#include "a/b/foo.cc"
781
782// The tests start here.
783...
784```
785
786
787However, please remember this is a hack and should only be used as the last
788resort.
789
790## What can the statement argument in ASSERT\_DEATH() be? ##
791
792`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used
793wherever `_statement_` is valid. So basically `_statement_` can be any C++
794statement that makes sense in the current context. In particular, it can
795reference global and/or local variables, and can be:
796  * a simple function call (often the case),
797  * a complex expression, or
798  * a compound statement.
799
800> Some examples are shown here:
801```
802// A death test can be a simple function call.
803TEST(MyDeathTest, FunctionCall) {
804  ASSERT_DEATH(Xyz(5), "Xyz failed");
805}
806
807// Or a complex expression that references variables and functions.
808TEST(MyDeathTest, ComplexExpression) {
809  const bool c = Condition();
810  ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
811               "(Func1|Method) failed");
812}
813
814// Death assertions can be used any where in a function. In
815// particular, they can be inside a loop.
816TEST(MyDeathTest, InsideLoop) {
817  // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
818  for (int i = 0; i < 5; i++) {
819    EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
820                   ::testing::Message() << "where i is " << i);
821  }
822}
823
824// A death assertion can contain a compound statement.
825TEST(MyDeathTest, CompoundStatement) {
826  // Verifies that at lease one of Bar(0), Bar(1), ..., and
827  // Bar(4) dies.
828  ASSERT_DEATH({
829    for (int i = 0; i < 5; i++) {
830      Bar(i);
831    }
832  },
833  "Bar has \\d+ errors");}
834```
835
836`googletest_unittest.cc` contains more examples if you are interested.
837
838## What syntax does the regular expression in ASSERT\_DEATH use? ##
839
840On POSIX systems, Google Test uses the POSIX Extended regular
841expression syntax
842(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
843On Windows, it uses a limited variant of regular expression
844syntax. For more details, see the
845[regular expression syntax](V1_7_AdvancedGuide#Regular_Expression_Syntax.md).
846
847## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ##
848
849Google Test needs to be able to create objects of your test fixture class, so
850it must have a default constructor. Normally the compiler will define one for
851you. However, there are cases where you have to define your own:
852  * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty.
853  * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.)
854
855## Why does ASSERT\_DEATH complain about previous threads that were already joined? ##
856
857With the Linux pthread library, there is no turning back once you cross the
858line from single thread to multiple threads. The first time you create a
859thread, a manager thread is created in addition, so you get 3, not 2, threads.
860Later when the thread you create joins the main thread, the thread count
861decrements by 1, but the manager thread will never be killed, so you still have
8622 threads, which means you cannot safely run a death test.
863
864The new NPTL thread library doesn't suffer from this problem, as it doesn't
865create a manager thread. However, if you don't control which machine your test
866runs on, you shouldn't depend on this.
867
868## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ##
869
870Google Test does not interleave tests from different test cases. That is, it
871runs all tests in one test case first, and then runs all tests in the next test
872case, and so on. Google Test does this because it needs to set up a test case
873before the first test in it is run, and tear it down afterwords. Splitting up
874the test case would require multiple set-up and tear-down processes, which is
875inefficient and makes the semantics unclean.
876
877If we were to determine the order of tests based on test name instead of test
878case name, then we would have a problem with the following situation:
879
880```
881TEST_F(FooTest, AbcDeathTest) { ... }
882TEST_F(FooTest, Uvw) { ... }
883
884TEST_F(BarTest, DefDeathTest) { ... }
885TEST_F(BarTest, Xyz) { ... }
886```
887
888Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
889interleave tests from different test cases, we need to run all tests in the
890`FooTest` case before running any test in the `BarTest` case. This contradicts
891with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
892
893## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ##
894
895You don't have to, but if you like, you may split up the test case into
896`FooTest` and `FooDeathTest`, where the names make it clear that they are
897related:
898
899```
900class FooTest : public ::testing::Test { ... };
901
902TEST_F(FooTest, Abc) { ... }
903TEST_F(FooTest, Def) { ... }
904
905typedef FooTest FooDeathTest;
906
907TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
908TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
909```
910
911## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ##
912
913If you use a user-defined type `FooType` in an assertion, you must make sure
914there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
915defined such that we can print a value of `FooType`.
916
917In addition, if `FooType` is declared in a name space, the `<<` operator also
918needs to be defined in the _same_ name space.
919
920## How do I suppress the memory leak messages on Windows? ##
921
922Since the statically initialized Google Test singleton requires allocations on
923the heap, the Visual C++ memory leak detector will report memory leaks at the
924end of the program run. The easiest way to avoid this is to use the
925`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
926statically initialized heap objects. See MSDN for more details and additional
927heap check/debug routines.
928
929## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ##
930
931You may get a number of the following linker error or warnings if you
932attempt to link your test project with the Google Test library when
933your project and the are not built using the same compiler settings.
934
935  * LNK2005: symbol already defined in object
936  * LNK4217: locally defined symbol 'symbol' imported in function 'function'
937  * LNK4049: locally defined symbol 'symbol' imported
938
939The Google Test project (gtest.vcproj) has the Runtime Library option
940set to /MT (use multi-threaded static libraries, /MTd for debug). If
941your project uses something else, for example /MD (use multi-threaded
942DLLs, /MDd for debug), you need to change the setting in the Google
943Test project to match your project's.
944
945To update this setting open the project properties in the Visual
946Studio IDE then select the branch Configuration Properties | C/C++ |
947Code Generation and change the option "Runtime Library".  You may also try
948using gtest-md.vcproj instead of gtest.vcproj.
949
950## I put my tests in a library and Google Test doesn't run them. What's happening? ##
951Have you read a
952[warning](http://code.google.com/p/googletest/wiki/V1_7_Primer#Important_note_for_Visual_C++_users) on
953the Google Test Primer page?
954
955## I want to use Google Test with Visual Studio but don't know where to start. ##
956Many people are in your position and one of the posted his solution to
957our mailing list. Here is his link:
958http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html.
959
960## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ##
961Google Test uses parts of the standard C++ library that SunStudio does not support.
962Our users reported success using alternative implementations. Try running the build after runing this commad:
963
964`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'`
965
966## How can my code detect if it is running in a test? ##
967
968If you write code that sniffs whether it's running in a test and does
969different things accordingly, you are leaking test-only logic into
970production code and there is no easy way to ensure that the test-only
971code paths aren't run by mistake in production.  Such cleverness also
972leads to
973[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug).
974Therefore we strongly advise against the practice, and Google Test doesn't
975provide a way to do it.
976
977In general, the recommended way to cause the code to behave
978differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html).
979You can inject different functionality from the test and from the
980production code.  Since your production code doesn't link in the
981for-test logic at all, there is no danger in accidentally running it.
982
983However, if you _really_, _really_, _really_ have no choice, and if
984you follow the rule of ending your test program names with `_test`,
985you can use the _horrible_ hack of sniffing your executable name
986(`argv[0]` in `main()`) to know whether the code is under test.
987
988## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ##
989
990In C++, macros don't obey namespaces.  Therefore two libraries that
991both define a macro of the same name will clash if you #include both
992definitions.  In case a Google Test macro clashes with another
993library, you can force Google Test to rename its macro to avoid the
994conflict.
995
996Specifically, if both Google Test and some other code define macro
997`FOO`, you can add
998```
999  -DGTEST_DONT_DEFINE_FOO=1
1000```
1001to the compiler flags to tell Google Test to change the macro's name
1002from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
1003```
1004  GTEST_TEST(SomeTest, DoesThis) { ... }
1005```
1006instead of
1007```
1008  TEST(SomeTest, DoesThis) { ... }
1009```
1010in order to define a test.
1011
1012Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file.
1013
1014
1015## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ##
1016
1017Yes.
1018
1019The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`).
1020
1021```
1022namespace foo {
1023TEST(CoolTest, DoSomething) {
1024  SUCCEED();
1025}
1026}  // namespace foo
1027
1028namespace bar {
1029TEST(CoolTest, DoSomething) {
1030  SUCCEED();
1031}
1032}  // namespace foo
1033```
1034
1035However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name.
1036
1037```
1038namespace foo {
1039class CoolTest : public ::testing::Test {};  // Fixture foo::CoolTest
1040TEST_F(CoolTest, DoSomething) {
1041  SUCCEED();
1042}
1043}  // namespace foo
1044
1045namespace bar {
1046class CoolTest : public ::testing::Test {};  // Fixture: bar::CoolTest
1047TEST_F(CoolTest, DoSomething) {
1048  SUCCEED();
1049}
1050}  // namespace foo
1051```
1052
1053## How do I build Google Testing Framework with Xcode 4? ##
1054
1055If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like
1056"Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](http://code.google.com/p/googletest/source/browse/trunk/README) file on how to resolve this.
1057
1058## My question is not covered in your FAQ! ##
1059
1060If you cannot find the answer to your question in this FAQ, there are
1061some other resources you can use:
1062
1063  1. read other [wiki pages](http://code.google.com/p/googletest/w/list),
1064  1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics),
1065  1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.).
1066
1067Please note that creating an issue in the
1068[issue tracker](http://code.google.com/p/googletest/issues/list) is _not_
1069a good way to get your answer, as it is monitored infrequently by a
1070very small number of people.
1071
1072When asking a question, it's helpful to provide as much of the
1073following information as possible (people cannot help you if there's
1074not enough information in your question):
1075
1076  * the version (or the revision number if you check out from SVN directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version),
1077  * your operating system,
1078  * the name and version of your compiler,
1079  * the complete command line flags you give to your compiler,
1080  * the complete compiler error messages (if the question is about compilation),
1081  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_7_Primer.md
r0r249096
1
2
3# Introduction: Why Google C++ Testing Framework? #
4
5_Google C++ Testing Framework_ helps you write better C++ tests.
6
7No matter whether you work on Linux, Windows, or a Mac, if you write C++ code,
8Google Test can help you.
9
10So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
11  1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests.  Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
12  1. Tests should be well _organized_ and reflect the structure of the tested code.  Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
13  1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral.  Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations.  (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
14  1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
15  1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_.  Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
16  1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
17
18Since Google C++ Testing Framework is based on the popular xUnit
19architecture, you'll feel right at home if you've used JUnit or PyUnit before.
20If not, it will take you about 10 minutes to learn the basics and get started.
21So let's go!
22
23_Note:_ We sometimes refer to Google C++ Testing Framework informally
24as _Google Test_.
25
26# Setting up a New Test Project #
27
28To write a test program using Google Test, you need to compile Google
29Test into a library and link your test with it.  We provide build
30files for some popular build systems: `msvc/` for Visual Studio,
31`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland
32C++ Builder, and the autotools script (deprecated) and
33`CMakeLists.txt` for CMake (recommended) in the Google Test root
34directory.  If your build system is not on this list, you can take a
35look at `make/Makefile` to learn how Google Test should be compiled
36(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT`
37and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT`
38is the Google Test root directory).
39
40Once you are able to compile the Google Test library, you should
41create a project or build target for your test program.  Make sure you
42have `GTEST_ROOT/include` in the header search path so that the
43compiler can find `"gtest/gtest.h"` when compiling your test.  Set up
44your test project to link with the Google Test library (for example,
45in Visual Studio, this is done by adding a dependency on
46`gtest.vcproj`).
47
48If you still have questions, take a look at how Google Test's own
49tests are built and use them as examples.
50
51# Basic Concepts #
52
53When using Google Test, you start by writing _assertions_, which are statements
54that check whether a condition is true. An assertion's result can be _success_,
55_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts
56the current function; otherwise the program continues normally.
57
58_Tests_ use assertions to verify the tested code's behavior. If a test crashes
59or has a failed assertion, then it _fails_; otherwise it _succeeds_.
60
61A _test case_ contains one or many tests. You should group your tests into test
62cases that reflect the structure of the tested code. When multiple tests in a
63test case need to share common objects and subroutines, you can put them into a
64_test fixture_ class.
65
66A _test program_ can contain multiple test cases.
67
68We'll now explain how to write a test program, starting at the individual
69assertion level and building up to tests and test cases.
70
71# Assertions #
72
73Google Test assertions are macros that resemble function calls. You test a
74class or function by making assertions about its behavior. When an assertion
75fails, Google Test prints the assertion's source file and line number location,
76along with a failure message. You may also supply a custom failure message
77which will be appended to Google Test's message.
78
79The assertions come in pairs that test the same thing but have different
80effects on the current function. `ASSERT_*` versions generate fatal failures
81when they fail, and **abort the current function**. `EXPECT_*` versions generate
82nonfatal failures, which don't abort the current function. Usually `EXPECT_*`
83are preferred, as they allow more than one failures to be reported in a test.
84However, you should use `ASSERT_*` if it doesn't make sense to continue when
85the assertion in question fails.
86
87Since a failed `ASSERT_*` returns from the current function immediately,
88possibly skipping clean-up code that comes after it, it may cause a space leak.
89Depending on the nature of the leak, it may or may not be worth fixing - so
90keep this in mind if you get a heap checker error in addition to assertion
91errors.
92
93To provide a custom failure message, simply stream it into the macro using the
94`<<` operator, or a sequence of such operators. An example:
95```
96ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
97
98for (int i = 0; i < x.size(); ++i) {
99  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
100}
101```
102
103Anything that can be streamed to an `ostream` can be streamed to an assertion
104macro--in particular, C strings and `string` objects. If a wide string
105(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
106streamed to an assertion, it will be translated to UTF-8 when printed.
107
108## Basic Assertions ##
109
110These assertions do basic true/false condition testing.
111| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
112|:--------------------|:-----------------------|:-------------|
113| `ASSERT_TRUE(`_condition_`)`;  | `EXPECT_TRUE(`_condition_`)`;   | _condition_ is true |
114| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`;  | _condition_ is false |
115
116Remember, when they fail, `ASSERT_*` yields a fatal failure and
117returns from the current function, while `EXPECT_*` yields a nonfatal
118failure, allowing the function to continue running. In either case, an
119assertion failure means its containing test fails.
120
121_Availability_: Linux, Windows, Mac.
122
123## Binary Comparison ##
124
125This section describes assertions that compare two values.
126
127| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
128|:--------------------|:-----------------------|:-------------|
129|`ASSERT_EQ(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ |
130|`ASSERT_NE(`_val1_`, `_val2_`);`      |`EXPECT_NE(`_val1_`, `_val2_`);`      | _val1_ `!=` _val2_ |
131|`ASSERT_LT(`_val1_`, `_val2_`);`      |`EXPECT_LT(`_val1_`, `_val2_`);`      | _val1_ `<` _val2_ |
132|`ASSERT_LE(`_val1_`, `_val2_`);`      |`EXPECT_LE(`_val1_`, `_val2_`);`      | _val1_ `<=` _val2_ |
133|`ASSERT_GT(`_val1_`, `_val2_`);`      |`EXPECT_GT(`_val1_`, `_val2_`);`      | _val1_ `>` _val2_ |
134|`ASSERT_GE(`_val1_`, `_val2_`);`      |`EXPECT_GE(`_val1_`, `_val2_`);`      | _val1_ `>=` _val2_ |
135
136In the event of a failure, Google Test prints both _val1_ and _val2_
137. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions
138we'll introduce later), you should put the expression you want to test
139in the position of _actual_, and put its expected value in _expected_,
140as Google Test's failure messages are optimized for this convention.
141
142Value arguments must be comparable by the assertion's comparison
143operator or you'll get a compiler error.  We used to require the
144arguments to support the `<<` operator for streaming to an `ostream`,
145but it's no longer necessary since v1.6.0 (if `<<` is supported, it
146will be called to print the arguments when the assertion fails;
147otherwise Google Test will attempt to print them in the best way it
148can. For more details and how to customize the printing of the
149arguments, see this Google Mock [recipe](http://code.google.com/p/googlemock/wiki/CookBook#Teaching_Google_Mock_How_to_Print_Your_Values).).
150
151These assertions can work with a user-defined type, but only if you define the
152corresponding comparison operator (e.g. `==`, `<`, etc).  If the corresponding
153operator is defined, prefer using the `ASSERT_*()` macros because they will
154print out not only the result of the comparison, but the two operands as well.
155
156Arguments are always evaluated exactly once. Therefore, it's OK for the
157arguments to have side effects. However, as with any ordinary C/C++ function,
158the arguments' evaluation order is undefined (i.e. the compiler is free to
159choose any order) and your code should not depend on any particular argument
160evaluation order.
161
162`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
163tests if they are in the same memory location, not if they have the same value.
164Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
165`ASSERT_STREQ()` , which will be described later on. In particular, to assert
166that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to
167compare two `string` objects, you should use `ASSERT_EQ`.
168
169Macros in this section work with both narrow and wide string objects (`string`
170and `wstring`).
171
172_Availability_: Linux, Windows, Mac.
173
174## String Comparison ##
175
176The assertions in this group compare two **C strings**. If you want to compare
177two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
178
179| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
180|:--------------------|:-----------------------|:-------------|
181| `ASSERT_STREQ(`_expected\_str_`, `_actual\_str_`);`    | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);`     | the two C strings have the same content |
182| `ASSERT_STRNE(`_str1_`, `_str2_`);`    | `EXPECT_STRNE(`_str1_`, `_str2_`);`     | the two C strings have different content |
183| `ASSERT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | the two C strings have the same content, ignoring case |
184| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case |
185
186Note that "CASE" in an assertion name means that case is ignored.
187
188`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a
189comparison of two wide strings fails, their values will be printed as UTF-8
190narrow strings.
191
192A `NULL` pointer and an empty string are considered _different_.
193
194_Availability_: Linux, Windows, Mac.
195
196See also: For more string comparison tricks (substring, prefix, suffix, and
197regular expression matching, for example), see the [Advanced Google Test Guide](V1_7_AdvancedGuide.md).
198
199# Simple Tests #
200
201To create a test:
202  1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value.
203  1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
204  1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
205
206```
207TEST(test_case_name, test_name) {
208 ... test body ...
209}
210```
211
212
213`TEST()` arguments go from general to specific. The _first_ argument is the
214name of the test case, and the _second_ argument is the test's name within the
215test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its
216individual name. Tests from different test cases can have the same individual
217name.
218
219For example, let's take a simple integer function:
220```
221int Factorial(int n); // Returns the factorial of n
222```
223
224A test case for this function might look like:
225```
226// Tests factorial of 0.
227TEST(FactorialTest, HandlesZeroInput) {
228  EXPECT_EQ(1, Factorial(0));
229}
230
231// Tests factorial of positive numbers.
232TEST(FactorialTest, HandlesPositiveInput) {
233  EXPECT_EQ(1, Factorial(1));
234  EXPECT_EQ(2, Factorial(2));
235  EXPECT_EQ(6, Factorial(3));
236  EXPECT_EQ(40320, Factorial(8));
237}
238```
239
240Google Test groups the test results by test cases, so logically-related tests
241should be in the same test case; in other words, the first argument to their
242`TEST()` should be the same. In the above example, we have two tests,
243`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
244case `FactorialTest`.
245
246_Availability_: Linux, Windows, Mac.
247
248# Test Fixtures: Using the Same Data Configuration for Multiple Tests #
249
250If you find yourself writing two or more tests that operate on similar data,
251you can use a _test fixture_. It allows you to reuse the same configuration of
252objects for several different tests.
253
254To create a fixture, just:
255  1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes.
256  1. Inside the class, declare any objects you plan to use.
257  1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you.
258  1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](http://code.google.com/p/googletest/wiki/V1_7_FAQ#Should_I_use_the_constructor/destructor_of_the_test_fixture_or_t).
259  1. If needed, define subroutines for your tests to share.
260
261When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
262access objects and subroutines in the test fixture:
263```
264TEST_F(test_case_name, test_name) {
265 ... test body ...
266}
267```
268
269Like `TEST()`, the first argument is the test case name, but for `TEST_F()`
270this must be the name of the test fixture class. You've probably guessed: `_F`
271is for fixture.
272
273Unfortunately, the C++ macro system does not allow us to create a single macro
274that can handle both types of tests. Using the wrong macro causes a compiler
275error.
276
277Also, you must first define a test fixture class before using it in a
278`TEST_F()`, or you'll get the compiler error "`virtual outside class
279declaration`".
280
281For each test defined with `TEST_F()`, Google Test will:
282  1. Create a _fresh_ test fixture at runtime
283  1. Immediately initialize it via `SetUp()` ,
284  1. Run the test
285  1. Clean up by calling `TearDown()`
286  1. Delete the test fixture.  Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
287
288As an example, let's write tests for a FIFO queue class named `Queue`, which
289has the following interface:
290```
291template <typename E> // E is the element type.
292class Queue {
293 public:
294  Queue();
295  void Enqueue(const E& element);
296  E* Dequeue(); // Returns NULL if the queue is empty.
297  size_t size() const;
298  ...
299};
300```
301
302First, define a fixture class. By convention, you should give it the name
303`FooTest` where `Foo` is the class being tested.
304```
305class QueueTest : public ::testing::Test {
306 protected:
307  virtual void SetUp() {
308    q1_.Enqueue(1);
309    q2_.Enqueue(2);
310    q2_.Enqueue(3);
311  }
312
313  // virtual void TearDown() {}
314
315  Queue<int> q0_;
316  Queue<int> q1_;
317  Queue<int> q2_;
318};
319```
320
321In this case, `TearDown()` is not needed since we don't have to clean up after
322each test, other than what's already done by the destructor.
323
324Now we'll write tests using `TEST_F()` and this fixture.
325```
326TEST_F(QueueTest, IsEmptyInitially) {
327  EXPECT_EQ(0, q0_.size());
328}
329
330TEST_F(QueueTest, DequeueWorks) {
331  int* n = q0_.Dequeue();
332  EXPECT_EQ(NULL, n);
333
334  n = q1_.Dequeue();
335  ASSERT_TRUE(n != NULL);
336  EXPECT_EQ(1, *n);
337  EXPECT_EQ(0, q1_.size());
338  delete n;
339
340  n = q2_.Dequeue();
341  ASSERT_TRUE(n != NULL);
342  EXPECT_EQ(2, *n);
343  EXPECT_EQ(1, q2_.size());
344  delete n;
345}
346```
347
348The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
349to use `EXPECT_*` when you want the test to continue to reveal more errors
350after the assertion failure, and use `ASSERT_*` when continuing after failure
351doesn't make sense. For example, the second assertion in the `Dequeue` test is
352`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later,
353which would lead to a segfault when `n` is `NULL`.
354
355When these tests run, the following happens:
356  1. Google Test constructs a `QueueTest` object (let's call it `t1` ).
357  1. `t1.SetUp()` initializes `t1` .
358  1. The first test ( `IsEmptyInitially` ) runs on `t1` .
359  1. `t1.TearDown()` cleans up after the test finishes.
360  1. `t1` is destructed.
361  1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test.
362
363_Availability_: Linux, Windows, Mac.
364
365_Note_: Google Test automatically saves all _Google Test_ flags when a test
366object is constructed, and restores them when it is destructed.
367
368# Invoking the Tests #
369
370`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
371
372After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files.
373
374When invoked, the `RUN_ALL_TESTS()` macro:
375  1. Saves the state of all  Google Test flags.
376  1. Creates a test fixture object for the first test.
377  1. Initializes it via `SetUp()`.
378  1. Runs the test on the fixture object.
379  1. Cleans up the fixture via `TearDown()`.
380  1. Deletes the fixture.
381  1. Restores the state of all Google Test flags.
382  1. Repeats the above steps for the next test, until all tests have run.
383
384In addition, if the text fixture's constructor generates a fatal failure in
385step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly,
386if step 3 generates a fatal failure, step 4 will be skipped.
387
388_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc`
389will give you a compiler error. The rationale for this design is that the
390automated testing service determines whether a test has passed based on its
391exit code, not on its stdout/stderr output; thus your `main()` function must
392return the value of `RUN_ALL_TESTS()`.
393
394Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once
395conflicts with some advanced Google Test features (e.g. thread-safe death
396tests) and thus is not supported.
397
398_Availability_: Linux, Windows, Mac.
399
400# Writing the main() Function #
401
402You can start from this boilerplate:
403```
404#include "this/package/foo.h"
405#include "gtest/gtest.h"
406
407namespace {
408
409// The fixture for testing class Foo.
410class FooTest : public ::testing::Test {
411 protected:
412  // You can remove any or all of the following functions if its body
413  // is empty.
414
415  FooTest() {
416    // You can do set-up work for each test here.
417  }
418
419  virtual ~FooTest() {
420    // You can do clean-up work that doesn't throw exceptions here.
421  }
422
423  // If the constructor and destructor are not enough for setting up
424  // and cleaning up each test, you can define the following methods:
425
426  virtual void SetUp() {
427    // Code here will be called immediately after the constructor (right
428    // before each test).
429  }
430
431  virtual void TearDown() {
432    // Code here will be called immediately after each test (right
433    // before the destructor).
434  }
435
436  // Objects declared here can be used by all tests in the test case for Foo.
437};
438
439// Tests that the Foo::Bar() method does Abc.
440TEST_F(FooTest, MethodBarDoesAbc) {
441  const string input_filepath = "this/package/testdata/myinputfile.dat";
442  const string output_filepath = "this/package/testdata/myoutputfile.dat";
443  Foo f;
444  EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
445}
446
447// Tests that Foo does Xyz.
448TEST_F(FooTest, DoesXyz) {
449  // Exercises the Xyz feature of Foo.
450}
451
452}  // namespace
453
454int main(int argc, char **argv) {
455  ::testing::InitGoogleTest(&argc, argv);
456  return RUN_ALL_TESTS();
457}
458```
459
460The `::testing::InitGoogleTest()` function parses the command line for Google
461Test flags, and removes all recognized flags. This allows the user to control a
462test program's behavior via various flags, which we'll cover in [AdvancedGuide](V1_7_AdvancedGuide.md).
463You must call this function before calling `RUN_ALL_TESTS()`, or the flags
464won't be properly initialized.
465
466On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
467in programs compiled in `UNICODE` mode as well.
468
469But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go.
470
471## Important note for Visual C++ users ##
472If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:
473```
474__declspec(dllexport) int PullInMyLibrary() { return 0; }
475```
476If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function:
477```
478int PullInMyLibrary();
479static int dummy = PullInMyLibrary();
480```
481This will keep your tests referenced and will make them register themselves at startup.
482
483In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.
484
485There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!
486
487# Where to Go from Here #
488
489Congratulations! You've learned the Google Test basics. You can start writing
490and running Google Test tests, read some [samples](V1_7_Samples.md), or continue with
491[AdvancedGuide](V1_7_AdvancedGuide.md), which describes many more useful Google Test features.
492
493# Known Limitations #
494
495Google Test is designed to be thread-safe.  The implementation is
496thread-safe on systems where the `pthreads` library is available.  It
497is currently _unsafe_ to use Google Test assertions from two threads
498concurrently on other systems (e.g. Windows).  In most tests this is
499not an issue as usually the assertions are done in the main thread. If
500you want to help, you can volunteer to implement the necessary
501synchronization primitives in `gtest-port.h` for your platform.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_7_PumpManual.md
r0r249096
1
2
3<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
4
5# The Problem #
6
7Template and macro libraries often need to define many classes,
8functions, or macros that vary only (or almost only) in the number of
9arguments they take. It's a lot of repetitive, mechanical, and
10error-prone work.
11
12Variadic templates and variadic macros can alleviate the problem.
13However, while both are being considered by the C++ committee, neither
14is in the standard yet or widely supported by compilers.  Thus they
15are often not a good choice, especially when your code needs to be
16portable. And their capabilities are still limited.
17
18As a result, authors of such libraries often have to write scripts to
19generate their implementation. However, our experience is that it's
20tedious to write such scripts, which tend to reflect the structure of
21the generated code poorly and are often hard to read and edit. For
22example, a small change needed in the generated code may require some
23non-intuitive, non-trivial changes in the script. This is especially
24painful when experimenting with the code.
25
26# Our Solution #
27
28Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
29Programming, or Practical Utility for Meta Programming, whichever you
30prefer) is a simple meta-programming tool for C++. The idea is that a
31programmer writes a `foo.pump` file which contains C++ code plus meta
32code that manipulates the C++ code. The meta code can handle
33iterations over a range, nested iterations, local meta variable
34definitions, simple arithmetic, and conditional expressions. You can
35view it as a small Domain-Specific Language. The meta language is
36designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode,
37for example) and concise, making Pump code intuitive and easy to
38maintain.
39
40## Highlights ##
41
42  * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms.
43  * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly.
44  * The format is human-readable and more concise than XML.
45  * The format works relatively well with Emacs' C++ mode.
46
47## Examples ##
48
49The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line):
50
51```
52$var n = 3     $$ Defines a meta variable n.
53$range i 0..n  $$ Declares the range of meta iterator i (inclusive).
54$for i [[
55               $$ Meta loop.
56// Foo$i does blah for $i-ary predicates.
57$range j 1..i
58template <size_t N $for j [[, typename A$j]]>
59class Foo$i {
60$if i == 0 [[
61  blah a;
62]] $elif i <= 2 [[
63  blah b;
64]] $else [[
65  blah c;
66]]
67};
68
69]]
70```
71
72will be translated by the Pump compiler to:
73
74```
75// Foo0 does blah for 0-ary predicates.
76template <size_t N>
77class Foo0 {
78  blah a;
79};
80
81// Foo1 does blah for 1-ary predicates.
82template <size_t N, typename A1>
83class Foo1 {
84  blah b;
85};
86
87// Foo2 does blah for 2-ary predicates.
88template <size_t N, typename A1, typename A2>
89class Foo2 {
90  blah b;
91};
92
93// Foo3 does blah for 3-ary predicates.
94template <size_t N, typename A1, typename A2, typename A3>
95class Foo3 {
96  blah c;
97};
98```
99
100In another example,
101
102```
103$range i 1..n
104Func($for i + [[a$i]]);
105$$ The text between i and [[ is the separator between iterations.
106```
107
108will generate one of the following lines (without the comments), depending on the value of `n`:
109
110```
111Func();              // If n is 0.
112Func(a1);            // If n is 1.
113Func(a1 + a2);       // If n is 2.
114Func(a1 + a2 + a3);  // If n is 3.
115// And so on...
116```
117
118## Constructs ##
119
120We support the following meta programming constructs:
121
122| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. |
123|:----------------|:-----------------------------------------------------------------------------------------------|
124| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later.          |
125| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`.         |
126| `$($)`          | Generates a single `$` character.                                                              |
127| `$id`           | Value of the named constant or iteration variable.                                             |
128| `$(exp)`        | Value of the expression.                                                                       |
129| `$if exp [[ code ]] else_branch` | Conditional.                                                                                   |
130| `[[ code ]]`    | Meta lexical block.                                                                            |
131| `cpp_code`      | Raw C++ code.                                                                                  |
132| `$$ comment`    | Meta comment.                                                                                  |
133
134**Note:** To give the user some freedom in formatting the Pump source
135code, Pump ignores a new-line character if it's right after `$for foo`
136or next to `[[` or `]]`. Without this rule you'll often be forced to write
137very long lines to get the desired output. Therefore sometimes you may
138need to insert an extra new-line in such places for a new-line to show
139up in your output.
140
141## Grammar ##
142
143```
144code ::= atomic_code*
145atomic_code ::= $var id = exp
146    | $var id = [[ code ]]
147    | $range id exp..exp
148    | $for id sep [[ code ]]
149    | $($)
150    | $id
151    | $(exp)
152    | $if exp [[ code ]] else_branch
153    | [[ code ]]
154    | cpp_code
155sep ::= cpp_code | empty_string
156else_branch ::= $else [[ code ]]
157    | $elif exp [[ code ]] else_branch
158    | empty_string
159exp ::= simple_expression_in_Python_syntax
160```
161
162## Code ##
163
164You can find the source code of Pump in [scripts/pump.py](http://code.google.com/p/googletest/source/browse/trunk/scripts/pump.py). It is still
165very unpolished and lacks automated tests, although it has been
166successfully used many times. If you find a chance to use it in your
167project, please let us know what you think!  We also welcome help on
168improving Pump.
169
170## Real Examples ##
171
172You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com).  The source file `foo.h.pump` generates `foo.h`.
173
174## Tips ##
175
176  * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1.
177  * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_7_Samples.md
r0r249096
1If you're like us, you'd like to look at some Google Test sample code.  The
2[samples folder](http://code.google.com/p/googletest/source/browse/#svn/trunk/samples) has a number of well-commented samples showing how to use a
3variety of Google Test features.
4
5  * [Sample #1](http://code.google.com/p/googletest/source/browse/trunk/samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions.
6  * [Sample #2](http://code.google.com/p/googletest/source/browse/trunk/samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions.
7  * [Sample #3](http://code.google.com/p/googletest/source/browse/trunk/samples/sample3_unittest.cc) uses a test fixture.
8  * [Sample #4](http://code.google.com/p/googletest/source/browse/trunk/samples/sample4_unittest.cc) is another basic example of using Google Test.
9  * [Sample #5](http://code.google.com/p/googletest/source/browse/trunk/samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it.
10  * [Sample #6](http://code.google.com/p/googletest/source/browse/trunk/samples/sample6_unittest.cc) demonstrates type-parameterized tests.
11  * [Sample #7](http://code.google.com/p/googletest/source/browse/trunk/samples/sample7_unittest.cc) teaches the basics of value-parameterized tests.
12  * [Sample #8](http://code.google.com/p/googletest/source/browse/trunk/samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests.
13  * [Sample #9](http://code.google.com/p/googletest/source/browse/trunk/samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results.
14  * [Sample #10](http://code.google.com/p/googletest/source/browse/trunk/samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/V1_7_XcodeGuide.md
r0r249096
1
2
3This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step.
4
5# Quick Start #
6
7Here is the quick guide for using Google Test in your Xcode project.
8
9  1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`
10  1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework.
11  1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests"
12  1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests"
13  1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests"
14  1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable.
15  1. Build and Go
16
17The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations.
18
19# Get the Source #
20
21Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command:
22
23```
24svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only
25```
26
27Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository.
28
29To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory.
30
31The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`).
32
33Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory.
34
35```
36[Computer:svn] user$ svn propget svn:externals trunk
37externals/src/googletest http://googletest.googlecode.com/svn/trunk
38```
39
40# Add the Framework to Your Project #
41
42The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below.
43
44  * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project.
45  * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below).
46
47# Make a Test Target #
48
49To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target.
50
51Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above.
52
53  * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library.
54  * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll  want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase.
55
56# Set Up the Executable Run Environment #
57
58Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework.
59
60If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this:
61
62```
63[Session started at 2008-08-15 06:23:57 -0600.]
64  dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest
65    Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest
66    Reason: image not found
67```
68
69To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH.
70
71# Build and Go #
72
73Now, when you click "Build and Go", the test will be executed. Dumping out something like this:
74
75```
76[Session started at 2008-08-06 06:36:13 -0600.]
77[==========] Running 2 tests from 1 test case.
78[----------] Global test environment set-up.
79[----------] 2 tests from WidgetInitializerTest
80[ RUN      ] WidgetInitializerTest.TestConstructor
81[       OK ] WidgetInitializerTest.TestConstructor
82[ RUN      ] WidgetInitializerTest.TestConversion
83[       OK ] WidgetInitializerTest.TestConversion
84[----------] Global test environment tear-down
85[==========] 2 tests from 1 test case ran.
86[  PASSED  ] 2 tests.
87
88The Debugger has exited with status 0. 
89```
90
91# Summary #
92
93Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment.
No newline at end of file
trunk/3rdparty/googletest/googletest/docs/XcodeGuide.md
r0r249096
1
2
3This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step.
4
5# Quick Start #
6
7Here is the quick guide for using Google Test in your Xcode project.
8
9  1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`
10  1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework.
11  1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests"
12  1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests"
13  1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests"
14  1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable.
15  1. Build and Go
16
17The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations.
18
19# Get the Source #
20
21Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command:
22
23```
24svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only
25```
26
27Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository.
28
29To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory.
30
31The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`).
32
33Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory.
34
35```
36[Computer:svn] user$ svn propget svn:externals trunk
37externals/src/googletest http://googletest.googlecode.com/svn/trunk
38```
39
40# Add the Framework to Your Project #
41
42The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below.
43
44  * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project.
45  * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below).
46
47# Make a Test Target #
48
49To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target.
50
51Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above.
52
53  * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library.
54  * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll  want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase.
55
56# Set Up the Executable Run Environment #
57
58Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework.
59
60If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this:
61
62```
63[Session started at 2008-08-15 06:23:57 -0600.]
64  dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest
65    Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest
66    Reason: image not found
67```
68
69To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH.
70
71# Build and Go #
72
73Now, when you click "Build and Go", the test will be executed. Dumping out something like this:
74
75```
76[Session started at 2008-08-06 06:36:13 -0600.]
77[==========] Running 2 tests from 1 test case.
78[----------] Global test environment set-up.
79[----------] 2 tests from WidgetInitializerTest
80[ RUN      ] WidgetInitializerTest.TestConstructor
81[       OK ] WidgetInitializerTest.TestConstructor
82[ RUN      ] WidgetInitializerTest.TestConversion
83[       OK ] WidgetInitializerTest.TestConversion
84[----------] Global test environment tear-down
85[==========] 2 tests from 1 test case ran.
86[  PASSED  ] 2 tests.
87
88The Debugger has exited with status 0. 
89```
90
91# Summary #
92
93Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment.
No newline at end of file
trunk/3rdparty/googletest/googletest/include/gtest/gtest-death-test.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file defines the public API for death tests.  It is
35// #included by gtest.h so a user doesn't need to include this
36// directly.
37
38#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
39#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
40
41#include "gtest/internal/gtest-death-test-internal.h"
42
43namespace testing {
44
45// This flag controls the style of death tests.  Valid values are "threadsafe",
46// meaning that the death test child process will re-execute the test binary
47// from the start, running only a single death test, or "fast",
48// meaning that the child process will execute the test logic immediately
49// after forking.
50GTEST_DECLARE_string_(death_test_style);
51
52#if GTEST_HAS_DEATH_TEST
53
54namespace internal {
55
56// Returns a Boolean value indicating whether the caller is currently
57// executing in the context of the death test child process.  Tools such as
58// Valgrind heap checkers may need this to modify their behavior in death
59// tests.  IMPORTANT: This is an internal utility.  Using it may break the
60// implementation of death tests.  User code MUST NOT use it.
61GTEST_API_ bool InDeathTestChild();
62
63}  // namespace internal
64
65// The following macros are useful for writing death tests.
66
67// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
68// executed:
69//
70//   1. It generates a warning if there is more than one active
71//   thread.  This is because it's safe to fork() or clone() only
72//   when there is a single thread.
73//
74//   2. The parent process clone()s a sub-process and runs the death
75//   test in it; the sub-process exits with code 0 at the end of the
76//   death test, if it hasn't exited already.
77//
78//   3. The parent process waits for the sub-process to terminate.
79//
80//   4. The parent process checks the exit code and error message of
81//   the sub-process.
82//
83// Examples:
84//
85//   ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
86//   for (int i = 0; i < 5; i++) {
87//     EXPECT_DEATH(server.ProcessRequest(i),
88//                  "Invalid request .* in ProcessRequest()")
89//                  << "Failed to die on request " << i;
90//   }
91//
92//   ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
93//
94//   bool KilledBySIGHUP(int exit_code) {
95//     return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
96//   }
97//
98//   ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
99//
100// On the regular expressions used in death tests:
101//
102//   On POSIX-compliant systems (*nix), we use the <regex.h> library,
103//   which uses the POSIX extended regex syntax.
104//
105//   On other platforms (e.g. Windows), we only support a simple regex
106//   syntax implemented as part of Google Test.  This limited
107//   implementation should be enough most of the time when writing
108//   death tests; though it lacks many features you can find in PCRE
109//   or POSIX extended regex syntax.  For example, we don't support
110//   union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
111//   repetition count ("x{5,7}"), among others.
112//
113//   Below is the syntax that we do support.  We chose it to be a
114//   subset of both PCRE and POSIX extended regex, so it's easy to
115//   learn wherever you come from.  In the following: 'A' denotes a
116//   literal character, period (.), or a single \\ escape sequence;
117//   'x' and 'y' denote regular expressions; 'm' and 'n' are for
118//   natural numbers.
119//
120//     c     matches any literal character c
121//     \\d   matches any decimal digit
122//     \\D   matches any character that's not a decimal digit
123//     \\f   matches \f
124//     \\n   matches \n
125//     \\r   matches \r
126//     \\s   matches any ASCII whitespace, including \n
127//     \\S   matches any character that's not a whitespace
128//     \\t   matches \t
129//     \\v   matches \v
130//     \\w   matches any letter, _, or decimal digit
131//     \\W   matches any character that \\w doesn't match
132//     \\c   matches any literal character c, which must be a punctuation
133//     .     matches any single character except \n
134//     A?    matches 0 or 1 occurrences of A
135//     A*    matches 0 or many occurrences of A
136//     A+    matches 1 or many occurrences of A
137//     ^     matches the beginning of a string (not that of each line)
138//     $     matches the end of a string (not that of each line)
139//     xy    matches x followed by y
140//
141//   If you accidentally use PCRE or POSIX extended regex features
142//   not implemented by us, you will get a run-time failure.  In that
143//   case, please try to rewrite your regular expression within the
144//   above syntax.
145//
146//   This implementation is *not* meant to be as highly tuned or robust
147//   as a compiled regex library, but should perform well enough for a
148//   death test, which already incurs significant overhead by launching
149//   a child process.
150//
151// Known caveats:
152//
153//   A "threadsafe" style death test obtains the path to the test
154//   program from argv[0] and re-executes it in the sub-process.  For
155//   simplicity, the current implementation doesn't search the PATH
156//   when launching the sub-process.  This means that the user must
157//   invoke the test program via a path that contains at least one
158//   path separator (e.g. path/to/foo_test and
159//   /absolute/path/to/bar_test are fine, but foo_test is not).  This
160//   is rarely a problem as people usually don't put the test binary
161//   directory in PATH.
162//
163// TODO(wan@google.com): make thread-safe death tests search the PATH.
164
165// Asserts that a given statement causes the program to exit, with an
166// integer exit status that satisfies predicate, and emitting error output
167// that matches regex.
168# define ASSERT_EXIT(statement, predicate, regex) \
169    GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
170
171// Like ASSERT_EXIT, but continues on to successive tests in the
172// test case, if any:
173# define EXPECT_EXIT(statement, predicate, regex) \
174    GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
175
176// Asserts that a given statement causes the program to exit, either by
177// explicitly exiting with a nonzero exit code or being killed by a
178// signal, and emitting error output that matches regex.
179# define ASSERT_DEATH(statement, regex) \
180    ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
181
182// Like ASSERT_DEATH, but continues on to successive tests in the
183// test case, if any:
184# define EXPECT_DEATH(statement, regex) \
185    EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
186
187// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
188
189// Tests that an exit code describes a normal exit with a given exit code.
190class GTEST_API_ ExitedWithCode {
191 public:
192  explicit ExitedWithCode(int exit_code);
193  bool operator()(int exit_status) const;
194 private:
195  // No implementation - assignment is unsupported.
196  void operator=(const ExitedWithCode& other);
197
198  const int exit_code_;
199};
200
201# if !GTEST_OS_WINDOWS
202// Tests that an exit code describes an exit due to termination by a
203// given signal.
204class GTEST_API_ KilledBySignal {
205 public:
206  explicit KilledBySignal(int signum);
207  bool operator()(int exit_status) const;
208 private:
209  const int signum_;
210};
211# endif  // !GTEST_OS_WINDOWS
212
213// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
214// The death testing framework causes this to have interesting semantics,
215// since the sideeffects of the call are only visible in opt mode, and not
216// in debug mode.
217//
218// In practice, this can be used to test functions that utilize the
219// LOG(DFATAL) macro using the following style:
220//
221// int DieInDebugOr12(int* sideeffect) {
222//   if (sideeffect) {
223//     *sideeffect = 12;
224//   }
225//   LOG(DFATAL) << "death";
226//   return 12;
227// }
228//
229// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) {
230//   int sideeffect = 0;
231//   // Only asserts in dbg.
232//   EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
233//
234// #ifdef NDEBUG
235//   // opt-mode has sideeffect visible.
236//   EXPECT_EQ(12, sideeffect);
237// #else
238//   // dbg-mode no visible sideeffect.
239//   EXPECT_EQ(0, sideeffect);
240// #endif
241// }
242//
243// This will assert that DieInDebugReturn12InOpt() crashes in debug
244// mode, usually due to a DCHECK or LOG(DFATAL), but returns the
245// appropriate fallback value (12 in this case) in opt mode. If you
246// need to test that a function has appropriate side-effects in opt
247// mode, include assertions against the side-effects.  A general
248// pattern for this is:
249//
250// EXPECT_DEBUG_DEATH({
251//   // Side-effects here will have an effect after this statement in
252//   // opt mode, but none in debug mode.
253//   EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
254// }, "death");
255//
256# ifdef NDEBUG
257
258#  define EXPECT_DEBUG_DEATH(statement, regex) \
259  GTEST_EXECUTE_STATEMENT_(statement, regex)
260
261#  define ASSERT_DEBUG_DEATH(statement, regex) \
262  GTEST_EXECUTE_STATEMENT_(statement, regex)
263
264# else
265
266#  define EXPECT_DEBUG_DEATH(statement, regex) \
267  EXPECT_DEATH(statement, regex)
268
269#  define ASSERT_DEBUG_DEATH(statement, regex) \
270  ASSERT_DEATH(statement, regex)
271
272# endif  // NDEBUG for EXPECT_DEBUG_DEATH
273#endif  // GTEST_HAS_DEATH_TEST
274
275// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
276// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
277// death tests are supported; otherwise they just issue a warning.  This is
278// useful when you are combining death test assertions with normal test
279// assertions in one test.
280#if GTEST_HAS_DEATH_TEST
281# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
282    EXPECT_DEATH(statement, regex)
283# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
284    ASSERT_DEATH(statement, regex)
285#else
286# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
287    GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, )
288# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
289    GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return)
290#endif
291
292}  // namespace testing
293
294#endif  // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest-message.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file defines the Message class.
35//
36// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
37// leave some internal implementation details in this header file.
38// They are clearly marked by comments like this:
39//
40//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
41//
42// Such code is NOT meant to be used by a user directly, and is subject
43// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
44// program!
45
46#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
47#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
48
49#include <limits>
50
51#include "gtest/internal/gtest-port.h"
52
53// Ensures that there is at least one operator<< in the global namespace.
54// See Message& operator<<(...) below for why.
55void operator<<(const testing::internal::Secret&, int);
56
57namespace testing {
58
59// The Message class works like an ostream repeater.
60//
61// Typical usage:
62//
63//   1. You stream a bunch of values to a Message object.
64//      It will remember the text in a stringstream.
65//   2. Then you stream the Message object to an ostream.
66//      This causes the text in the Message to be streamed
67//      to the ostream.
68//
69// For example;
70//
71//   testing::Message foo;
72//   foo << 1 << " != " << 2;
73//   std::cout << foo;
74//
75// will print "1 != 2".
76//
77// Message is not intended to be inherited from.  In particular, its
78// destructor is not virtual.
79//
80// Note that stringstream behaves differently in gcc and in MSVC.  You
81// can stream a NULL char pointer to it in the former, but not in the
82// latter (it causes an access violation if you do).  The Message
83// class hides this difference by treating a NULL char pointer as
84// "(null)".
85class GTEST_API_ Message {
86 private:
87  // The type of basic IO manipulators (endl, ends, and flush) for
88  // narrow streams.
89  typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
90
91 public:
92  // Constructs an empty Message.
93  Message();
94
95  // Copy constructor.
96  Message(const Message& msg) : ss_(new ::std::stringstream) {  // NOLINT
97    *ss_ << msg.GetString();
98  }
99
100  // Constructs a Message from a C-string.
101  explicit Message(const char* str) : ss_(new ::std::stringstream) {
102    *ss_ << str;
103  }
104
105#if GTEST_OS_SYMBIAN
106  // Streams a value (either a pointer or not) to this object.
107  template <typename T>
108  inline Message& operator <<(const T& value) {
109    StreamHelper(typename internal::is_pointer<T>::type(), value);
110    return *this;
111  }
112#else
113  // Streams a non-pointer value to this object.
114  template <typename T>
115  inline Message& operator <<(const T& val) {
116    // Some libraries overload << for STL containers.  These
117    // overloads are defined in the global namespace instead of ::std.
118    //
119    // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
120    // overloads are visible in either the std namespace or the global
121    // namespace, but not other namespaces, including the testing
122    // namespace which Google Test's Message class is in.
123    //
124    // To allow STL containers (and other types that has a << operator
125    // defined in the global namespace) to be used in Google Test
126    // assertions, testing::Message must access the custom << operator
127    // from the global namespace.  With this using declaration,
128    // overloads of << defined in the global namespace and those
129    // visible via Koenig lookup are both exposed in this function.
130    using ::operator <<;
131    *ss_ << val;
132    return *this;
133  }
134
135  // Streams a pointer value to this object.
136  //
137  // This function is an overload of the previous one.  When you
138  // stream a pointer to a Message, this definition will be used as it
139  // is more specialized.  (The C++ Standard, section
140  // [temp.func.order].)  If you stream a non-pointer, then the
141  // previous definition will be used.
142  //
143  // The reason for this overload is that streaming a NULL pointer to
144  // ostream is undefined behavior.  Depending on the compiler, you
145  // may get "0", "(nil)", "(null)", or an access violation.  To
146  // ensure consistent result across compilers, we always treat NULL
147  // as "(null)".
148  template <typename T>
149  inline Message& operator <<(T* const& pointer) {  // NOLINT
150    if (pointer == NULL) {
151      *ss_ << "(null)";
152    } else {
153      *ss_ << pointer;
154    }
155    return *this;
156  }
157#endif  // GTEST_OS_SYMBIAN
158
159  // Since the basic IO manipulators are overloaded for both narrow
160  // and wide streams, we have to provide this specialized definition
161  // of operator <<, even though its body is the same as the
162  // templatized version above.  Without this definition, streaming
163  // endl or other basic IO manipulators to Message will confuse the
164  // compiler.
165  Message& operator <<(BasicNarrowIoManip val) {
166    *ss_ << val;
167    return *this;
168  }
169
170  // Instead of 1/0, we want to see true/false for bool values.
171  Message& operator <<(bool b) {
172    return *this << (b ? "true" : "false");
173  }
174
175  // These two overloads allow streaming a wide C string to a Message
176  // using the UTF-8 encoding.
177  Message& operator <<(const wchar_t* wide_c_str);
178  Message& operator <<(wchar_t* wide_c_str);
179
180#if GTEST_HAS_STD_WSTRING
181  // Converts the given wide string to a narrow string using the UTF-8
182  // encoding, and streams the result to this Message object.
183  Message& operator <<(const ::std::wstring& wstr);
184#endif  // GTEST_HAS_STD_WSTRING
185
186#if GTEST_HAS_GLOBAL_WSTRING
187  // Converts the given wide string to a narrow string using the UTF-8
188  // encoding, and streams the result to this Message object.
189  Message& operator <<(const ::wstring& wstr);
190#endif  // GTEST_HAS_GLOBAL_WSTRING
191
192  // Gets the text streamed to this object so far as an std::string.
193  // Each '\0' character in the buffer is replaced with "\\0".
194  //
195  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
196  std::string GetString() const;
197
198 private:
199
200#if GTEST_OS_SYMBIAN
201  // These are needed as the Nokia Symbian Compiler cannot decide between
202  // const T& and const T* in a function template. The Nokia compiler _can_
203  // decide between class template specializations for T and T*, so a
204  // tr1::type_traits-like is_pointer works, and we can overload on that.
205  template <typename T>
206  inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) {
207    if (pointer == NULL) {
208      *ss_ << "(null)";
209    } else {
210      *ss_ << pointer;
211    }
212  }
213  template <typename T>
214  inline void StreamHelper(internal::false_type /*is_pointer*/,
215                           const T& value) {
216    // See the comments in Message& operator <<(const T&) above for why
217    // we need this using statement.
218    using ::operator <<;
219    *ss_ << value;
220  }
221#endif  // GTEST_OS_SYMBIAN
222
223  // We'll hold the text streamed to this object here.
224  const internal::scoped_ptr< ::std::stringstream> ss_;
225
226  // We declare (but don't implement) this to prevent the compiler
227  // from implementing the assignment operator.
228  void operator=(const Message&);
229};
230
231// Streams a Message to an ostream.
232inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
233  return os << sb.GetString();
234}
235
236namespace internal {
237
238// Converts a streamable value to an std::string.  A NULL pointer is
239// converted to "(null)".  When the input value is a ::string,
240// ::std::string, ::wstring, or ::std::wstring object, each NUL
241// character in it is replaced with "\\0".
242template <typename T>
243std::string StreamableToString(const T& streamable) {
244  return (Message() << streamable).GetString();
245}
246
247}  // namespace internal
248}  // namespace testing
249
250#endif  // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest-param-test.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gtest-param-test.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2008, Google Inc.
6// All rights reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33//
34// Authors: vladl@google.com (Vlad Losev)
35//
36// Macros and functions for implementing parameterized tests
37// in Google C++ Testing Framework (Google Test)
38//
39// This file is generated by a SCRIPT.  DO NOT EDIT BY HAND!
40//
41#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
42#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
43
44
45// Value-parameterized tests allow you to test your code with different
46// parameters without writing multiple copies of the same test.
47//
48// Here is how you use value-parameterized tests:
49
50#if 0
51
52// To write value-parameterized tests, first you should define a fixture
53// class. It is usually derived from testing::TestWithParam<T> (see below for
54// another inheritance scheme that's sometimes useful in more complicated
55// class hierarchies), where the type of your parameter values.
56// TestWithParam<T> is itself derived from testing::Test. T can be any
57// copyable type. If it's a raw pointer, you are responsible for managing the
58// lifespan of the pointed values.
59
60class FooTest : public ::testing::TestWithParam<const char*> {
61  // You can implement all the usual class fixture members here.
62};
63
64// Then, use the TEST_P macro to define as many parameterized tests
65// for this fixture as you want. The _P suffix is for "parameterized"
66// or "pattern", whichever you prefer to think.
67
68TEST_P(FooTest, DoesBlah) {
69  // Inside a test, access the test parameter with the GetParam() method
70  // of the TestWithParam<T> class:
71  EXPECT_TRUE(foo.Blah(GetParam()));
72  ...
73}
74
75TEST_P(FooTest, HasBlahBlah) {
76  ...
77}
78
79// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test
80// case with any set of parameters you want. Google Test defines a number
81// of functions for generating test parameters. They return what we call
82// (surprise!) parameter generators. Here is a  summary of them, which
83// are all in the testing namespace:
84//
85//
86//  Range(begin, end [, step]) - Yields values {begin, begin+step,
87//                               begin+step+step, ...}. The values do not
88//                               include end. step defaults to 1.
89//  Values(v1, v2, ..., vN)    - Yields values {v1, v2, ..., vN}.
90//  ValuesIn(container)        - Yields values from a C-style array, an STL
91//  ValuesIn(begin,end)          container, or an iterator range [begin, end).
92//  Bool()                     - Yields sequence {false, true}.
93//  Combine(g1, g2, ..., gN)   - Yields all combinations (the Cartesian product
94//                               for the math savvy) of the values generated
95//                               by the N generators.
96//
97// For more details, see comments at the definitions of these functions below
98// in this file.
99//
100// The following statement will instantiate tests from the FooTest test case
101// each with parameter values "meeny", "miny", and "moe".
102
103INSTANTIATE_TEST_CASE_P(InstantiationName,
104                        FooTest,
105                        Values("meeny", "miny", "moe"));
106
107// To distinguish different instances of the pattern, (yes, you
108// can instantiate it more then once) the first argument to the
109// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the
110// actual test case name. Remember to pick unique prefixes for different
111// instantiations. The tests from the instantiation above will have
112// these names:
113//
114//    * InstantiationName/FooTest.DoesBlah/0 for "meeny"
115//    * InstantiationName/FooTest.DoesBlah/1 for "miny"
116//    * InstantiationName/FooTest.DoesBlah/2 for "moe"
117//    * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
118//    * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
119//    * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
120//
121// You can use these names in --gtest_filter.
122//
123// This statement will instantiate all tests from FooTest again, each
124// with parameter values "cat" and "dog":
125
126const char* pets[] = {"cat", "dog"};
127INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
128
129// The tests from the instantiation above will have these names:
130//
131//    * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
132//    * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
133//    * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
134//    * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
135//
136// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests
137// in the given test case, whether their definitions come before or
138// AFTER the INSTANTIATE_TEST_CASE_P statement.
139//
140// Please also note that generator expressions (including parameters to the
141// generators) are evaluated in InitGoogleTest(), after main() has started.
142// This allows the user on one hand, to adjust generator parameters in order
143// to dynamically determine a set of tests to run and on the other hand,
144// give the user a chance to inspect the generated tests with Google Test
145// reflection API before RUN_ALL_TESTS() is executed.
146//
147// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
148// for more examples.
149//
150// In the future, we plan to publish the API for defining new parameter
151// generators. But for now this interface remains part of the internal
152// implementation and is subject to change.
153//
154//
155// A parameterized test fixture must be derived from testing::Test and from
156// testing::WithParamInterface<T>, where T is the type of the parameter
157// values. Inheriting from TestWithParam<T> satisfies that requirement because
158// TestWithParam<T> inherits from both Test and WithParamInterface. In more
159// complicated hierarchies, however, it is occasionally useful to inherit
160// separately from Test and WithParamInterface. For example:
161
162class BaseTest : public ::testing::Test {
163  // You can inherit all the usual members for a non-parameterized test
164  // fixture here.
165};
166
167class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
168  // The usual test fixture members go here too.
169};
170
171TEST_F(BaseTest, HasFoo) {
172  // This is an ordinary non-parameterized test.
173}
174
175TEST_P(DerivedTest, DoesBlah) {
176  // GetParam works just the same here as if you inherit from TestWithParam.
177  EXPECT_TRUE(foo.Blah(GetParam()));
178}
179
180#endif  // 0
181
182#include "gtest/internal/gtest-port.h"
183
184#if !GTEST_OS_SYMBIAN
185# include <utility>
186#endif
187
188// scripts/fuse_gtest.py depends on gtest's own header being #included
189// *unconditionally*.  Therefore these #includes cannot be moved
190// inside #if GTEST_HAS_PARAM_TEST.
191#include "gtest/internal/gtest-internal.h"
192#include "gtest/internal/gtest-param-util.h"
193#include "gtest/internal/gtest-param-util-generated.h"
194
195#if GTEST_HAS_PARAM_TEST
196
197namespace testing {
198
199// Functions producing parameter generators.
200//
201// Google Test uses these generators to produce parameters for value-
202// parameterized tests. When a parameterized test case is instantiated
203// with a particular generator, Google Test creates and runs tests
204// for each element in the sequence produced by the generator.
205//
206// In the following sample, tests from test case FooTest are instantiated
207// each three times with parameter values 3, 5, and 8:
208//
209// class FooTest : public TestWithParam<int> { ... };
210//
211// TEST_P(FooTest, TestThis) {
212// }
213// TEST_P(FooTest, TestThat) {
214// }
215// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8));
216//
217
218// Range() returns generators providing sequences of values in a range.
219//
220// Synopsis:
221// Range(start, end)
222//   - returns a generator producing a sequence of values {start, start+1,
223//     start+2, ..., }.
224// Range(start, end, step)
225//   - returns a generator producing a sequence of values {start, start+step,
226//     start+step+step, ..., }.
227// Notes:
228//   * The generated sequences never include end. For example, Range(1, 5)
229//     returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
230//     returns a generator producing {1, 3, 5, 7}.
231//   * start and end must have the same type. That type may be any integral or
232//     floating-point type or a user defined type satisfying these conditions:
233//     * It must be assignable (have operator=() defined).
234//     * It must have operator+() (operator+(int-compatible type) for
235//       two-operand version).
236//     * It must have operator<() defined.
237//     Elements in the resulting sequences will also have that type.
238//   * Condition start < end must be satisfied in order for resulting sequences
239//     to contain any elements.
240//
241template <typename T, typename IncrementT>
242internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
243  return internal::ParamGenerator<T>(
244      new internal::RangeGenerator<T, IncrementT>(start, end, step));
245}
246
247template <typename T>
248internal::ParamGenerator<T> Range(T start, T end) {
249  return Range(start, end, 1);
250}
251
252// ValuesIn() function allows generation of tests with parameters coming from
253// a container.
254//
255// Synopsis:
256// ValuesIn(const T (&array)[N])
257//   - returns a generator producing sequences with elements from
258//     a C-style array.
259// ValuesIn(const Container& container)
260//   - returns a generator producing sequences with elements from
261//     an STL-style container.
262// ValuesIn(Iterator begin, Iterator end)
263//   - returns a generator producing sequences with elements from
264//     a range [begin, end) defined by a pair of STL-style iterators. These
265//     iterators can also be plain C pointers.
266//
267// Please note that ValuesIn copies the values from the containers
268// passed in and keeps them to generate tests in RUN_ALL_TESTS().
269//
270// Examples:
271//
272// This instantiates tests from test case StringTest
273// each with C-string values of "foo", "bar", and "baz":
274//
275// const char* strings[] = {"foo", "bar", "baz"};
276// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings));
277//
278// This instantiates tests from test case StlStringTest
279// each with STL strings with values "a" and "b":
280//
281// ::std::vector< ::std::string> GetParameterStrings() {
282//   ::std::vector< ::std::string> v;
283//   v.push_back("a");
284//   v.push_back("b");
285//   return v;
286// }
287//
288// INSTANTIATE_TEST_CASE_P(CharSequence,
289//                         StlStringTest,
290//                         ValuesIn(GetParameterStrings()));
291//
292//
293// This will also instantiate tests from CharTest
294// each with parameter values 'a' and 'b':
295//
296// ::std::list<char> GetParameterChars() {
297//   ::std::list<char> list;
298//   list.push_back('a');
299//   list.push_back('b');
300//   return list;
301// }
302// ::std::list<char> l = GetParameterChars();
303// INSTANTIATE_TEST_CASE_P(CharSequence2,
304//                         CharTest,
305//                         ValuesIn(l.begin(), l.end()));
306//
307template <typename ForwardIterator>
308internal::ParamGenerator<
309  typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type>
310ValuesIn(ForwardIterator begin, ForwardIterator end) {
311  typedef typename ::testing::internal::IteratorTraits<ForwardIterator>
312      ::value_type ParamType;
313  return internal::ParamGenerator<ParamType>(
314      new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
315}
316
317template <typename T, size_t N>
318internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
319  return ValuesIn(array, array + N);
320}
321
322template <class Container>
323internal::ParamGenerator<typename Container::value_type> ValuesIn(
324    const Container& container) {
325  return ValuesIn(container.begin(), container.end());
326}
327
328// Values() allows generating tests from explicitly specified list of
329// parameters.
330//
331// Synopsis:
332// Values(T v1, T v2, ..., T vN)
333//   - returns a generator producing sequences with elements v1, v2, ..., vN.
334//
335// For example, this instantiates tests from test case BarTest each
336// with values "one", "two", and "three":
337//
338// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three"));
339//
340// This instantiates tests from test case BazTest each with values 1, 2, 3.5.
341// The exact type of values will depend on the type of parameter in BazTest.
342//
343// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
344//
345// Currently, Values() supports from 1 to 50 parameters.
346//
347template <typename T1>
348internal::ValueArray1<T1> Values(T1 v1) {
349  return internal::ValueArray1<T1>(v1);
350}
351
352template <typename T1, typename T2>
353internal::ValueArray2<T1, T2> Values(T1 v1, T2 v2) {
354  return internal::ValueArray2<T1, T2>(v1, v2);
355}
356
357template <typename T1, typename T2, typename T3>
358internal::ValueArray3<T1, T2, T3> Values(T1 v1, T2 v2, T3 v3) {
359  return internal::ValueArray3<T1, T2, T3>(v1, v2, v3);
360}
361
362template <typename T1, typename T2, typename T3, typename T4>
363internal::ValueArray4<T1, T2, T3, T4> Values(T1 v1, T2 v2, T3 v3, T4 v4) {
364  return internal::ValueArray4<T1, T2, T3, T4>(v1, v2, v3, v4);
365}
366
367template <typename T1, typename T2, typename T3, typename T4, typename T5>
368internal::ValueArray5<T1, T2, T3, T4, T5> Values(T1 v1, T2 v2, T3 v3, T4 v4,
369    T5 v5) {
370  return internal::ValueArray5<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5);
371}
372
373template <typename T1, typename T2, typename T3, typename T4, typename T5,
374    typename T6>
375internal::ValueArray6<T1, T2, T3, T4, T5, T6> Values(T1 v1, T2 v2, T3 v3,
376    T4 v4, T5 v5, T6 v6) {
377  return internal::ValueArray6<T1, T2, T3, T4, T5, T6>(v1, v2, v3, v4, v5, v6);
378}
379
380template <typename T1, typename T2, typename T3, typename T4, typename T5,
381    typename T6, typename T7>
382internal::ValueArray7<T1, T2, T3, T4, T5, T6, T7> Values(T1 v1, T2 v2, T3 v3,
383    T4 v4, T5 v5, T6 v6, T7 v7) {
384  return internal::ValueArray7<T1, T2, T3, T4, T5, T6, T7>(v1, v2, v3, v4, v5,
385      v6, v7);
386}
387
388template <typename T1, typename T2, typename T3, typename T4, typename T5,
389    typename T6, typename T7, typename T8>
390internal::ValueArray8<T1, T2, T3, T4, T5, T6, T7, T8> Values(T1 v1, T2 v2,
391    T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) {
392  return internal::ValueArray8<T1, T2, T3, T4, T5, T6, T7, T8>(v1, v2, v3, v4,
393      v5, v6, v7, v8);
394}
395
396template <typename T1, typename T2, typename T3, typename T4, typename T5,
397    typename T6, typename T7, typename T8, typename T9>
398internal::ValueArray9<T1, T2, T3, T4, T5, T6, T7, T8, T9> Values(T1 v1, T2 v2,
399    T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) {
400  return internal::ValueArray9<T1, T2, T3, T4, T5, T6, T7, T8, T9>(v1, v2, v3,
401      v4, v5, v6, v7, v8, v9);
402}
403
404template <typename T1, typename T2, typename T3, typename T4, typename T5,
405    typename T6, typename T7, typename T8, typename T9, typename T10>
406internal::ValueArray10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Values(T1 v1,
407    T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) {
408  return internal::ValueArray10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(v1,
409      v2, v3, v4, v5, v6, v7, v8, v9, v10);
410}
411
412template <typename T1, typename T2, typename T3, typename T4, typename T5,
413    typename T6, typename T7, typename T8, typename T9, typename T10,
414    typename T11>
415internal::ValueArray11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10,
416    T11> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
417    T10 v10, T11 v11) {
418  return internal::ValueArray11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10,
419      T11>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11);
420}
421
422template <typename T1, typename T2, typename T3, typename T4, typename T5,
423    typename T6, typename T7, typename T8, typename T9, typename T10,
424    typename T11, typename T12>
425internal::ValueArray12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
426    T12> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
427    T10 v10, T11 v11, T12 v12) {
428  return internal::ValueArray12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
429      T12>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12);
430}
431
432template <typename T1, typename T2, typename T3, typename T4, typename T5,
433    typename T6, typename T7, typename T8, typename T9, typename T10,
434    typename T11, typename T12, typename T13>
435internal::ValueArray13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
436    T13> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
437    T10 v10, T11 v11, T12 v12, T13 v13) {
438  return internal::ValueArray13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
439      T12, T13>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13);
440}
441
442template <typename T1, typename T2, typename T3, typename T4, typename T5,
443    typename T6, typename T7, typename T8, typename T9, typename T10,
444    typename T11, typename T12, typename T13, typename T14>
445internal::ValueArray14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
446    T14> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
447    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) {
448  return internal::ValueArray14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
449      T12, T13, T14>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13,
450      v14);
451}
452
453template <typename T1, typename T2, typename T3, typename T4, typename T5,
454    typename T6, typename T7, typename T8, typename T9, typename T10,
455    typename T11, typename T12, typename T13, typename T14, typename T15>
456internal::ValueArray15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
457    T14, T15> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8,
458    T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) {
459  return internal::ValueArray15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
460      T12, T13, T14, T15>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12,
461      v13, v14, v15);
462}
463
464template <typename T1, typename T2, typename T3, typename T4, typename T5,
465    typename T6, typename T7, typename T8, typename T9, typename T10,
466    typename T11, typename T12, typename T13, typename T14, typename T15,
467    typename T16>
468internal::ValueArray16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
469    T14, T15, T16> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7,
470    T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
471    T16 v16) {
472  return internal::ValueArray16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
473      T12, T13, T14, T15, T16>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11,
474      v12, v13, v14, v15, v16);
475}
476
477template <typename T1, typename T2, typename T3, typename T4, typename T5,
478    typename T6, typename T7, typename T8, typename T9, typename T10,
479    typename T11, typename T12, typename T13, typename T14, typename T15,
480    typename T16, typename T17>
481internal::ValueArray17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
482    T14, T15, T16, T17> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7,
483    T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
484    T16 v16, T17 v17) {
485  return internal::ValueArray17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
486      T12, T13, T14, T15, T16, T17>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10,
487      v11, v12, v13, v14, v15, v16, v17);
488}
489
490template <typename T1, typename T2, typename T3, typename T4, typename T5,
491    typename T6, typename T7, typename T8, typename T9, typename T10,
492    typename T11, typename T12, typename T13, typename T14, typename T15,
493    typename T16, typename T17, typename T18>
494internal::ValueArray18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
495    T14, T15, T16, T17, T18> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6,
496    T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
497    T16 v16, T17 v17, T18 v18) {
498  return internal::ValueArray18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
499      T12, T13, T14, T15, T16, T17, T18>(v1, v2, v3, v4, v5, v6, v7, v8, v9,
500      v10, v11, v12, v13, v14, v15, v16, v17, v18);
501}
502
503template <typename T1, typename T2, typename T3, typename T4, typename T5,
504    typename T6, typename T7, typename T8, typename T9, typename T10,
505    typename T11, typename T12, typename T13, typename T14, typename T15,
506    typename T16, typename T17, typename T18, typename T19>
507internal::ValueArray19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
508    T14, T15, T16, T17, T18, T19> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5,
509    T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14,
510    T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) {
511  return internal::ValueArray19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
512      T12, T13, T14, T15, T16, T17, T18, T19>(v1, v2, v3, v4, v5, v6, v7, v8,
513      v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19);
514}
515
516template <typename T1, typename T2, typename T3, typename T4, typename T5,
517    typename T6, typename T7, typename T8, typename T9, typename T10,
518    typename T11, typename T12, typename T13, typename T14, typename T15,
519    typename T16, typename T17, typename T18, typename T19, typename T20>
520internal::ValueArray20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
521    T14, T15, T16, T17, T18, T19, T20> Values(T1 v1, T2 v2, T3 v3, T4 v4,
522    T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13,
523    T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) {
524  return internal::ValueArray20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
525      T12, T13, T14, T15, T16, T17, T18, T19, T20>(v1, v2, v3, v4, v5, v6, v7,
526      v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20);
527}
528
529template <typename T1, typename T2, typename T3, typename T4, typename T5,
530    typename T6, typename T7, typename T8, typename T9, typename T10,
531    typename T11, typename T12, typename T13, typename T14, typename T15,
532    typename T16, typename T17, typename T18, typename T19, typename T20,
533    typename T21>
534internal::ValueArray21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
535    T14, T15, T16, T17, T18, T19, T20, T21> Values(T1 v1, T2 v2, T3 v3, T4 v4,
536    T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13,
537    T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) {
538  return internal::ValueArray21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
539      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(v1, v2, v3, v4, v5, v6,
540      v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21);
541}
542
543template <typename T1, typename T2, typename T3, typename T4, typename T5,
544    typename T6, typename T7, typename T8, typename T9, typename T10,
545    typename T11, typename T12, typename T13, typename T14, typename T15,
546    typename T16, typename T17, typename T18, typename T19, typename T20,
547    typename T21, typename T22>
548internal::ValueArray22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
549    T14, T15, T16, T17, T18, T19, T20, T21, T22> Values(T1 v1, T2 v2, T3 v3,
550    T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12,
551    T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20,
552    T21 v21, T22 v22) {
553  return internal::ValueArray22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
554      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22>(v1, v2, v3, v4,
555      v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19,
556      v20, v21, v22);
557}
558
559template <typename T1, typename T2, typename T3, typename T4, typename T5,
560    typename T6, typename T7, typename T8, typename T9, typename T10,
561    typename T11, typename T12, typename T13, typename T14, typename T15,
562    typename T16, typename T17, typename T18, typename T19, typename T20,
563    typename T21, typename T22, typename T23>
564internal::ValueArray23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
565    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> Values(T1 v1, T2 v2,
566    T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12,
567    T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20,
568    T21 v21, T22 v22, T23 v23) {
569  return internal::ValueArray23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
570      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23>(v1, v2, v3,
571      v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19,
572      v20, v21, v22, v23);
573}
574
575template <typename T1, typename T2, typename T3, typename T4, typename T5,
576    typename T6, typename T7, typename T8, typename T9, typename T10,
577    typename T11, typename T12, typename T13, typename T14, typename T15,
578    typename T16, typename T17, typename T18, typename T19, typename T20,
579    typename T21, typename T22, typename T23, typename T24>
580internal::ValueArray24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
581    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> Values(T1 v1, T2 v2,
582    T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12,
583    T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20,
584    T21 v21, T22 v22, T23 v23, T24 v24) {
585  return internal::ValueArray24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
586      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24>(v1, v2,
587      v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18,
588      v19, v20, v21, v22, v23, v24);
589}
590
591template <typename T1, typename T2, typename T3, typename T4, typename T5,
592    typename T6, typename T7, typename T8, typename T9, typename T10,
593    typename T11, typename T12, typename T13, typename T14, typename T15,
594    typename T16, typename T17, typename T18, typename T19, typename T20,
595    typename T21, typename T22, typename T23, typename T24, typename T25>
596internal::ValueArray25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
597    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Values(T1 v1,
598    T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11,
599    T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19,
600    T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) {
601  return internal::ValueArray25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
602      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25>(v1,
603      v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17,
604      v18, v19, v20, v21, v22, v23, v24, v25);
605}
606
607template <typename T1, typename T2, typename T3, typename T4, typename T5,
608    typename T6, typename T7, typename T8, typename T9, typename T10,
609    typename T11, typename T12, typename T13, typename T14, typename T15,
610    typename T16, typename T17, typename T18, typename T19, typename T20,
611    typename T21, typename T22, typename T23, typename T24, typename T25,
612    typename T26>
613internal::ValueArray26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
614    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
615    T26> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
616    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
617    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
618    T26 v26) {
619  return internal::ValueArray26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
620      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
621      T26>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15,
622      v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26);
623}
624
625template <typename T1, typename T2, typename T3, typename T4, typename T5,
626    typename T6, typename T7, typename T8, typename T9, typename T10,
627    typename T11, typename T12, typename T13, typename T14, typename T15,
628    typename T16, typename T17, typename T18, typename T19, typename T20,
629    typename T21, typename T22, typename T23, typename T24, typename T25,
630    typename T26, typename T27>
631internal::ValueArray27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
632    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
633    T27> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
634    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
635    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
636    T26 v26, T27 v27) {
637  return internal::ValueArray27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
638      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
639      T26, T27>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14,
640      v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27);
641}
642
643template <typename T1, typename T2, typename T3, typename T4, typename T5,
644    typename T6, typename T7, typename T8, typename T9, typename T10,
645    typename T11, typename T12, typename T13, typename T14, typename T15,
646    typename T16, typename T17, typename T18, typename T19, typename T20,
647    typename T21, typename T22, typename T23, typename T24, typename T25,
648    typename T26, typename T27, typename T28>
649internal::ValueArray28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
650    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
651    T28> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
652    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
653    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
654    T26 v26, T27 v27, T28 v28) {
655  return internal::ValueArray28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
656      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
657      T26, T27, T28>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13,
658      v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27,
659      v28);
660}
661
662template <typename T1, typename T2, typename T3, typename T4, typename T5,
663    typename T6, typename T7, typename T8, typename T9, typename T10,
664    typename T11, typename T12, typename T13, typename T14, typename T15,
665    typename T16, typename T17, typename T18, typename T19, typename T20,
666    typename T21, typename T22, typename T23, typename T24, typename T25,
667    typename T26, typename T27, typename T28, typename T29>
668internal::ValueArray29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
669    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
670    T29> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
671    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
672    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
673    T26 v26, T27 v27, T28 v28, T29 v29) {
674  return internal::ValueArray29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
675      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
676      T26, T27, T28, T29>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12,
677      v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26,
678      v27, v28, v29);
679}
680
681template <typename T1, typename T2, typename T3, typename T4, typename T5,
682    typename T6, typename T7, typename T8, typename T9, typename T10,
683    typename T11, typename T12, typename T13, typename T14, typename T15,
684    typename T16, typename T17, typename T18, typename T19, typename T20,
685    typename T21, typename T22, typename T23, typename T24, typename T25,
686    typename T26, typename T27, typename T28, typename T29, typename T30>
687internal::ValueArray30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
688    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
689    T29, T30> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8,
690    T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16,
691    T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24,
692    T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) {
693  return internal::ValueArray30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
694      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
695      T26, T27, T28, T29, T30>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11,
696      v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25,
697      v26, v27, v28, v29, v30);
698}
699
700template <typename T1, typename T2, typename T3, typename T4, typename T5,
701    typename T6, typename T7, typename T8, typename T9, typename T10,
702    typename T11, typename T12, typename T13, typename T14, typename T15,
703    typename T16, typename T17, typename T18, typename T19, typename T20,
704    typename T21, typename T22, typename T23, typename T24, typename T25,
705    typename T26, typename T27, typename T28, typename T29, typename T30,
706    typename T31>
707internal::ValueArray31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
708    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
709    T29, T30, T31> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7,
710    T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
711    T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23,
712    T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) {
713  return internal::ValueArray31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
714      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
715      T26, T27, T28, T29, T30, T31>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10,
716      v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24,
717      v25, v26, v27, v28, v29, v30, v31);
718}
719
720template <typename T1, typename T2, typename T3, typename T4, typename T5,
721    typename T6, typename T7, typename T8, typename T9, typename T10,
722    typename T11, typename T12, typename T13, typename T14, typename T15,
723    typename T16, typename T17, typename T18, typename T19, typename T20,
724    typename T21, typename T22, typename T23, typename T24, typename T25,
725    typename T26, typename T27, typename T28, typename T29, typename T30,
726    typename T31, typename T32>
727internal::ValueArray32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
728    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
729    T29, T30, T31, T32> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7,
730    T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
731    T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23,
732    T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31,
733    T32 v32) {
734  return internal::ValueArray32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
735      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
736      T26, T27, T28, T29, T30, T31, T32>(v1, v2, v3, v4, v5, v6, v7, v8, v9,
737      v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23,
738      v24, v25, v26, v27, v28, v29, v30, v31, v32);
739}
740
741template <typename T1, typename T2, typename T3, typename T4, typename T5,
742    typename T6, typename T7, typename T8, typename T9, typename T10,
743    typename T11, typename T12, typename T13, typename T14, typename T15,
744    typename T16, typename T17, typename T18, typename T19, typename T20,
745    typename T21, typename T22, typename T23, typename T24, typename T25,
746    typename T26, typename T27, typename T28, typename T29, typename T30,
747    typename T31, typename T32, typename T33>
748internal::ValueArray33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
749    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
750    T29, T30, T31, T32, T33> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6,
751    T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
752    T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23,
753    T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31,
754    T32 v32, T33 v33) {
755  return internal::ValueArray33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
756      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
757      T26, T27, T28, T29, T30, T31, T32, T33>(v1, v2, v3, v4, v5, v6, v7, v8,
758      v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23,
759      v24, v25, v26, v27, v28, v29, v30, v31, v32, v33);
760}
761
762template <typename T1, typename T2, typename T3, typename T4, typename T5,
763    typename T6, typename T7, typename T8, typename T9, typename T10,
764    typename T11, typename T12, typename T13, typename T14, typename T15,
765    typename T16, typename T17, typename T18, typename T19, typename T20,
766    typename T21, typename T22, typename T23, typename T24, typename T25,
767    typename T26, typename T27, typename T28, typename T29, typename T30,
768    typename T31, typename T32, typename T33, typename T34>
769internal::ValueArray34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
770    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
771    T29, T30, T31, T32, T33, T34> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5,
772    T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14,
773    T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22,
774    T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30,
775    T31 v31, T32 v32, T33 v33, T34 v34) {
776  return internal::ValueArray34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
777      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
778      T26, T27, T28, T29, T30, T31, T32, T33, T34>(v1, v2, v3, v4, v5, v6, v7,
779      v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22,
780      v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34);
781}
782
783template <typename T1, typename T2, typename T3, typename T4, typename T5,
784    typename T6, typename T7, typename T8, typename T9, typename T10,
785    typename T11, typename T12, typename T13, typename T14, typename T15,
786    typename T16, typename T17, typename T18, typename T19, typename T20,
787    typename T21, typename T22, typename T23, typename T24, typename T25,
788    typename T26, typename T27, typename T28, typename T29, typename T30,
789    typename T31, typename T32, typename T33, typename T34, typename T35>
790internal::ValueArray35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
791    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
792    T29, T30, T31, T32, T33, T34, T35> Values(T1 v1, T2 v2, T3 v3, T4 v4,
793    T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13,
794    T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21,
795    T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29,
796    T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) {
797  return internal::ValueArray35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
798      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
799      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35>(v1, v2, v3, v4, v5, v6,
800      v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21,
801      v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35);
802}
803
804template <typename T1, typename T2, typename T3, typename T4, typename T5,
805    typename T6, typename T7, typename T8, typename T9, typename T10,
806    typename T11, typename T12, typename T13, typename T14, typename T15,
807    typename T16, typename T17, typename T18, typename T19, typename T20,
808    typename T21, typename T22, typename T23, typename T24, typename T25,
809    typename T26, typename T27, typename T28, typename T29, typename T30,
810    typename T31, typename T32, typename T33, typename T34, typename T35,
811    typename T36>
812internal::ValueArray36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
813    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
814    T29, T30, T31, T32, T33, T34, T35, T36> Values(T1 v1, T2 v2, T3 v3, T4 v4,
815    T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13,
816    T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21,
817    T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29,
818    T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) {
819  return internal::ValueArray36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
820      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
821      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36>(v1, v2, v3, v4,
822      v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19,
823      v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33,
824      v34, v35, v36);
825}
826
827template <typename T1, typename T2, typename T3, typename T4, typename T5,
828    typename T6, typename T7, typename T8, typename T9, typename T10,
829    typename T11, typename T12, typename T13, typename T14, typename T15,
830    typename T16, typename T17, typename T18, typename T19, typename T20,
831    typename T21, typename T22, typename T23, typename T24, typename T25,
832    typename T26, typename T27, typename T28, typename T29, typename T30,
833    typename T31, typename T32, typename T33, typename T34, typename T35,
834    typename T36, typename T37>
835internal::ValueArray37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
836    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
837    T29, T30, T31, T32, T33, T34, T35, T36, T37> Values(T1 v1, T2 v2, T3 v3,
838    T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12,
839    T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20,
840    T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28,
841    T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36,
842    T37 v37) {
843  return internal::ValueArray37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
844      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
845      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37>(v1, v2, v3,
846      v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19,
847      v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33,
848      v34, v35, v36, v37);
849}
850
851template <typename T1, typename T2, typename T3, typename T4, typename T5,
852    typename T6, typename T7, typename T8, typename T9, typename T10,
853    typename T11, typename T12, typename T13, typename T14, typename T15,
854    typename T16, typename T17, typename T18, typename T19, typename T20,
855    typename T21, typename T22, typename T23, typename T24, typename T25,
856    typename T26, typename T27, typename T28, typename T29, typename T30,
857    typename T31, typename T32, typename T33, typename T34, typename T35,
858    typename T36, typename T37, typename T38>
859internal::ValueArray38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
860    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
861    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> Values(T1 v1, T2 v2,
862    T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12,
863    T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20,
864    T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28,
865    T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36,
866    T37 v37, T38 v38) {
867  return internal::ValueArray38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
868      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
869      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38>(v1, v2,
870      v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18,
871      v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32,
872      v33, v34, v35, v36, v37, v38);
873}
874
875template <typename T1, typename T2, typename T3, typename T4, typename T5,
876    typename T6, typename T7, typename T8, typename T9, typename T10,
877    typename T11, typename T12, typename T13, typename T14, typename T15,
878    typename T16, typename T17, typename T18, typename T19, typename T20,
879    typename T21, typename T22, typename T23, typename T24, typename T25,
880    typename T26, typename T27, typename T28, typename T29, typename T30,
881    typename T31, typename T32, typename T33, typename T34, typename T35,
882    typename T36, typename T37, typename T38, typename T39>
883internal::ValueArray39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
884    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
885    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Values(T1 v1, T2 v2,
886    T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12,
887    T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20,
888    T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28,
889    T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36,
890    T37 v37, T38 v38, T39 v39) {
891  return internal::ValueArray39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
892      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
893      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39>(v1,
894      v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17,
895      v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31,
896      v32, v33, v34, v35, v36, v37, v38, v39);
897}
898
899template <typename T1, typename T2, typename T3, typename T4, typename T5,
900    typename T6, typename T7, typename T8, typename T9, typename T10,
901    typename T11, typename T12, typename T13, typename T14, typename T15,
902    typename T16, typename T17, typename T18, typename T19, typename T20,
903    typename T21, typename T22, typename T23, typename T24, typename T25,
904    typename T26, typename T27, typename T28, typename T29, typename T30,
905    typename T31, typename T32, typename T33, typename T34, typename T35,
906    typename T36, typename T37, typename T38, typename T39, typename T40>
907internal::ValueArray40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
908    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
909    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Values(T1 v1,
910    T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11,
911    T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19,
912    T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27,
913    T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35,
914    T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) {
915  return internal::ValueArray40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
916      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
917      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
918      T40>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15,
919      v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29,
920      v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40);
921}
922
923template <typename T1, typename T2, typename T3, typename T4, typename T5,
924    typename T6, typename T7, typename T8, typename T9, typename T10,
925    typename T11, typename T12, typename T13, typename T14, typename T15,
926    typename T16, typename T17, typename T18, typename T19, typename T20,
927    typename T21, typename T22, typename T23, typename T24, typename T25,
928    typename T26, typename T27, typename T28, typename T29, typename T30,
929    typename T31, typename T32, typename T33, typename T34, typename T35,
930    typename T36, typename T37, typename T38, typename T39, typename T40,
931    typename T41>
932internal::ValueArray41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
933    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
934    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
935    T41> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
936    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
937    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
938    T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
939    T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) {
940  return internal::ValueArray41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
941      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
942      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
943      T40, T41>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14,
944      v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28,
945      v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41);
946}
947
948template <typename T1, typename T2, typename T3, typename T4, typename T5,
949    typename T6, typename T7, typename T8, typename T9, typename T10,
950    typename T11, typename T12, typename T13, typename T14, typename T15,
951    typename T16, typename T17, typename T18, typename T19, typename T20,
952    typename T21, typename T22, typename T23, typename T24, typename T25,
953    typename T26, typename T27, typename T28, typename T29, typename T30,
954    typename T31, typename T32, typename T33, typename T34, typename T35,
955    typename T36, typename T37, typename T38, typename T39, typename T40,
956    typename T41, typename T42>
957internal::ValueArray42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
958    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
959    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
960    T42> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
961    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
962    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
963    T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
964    T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
965    T42 v42) {
966  return internal::ValueArray42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
967      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
968      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
969      T40, T41, T42>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13,
970      v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27,
971      v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41,
972      v42);
973}
974
975template <typename T1, typename T2, typename T3, typename T4, typename T5,
976    typename T6, typename T7, typename T8, typename T9, typename T10,
977    typename T11, typename T12, typename T13, typename T14, typename T15,
978    typename T16, typename T17, typename T18, typename T19, typename T20,
979    typename T21, typename T22, typename T23, typename T24, typename T25,
980    typename T26, typename T27, typename T28, typename T29, typename T30,
981    typename T31, typename T32, typename T33, typename T34, typename T35,
982    typename T36, typename T37, typename T38, typename T39, typename T40,
983    typename T41, typename T42, typename T43>
984internal::ValueArray43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
985    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
986    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
987    T43> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
988    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
989    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
990    T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
991    T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
992    T42 v42, T43 v43) {
993  return internal::ValueArray43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
994      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
995      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
996      T40, T41, T42, T43>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12,
997      v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26,
998      v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40,
999      v41, v42, v43);
1000}
1001
1002template <typename T1, typename T2, typename T3, typename T4, typename T5,
1003    typename T6, typename T7, typename T8, typename T9, typename T10,
1004    typename T11, typename T12, typename T13, typename T14, typename T15,
1005    typename T16, typename T17, typename T18, typename T19, typename T20,
1006    typename T21, typename T22, typename T23, typename T24, typename T25,
1007    typename T26, typename T27, typename T28, typename T29, typename T30,
1008    typename T31, typename T32, typename T33, typename T34, typename T35,
1009    typename T36, typename T37, typename T38, typename T39, typename T40,
1010    typename T41, typename T42, typename T43, typename T44>
1011internal::ValueArray44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1012    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1013    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1014    T44> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1015    T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1016    T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1017    T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
1018    T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
1019    T42 v42, T43 v43, T44 v44) {
1020  return internal::ValueArray44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
1021      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1022      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1023      T40, T41, T42, T43, T44>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11,
1024      v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25,
1025      v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39,
1026      v40, v41, v42, v43, v44);
1027}
1028
1029template <typename T1, typename T2, typename T3, typename T4, typename T5,
1030    typename T6, typename T7, typename T8, typename T9, typename T10,
1031    typename T11, typename T12, typename T13, typename T14, typename T15,
1032    typename T16, typename T17, typename T18, typename T19, typename T20,
1033    typename T21, typename T22, typename T23, typename T24, typename T25,
1034    typename T26, typename T27, typename T28, typename T29, typename T30,
1035    typename T31, typename T32, typename T33, typename T34, typename T35,
1036    typename T36, typename T37, typename T38, typename T39, typename T40,
1037    typename T41, typename T42, typename T43, typename T44, typename T45>
1038internal::ValueArray45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1039    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1040    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1041    T44, T45> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8,
1042    T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16,
1043    T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24,
1044    T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32,
1045    T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40,
1046    T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) {
1047  return internal::ValueArray45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
1048      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1049      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1050      T40, T41, T42, T43, T44, T45>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10,
1051      v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24,
1052      v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38,
1053      v39, v40, v41, v42, v43, v44, v45);
1054}
1055
1056template <typename T1, typename T2, typename T3, typename T4, typename T5,
1057    typename T6, typename T7, typename T8, typename T9, typename T10,
1058    typename T11, typename T12, typename T13, typename T14, typename T15,
1059    typename T16, typename T17, typename T18, typename T19, typename T20,
1060    typename T21, typename T22, typename T23, typename T24, typename T25,
1061    typename T26, typename T27, typename T28, typename T29, typename T30,
1062    typename T31, typename T32, typename T33, typename T34, typename T35,
1063    typename T36, typename T37, typename T38, typename T39, typename T40,
1064    typename T41, typename T42, typename T43, typename T44, typename T45,
1065    typename T46>
1066internal::ValueArray46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1067    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1068    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1069    T44, T45, T46> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7,
1070    T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
1071    T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23,
1072    T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31,
1073    T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39,
1074    T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) {
1075  return internal::ValueArray46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
1076      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1077      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1078      T40, T41, T42, T43, T44, T45, T46>(v1, v2, v3, v4, v5, v6, v7, v8, v9,
1079      v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23,
1080      v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37,
1081      v38, v39, v40, v41, v42, v43, v44, v45, v46);
1082}
1083
1084template <typename T1, typename T2, typename T3, typename T4, typename T5,
1085    typename T6, typename T7, typename T8, typename T9, typename T10,
1086    typename T11, typename T12, typename T13, typename T14, typename T15,
1087    typename T16, typename T17, typename T18, typename T19, typename T20,
1088    typename T21, typename T22, typename T23, typename T24, typename T25,
1089    typename T26, typename T27, typename T28, typename T29, typename T30,
1090    typename T31, typename T32, typename T33, typename T34, typename T35,
1091    typename T36, typename T37, typename T38, typename T39, typename T40,
1092    typename T41, typename T42, typename T43, typename T44, typename T45,
1093    typename T46, typename T47>
1094internal::ValueArray47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1095    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1096    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1097    T44, T45, T46, T47> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7,
1098    T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
1099    T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23,
1100    T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31,
1101    T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39,
1102    T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) {
1103  return internal::ValueArray47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
1104      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1105      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1106      T40, T41, T42, T43, T44, T45, T46, T47>(v1, v2, v3, v4, v5, v6, v7, v8,
1107      v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23,
1108      v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37,
1109      v38, v39, v40, v41, v42, v43, v44, v45, v46, v47);
1110}
1111
1112template <typename T1, typename T2, typename T3, typename T4, typename T5,
1113    typename T6, typename T7, typename T8, typename T9, typename T10,
1114    typename T11, typename T12, typename T13, typename T14, typename T15,
1115    typename T16, typename T17, typename T18, typename T19, typename T20,
1116    typename T21, typename T22, typename T23, typename T24, typename T25,
1117    typename T26, typename T27, typename T28, typename T29, typename T30,
1118    typename T31, typename T32, typename T33, typename T34, typename T35,
1119    typename T36, typename T37, typename T38, typename T39, typename T40,
1120    typename T41, typename T42, typename T43, typename T44, typename T45,
1121    typename T46, typename T47, typename T48>
1122internal::ValueArray48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1123    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1124    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1125    T44, T45, T46, T47, T48> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6,
1126    T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15,
1127    T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23,
1128    T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31,
1129    T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39,
1130    T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47,
1131    T48 v48) {
1132  return internal::ValueArray48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
1133      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1134      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1135      T40, T41, T42, T43, T44, T45, T46, T47, T48>(v1, v2, v3, v4, v5, v6, v7,
1136      v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22,
1137      v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36,
1138      v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48);
1139}
1140
1141template <typename T1, typename T2, typename T3, typename T4, typename T5,
1142    typename T6, typename T7, typename T8, typename T9, typename T10,
1143    typename T11, typename T12, typename T13, typename T14, typename T15,
1144    typename T16, typename T17, typename T18, typename T19, typename T20,
1145    typename T21, typename T22, typename T23, typename T24, typename T25,
1146    typename T26, typename T27, typename T28, typename T29, typename T30,
1147    typename T31, typename T32, typename T33, typename T34, typename T35,
1148    typename T36, typename T37, typename T38, typename T39, typename T40,
1149    typename T41, typename T42, typename T43, typename T44, typename T45,
1150    typename T46, typename T47, typename T48, typename T49>
1151internal::ValueArray49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1152    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1153    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1154    T44, T45, T46, T47, T48, T49> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5,
1155    T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14,
1156    T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22,
1157    T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30,
1158    T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38,
1159    T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46,
1160    T47 v47, T48 v48, T49 v49) {
1161  return internal::ValueArray49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
1162      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1163      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1164      T40, T41, T42, T43, T44, T45, T46, T47, T48, T49>(v1, v2, v3, v4, v5, v6,
1165      v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21,
1166      v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35,
1167      v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49);
1168}
1169
1170template <typename T1, typename T2, typename T3, typename T4, typename T5,
1171    typename T6, typename T7, typename T8, typename T9, typename T10,
1172    typename T11, typename T12, typename T13, typename T14, typename T15,
1173    typename T16, typename T17, typename T18, typename T19, typename T20,
1174    typename T21, typename T22, typename T23, typename T24, typename T25,
1175    typename T26, typename T27, typename T28, typename T29, typename T30,
1176    typename T31, typename T32, typename T33, typename T34, typename T35,
1177    typename T36, typename T37, typename T38, typename T39, typename T40,
1178    typename T41, typename T42, typename T43, typename T44, typename T45,
1179    typename T46, typename T47, typename T48, typename T49, typename T50>
1180internal::ValueArray50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1181    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1182    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1183    T44, T45, T46, T47, T48, T49, T50> Values(T1 v1, T2 v2, T3 v3, T4 v4,
1184    T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13,
1185    T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21,
1186    T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29,
1187    T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37,
1188    T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45,
1189    T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) {
1190  return internal::ValueArray50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
1191      T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1192      T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1193      T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50>(v1, v2, v3, v4,
1194      v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19,
1195      v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33,
1196      v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47,
1197      v48, v49, v50);
1198}
1199
1200// Bool() allows generating tests with parameters in a set of (false, true).
1201//
1202// Synopsis:
1203// Bool()
1204//   - returns a generator producing sequences with elements {false, true}.
1205//
1206// It is useful when testing code that depends on Boolean flags. Combinations
1207// of multiple flags can be tested when several Bool()'s are combined using
1208// Combine() function.
1209//
1210// In the following example all tests in the test case FlagDependentTest
1211// will be instantiated twice with parameters false and true.
1212//
1213// class FlagDependentTest : public testing::TestWithParam<bool> {
1214//   virtual void SetUp() {
1215//     external_flag = GetParam();
1216//   }
1217// }
1218// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool());
1219//
1220inline internal::ParamGenerator<bool> Bool() {
1221  return Values(false, true);
1222}
1223
1224# if GTEST_HAS_COMBINE
1225// Combine() allows the user to combine two or more sequences to produce
1226// values of a Cartesian product of those sequences' elements.
1227//
1228// Synopsis:
1229// Combine(gen1, gen2, ..., genN)
1230//   - returns a generator producing sequences with elements coming from
1231//     the Cartesian product of elements from the sequences generated by
1232//     gen1, gen2, ..., genN. The sequence elements will have a type of
1233//     tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
1234//     of elements from sequences produces by gen1, gen2, ..., genN.
1235//
1236// Combine can have up to 10 arguments. This number is currently limited
1237// by the maximum number of elements in the tuple implementation used by Google
1238// Test.
1239//
1240// Example:
1241//
1242// This will instantiate tests in test case AnimalTest each one with
1243// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
1244// tuple("dog", BLACK), and tuple("dog", WHITE):
1245//
1246// enum Color { BLACK, GRAY, WHITE };
1247// class AnimalTest
1248//     : public testing::TestWithParam<tuple<const char*, Color> > {...};
1249//
1250// TEST_P(AnimalTest, AnimalLooksNice) {...}
1251//
1252// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest,
1253//                         Combine(Values("cat", "dog"),
1254//                                 Values(BLACK, WHITE)));
1255//
1256// This will instantiate tests in FlagDependentTest with all variations of two
1257// Boolean flags:
1258//
1259// class FlagDependentTest
1260//     : public testing::TestWithParam<tuple<bool, bool> > {
1261//   virtual void SetUp() {
1262//     // Assigns external_flag_1 and external_flag_2 values from the tuple.
1263//     tie(external_flag_1, external_flag_2) = GetParam();
1264//   }
1265// };
1266//
1267// TEST_P(FlagDependentTest, TestFeature1) {
1268//   // Test your code using external_flag_1 and external_flag_2 here.
1269// }
1270// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest,
1271//                         Combine(Bool(), Bool()));
1272//
1273template <typename Generator1, typename Generator2>
1274internal::CartesianProductHolder2<Generator1, Generator2> Combine(
1275    const Generator1& g1, const Generator2& g2) {
1276  return internal::CartesianProductHolder2<Generator1, Generator2>(
1277      g1, g2);
1278}
1279
1280template <typename Generator1, typename Generator2, typename Generator3>
1281internal::CartesianProductHolder3<Generator1, Generator2, Generator3> Combine(
1282    const Generator1& g1, const Generator2& g2, const Generator3& g3) {
1283  return internal::CartesianProductHolder3<Generator1, Generator2, Generator3>(
1284      g1, g2, g3);
1285}
1286
1287template <typename Generator1, typename Generator2, typename Generator3,
1288    typename Generator4>
1289internal::CartesianProductHolder4<Generator1, Generator2, Generator3,
1290    Generator4> Combine(
1291    const Generator1& g1, const Generator2& g2, const Generator3& g3,
1292        const Generator4& g4) {
1293  return internal::CartesianProductHolder4<Generator1, Generator2, Generator3,
1294      Generator4>(
1295      g1, g2, g3, g4);
1296}
1297
1298template <typename Generator1, typename Generator2, typename Generator3,
1299    typename Generator4, typename Generator5>
1300internal::CartesianProductHolder5<Generator1, Generator2, Generator3,
1301    Generator4, Generator5> Combine(
1302    const Generator1& g1, const Generator2& g2, const Generator3& g3,
1303        const Generator4& g4, const Generator5& g5) {
1304  return internal::CartesianProductHolder5<Generator1, Generator2, Generator3,
1305      Generator4, Generator5>(
1306      g1, g2, g3, g4, g5);
1307}
1308
1309template <typename Generator1, typename Generator2, typename Generator3,
1310    typename Generator4, typename Generator5, typename Generator6>
1311internal::CartesianProductHolder6<Generator1, Generator2, Generator3,
1312    Generator4, Generator5, Generator6> Combine(
1313    const Generator1& g1, const Generator2& g2, const Generator3& g3,
1314        const Generator4& g4, const Generator5& g5, const Generator6& g6) {
1315  return internal::CartesianProductHolder6<Generator1, Generator2, Generator3,
1316      Generator4, Generator5, Generator6>(
1317      g1, g2, g3, g4, g5, g6);
1318}
1319
1320template <typename Generator1, typename Generator2, typename Generator3,
1321    typename Generator4, typename Generator5, typename Generator6,
1322    typename Generator7>
1323internal::CartesianProductHolder7<Generator1, Generator2, Generator3,
1324    Generator4, Generator5, Generator6, Generator7> Combine(
1325    const Generator1& g1, const Generator2& g2, const Generator3& g3,
1326        const Generator4& g4, const Generator5& g5, const Generator6& g6,
1327        const Generator7& g7) {
1328  return internal::CartesianProductHolder7<Generator1, Generator2, Generator3,
1329      Generator4, Generator5, Generator6, Generator7>(
1330      g1, g2, g3, g4, g5, g6, g7);
1331}
1332
1333template <typename Generator1, typename Generator2, typename Generator3,
1334    typename Generator4, typename Generator5, typename Generator6,
1335    typename Generator7, typename Generator8>
1336internal::CartesianProductHolder8<Generator1, Generator2, Generator3,
1337    Generator4, Generator5, Generator6, Generator7, Generator8> Combine(
1338    const Generator1& g1, const Generator2& g2, const Generator3& g3,
1339        const Generator4& g4, const Generator5& g5, const Generator6& g6,
1340        const Generator7& g7, const Generator8& g8) {
1341  return internal::CartesianProductHolder8<Generator1, Generator2, Generator3,
1342      Generator4, Generator5, Generator6, Generator7, Generator8>(
1343      g1, g2, g3, g4, g5, g6, g7, g8);
1344}
1345
1346template <typename Generator1, typename Generator2, typename Generator3,
1347    typename Generator4, typename Generator5, typename Generator6,
1348    typename Generator7, typename Generator8, typename Generator9>
1349internal::CartesianProductHolder9<Generator1, Generator2, Generator3,
1350    Generator4, Generator5, Generator6, Generator7, Generator8,
1351    Generator9> Combine(
1352    const Generator1& g1, const Generator2& g2, const Generator3& g3,
1353        const Generator4& g4, const Generator5& g5, const Generator6& g6,
1354        const Generator7& g7, const Generator8& g8, const Generator9& g9) {
1355  return internal::CartesianProductHolder9<Generator1, Generator2, Generator3,
1356      Generator4, Generator5, Generator6, Generator7, Generator8, Generator9>(
1357      g1, g2, g3, g4, g5, g6, g7, g8, g9);
1358}
1359
1360template <typename Generator1, typename Generator2, typename Generator3,
1361    typename Generator4, typename Generator5, typename Generator6,
1362    typename Generator7, typename Generator8, typename Generator9,
1363    typename Generator10>
1364internal::CartesianProductHolder10<Generator1, Generator2, Generator3,
1365    Generator4, Generator5, Generator6, Generator7, Generator8, Generator9,
1366    Generator10> Combine(
1367    const Generator1& g1, const Generator2& g2, const Generator3& g3,
1368        const Generator4& g4, const Generator5& g5, const Generator6& g6,
1369        const Generator7& g7, const Generator8& g8, const Generator9& g9,
1370        const Generator10& g10) {
1371  return internal::CartesianProductHolder10<Generator1, Generator2, Generator3,
1372      Generator4, Generator5, Generator6, Generator7, Generator8, Generator9,
1373      Generator10>(
1374      g1, g2, g3, g4, g5, g6, g7, g8, g9, g10);
1375}
1376# endif  // GTEST_HAS_COMBINE
1377
1378
1379
1380# define TEST_P(test_case_name, test_name) \
1381  class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
1382      : public test_case_name { \
1383   public: \
1384    GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \
1385    virtual void TestBody(); \
1386   private: \
1387    static int AddToRegistry() { \
1388      ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \
1389          GetTestCasePatternHolder<test_case_name>(\
1390              #test_case_name, \
1391              ::testing::internal::CodeLocation(\
1392                  __FILE__, __LINE__))->AddTestPattern(\
1393                      #test_case_name, \
1394                      #test_name, \
1395                      new ::testing::internal::TestMetaFactory< \
1396                          GTEST_TEST_CLASS_NAME_(\
1397                              test_case_name, test_name)>()); \
1398      return 0; \
1399    } \
1400    static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
1401    GTEST_DISALLOW_COPY_AND_ASSIGN_(\
1402        GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \
1403  }; \
1404  int GTEST_TEST_CLASS_NAME_(test_case_name, \
1405                             test_name)::gtest_registering_dummy_ = \
1406      GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \
1407  void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
1408
1409// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user
1410// to specify a function or functor that generates custom test name suffixes
1411// based on the test parameters. The function should accept one argument of
1412// type testing::TestParamInfo<class ParamType>, and return std::string.
1413//
1414// testing::PrintToStringParamName is a builtin test suffix generator that
1415// returns the value of testing::PrintToString(GetParam()). It does not work
1416// for std::string or C strings.
1417//
1418// Note: test names must be non-empty, unique, and may only contain ASCII
1419// alphanumeric characters or underscore.
1420
1421# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \
1422  ::testing::internal::ParamGenerator<test_case_name::ParamType> \
1423      gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \
1424  ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \
1425      const ::testing::TestParamInfo<test_case_name::ParamType>& info) { \
1426    return ::testing::internal::GetParamNameGen<test_case_name::ParamType> \
1427        (__VA_ARGS__)(info); \
1428  } \
1429  int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \
1430      ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \
1431          GetTestCasePatternHolder<test_case_name>(\
1432              #test_case_name, \
1433              ::testing::internal::CodeLocation(\
1434                  __FILE__, __LINE__))->AddTestCaseInstantiation(\
1435                      #prefix, \
1436                      &gtest_##prefix##test_case_name##_EvalGenerator_, \
1437                      &gtest_##prefix##test_case_name##_EvalGenerateName_, \
1438                      __FILE__, __LINE__)
1439
1440}  // namespace testing
1441
1442#endif  // GTEST_HAS_PARAM_TEST
1443
1444#endif  // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest-param-test.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$var n = 50  $$ Maximum length of Values arguments we want to support.
3$var maxtuple = 10  $$ Maximum number of Combine arguments we want to support.
4// Copyright 2008, Google Inc.
5// All rights reserved.
6//
7// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions are
9// met:
10//
11//     * Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//     * Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following disclaimer
15// in the documentation and/or other materials provided with the
16// distribution.
17//     * Neither the name of Google Inc. nor the names of its
18// contributors may be used to endorse or promote products derived from
19// this software without specific prior written permission.
20//
21// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32//
33// Authors: vladl@google.com (Vlad Losev)
34//
35// Macros and functions for implementing parameterized tests
36// in Google C++ Testing Framework (Google Test)
37//
38// This file is generated by a SCRIPT.  DO NOT EDIT BY HAND!
39//
40#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
41#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
42
43
44// Value-parameterized tests allow you to test your code with different
45// parameters without writing multiple copies of the same test.
46//
47// Here is how you use value-parameterized tests:
48
49#if 0
50
51// To write value-parameterized tests, first you should define a fixture
52// class. It is usually derived from testing::TestWithParam<T> (see below for
53// another inheritance scheme that's sometimes useful in more complicated
54// class hierarchies), where the type of your parameter values.
55// TestWithParam<T> is itself derived from testing::Test. T can be any
56// copyable type. If it's a raw pointer, you are responsible for managing the
57// lifespan of the pointed values.
58
59class FooTest : public ::testing::TestWithParam<const char*> {
60  // You can implement all the usual class fixture members here.
61};
62
63// Then, use the TEST_P macro to define as many parameterized tests
64// for this fixture as you want. The _P suffix is for "parameterized"
65// or "pattern", whichever you prefer to think.
66
67TEST_P(FooTest, DoesBlah) {
68  // Inside a test, access the test parameter with the GetParam() method
69  // of the TestWithParam<T> class:
70  EXPECT_TRUE(foo.Blah(GetParam()));
71  ...
72}
73
74TEST_P(FooTest, HasBlahBlah) {
75  ...
76}
77
78// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test
79// case with any set of parameters you want. Google Test defines a number
80// of functions for generating test parameters. They return what we call
81// (surprise!) parameter generators. Here is a  summary of them, which
82// are all in the testing namespace:
83//
84//
85//  Range(begin, end [, step]) - Yields values {begin, begin+step,
86//                               begin+step+step, ...}. The values do not
87//                               include end. step defaults to 1.
88//  Values(v1, v2, ..., vN)    - Yields values {v1, v2, ..., vN}.
89//  ValuesIn(container)        - Yields values from a C-style array, an STL
90//  ValuesIn(begin,end)          container, or an iterator range [begin, end).
91//  Bool()                     - Yields sequence {false, true}.
92//  Combine(g1, g2, ..., gN)   - Yields all combinations (the Cartesian product
93//                               for the math savvy) of the values generated
94//                               by the N generators.
95//
96// For more details, see comments at the definitions of these functions below
97// in this file.
98//
99// The following statement will instantiate tests from the FooTest test case
100// each with parameter values "meeny", "miny", and "moe".
101
102INSTANTIATE_TEST_CASE_P(InstantiationName,
103                        FooTest,
104                        Values("meeny", "miny", "moe"));
105
106// To distinguish different instances of the pattern, (yes, you
107// can instantiate it more then once) the first argument to the
108// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the
109// actual test case name. Remember to pick unique prefixes for different
110// instantiations. The tests from the instantiation above will have
111// these names:
112//
113//    * InstantiationName/FooTest.DoesBlah/0 for "meeny"
114//    * InstantiationName/FooTest.DoesBlah/1 for "miny"
115//    * InstantiationName/FooTest.DoesBlah/2 for "moe"
116//    * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
117//    * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
118//    * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
119//
120// You can use these names in --gtest_filter.
121//
122// This statement will instantiate all tests from FooTest again, each
123// with parameter values "cat" and "dog":
124
125const char* pets[] = {"cat", "dog"};
126INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
127
128// The tests from the instantiation above will have these names:
129//
130//    * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
131//    * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
132//    * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
133//    * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
134//
135// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests
136// in the given test case, whether their definitions come before or
137// AFTER the INSTANTIATE_TEST_CASE_P statement.
138//
139// Please also note that generator expressions (including parameters to the
140// generators) are evaluated in InitGoogleTest(), after main() has started.
141// This allows the user on one hand, to adjust generator parameters in order
142// to dynamically determine a set of tests to run and on the other hand,
143// give the user a chance to inspect the generated tests with Google Test
144// reflection API before RUN_ALL_TESTS() is executed.
145//
146// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
147// for more examples.
148//
149// In the future, we plan to publish the API for defining new parameter
150// generators. But for now this interface remains part of the internal
151// implementation and is subject to change.
152//
153//
154// A parameterized test fixture must be derived from testing::Test and from
155// testing::WithParamInterface<T>, where T is the type of the parameter
156// values. Inheriting from TestWithParam<T> satisfies that requirement because
157// TestWithParam<T> inherits from both Test and WithParamInterface. In more
158// complicated hierarchies, however, it is occasionally useful to inherit
159// separately from Test and WithParamInterface. For example:
160
161class BaseTest : public ::testing::Test {
162  // You can inherit all the usual members for a non-parameterized test
163  // fixture here.
164};
165
166class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
167  // The usual test fixture members go here too.
168};
169
170TEST_F(BaseTest, HasFoo) {
171  // This is an ordinary non-parameterized test.
172}
173
174TEST_P(DerivedTest, DoesBlah) {
175  // GetParam works just the same here as if you inherit from TestWithParam.
176  EXPECT_TRUE(foo.Blah(GetParam()));
177}
178
179#endif  // 0
180
181#include "gtest/internal/gtest-port.h"
182
183#if !GTEST_OS_SYMBIAN
184# include <utility>
185#endif
186
187// scripts/fuse_gtest.py depends on gtest's own header being #included
188// *unconditionally*.  Therefore these #includes cannot be moved
189// inside #if GTEST_HAS_PARAM_TEST.
190#include "gtest/internal/gtest-internal.h"
191#include "gtest/internal/gtest-param-util.h"
192#include "gtest/internal/gtest-param-util-generated.h"
193
194#if GTEST_HAS_PARAM_TEST
195
196namespace testing {
197
198// Functions producing parameter generators.
199//
200// Google Test uses these generators to produce parameters for value-
201// parameterized tests. When a parameterized test case is instantiated
202// with a particular generator, Google Test creates and runs tests
203// for each element in the sequence produced by the generator.
204//
205// In the following sample, tests from test case FooTest are instantiated
206// each three times with parameter values 3, 5, and 8:
207//
208// class FooTest : public TestWithParam<int> { ... };
209//
210// TEST_P(FooTest, TestThis) {
211// }
212// TEST_P(FooTest, TestThat) {
213// }
214// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8));
215//
216
217// Range() returns generators providing sequences of values in a range.
218//
219// Synopsis:
220// Range(start, end)
221//   - returns a generator producing a sequence of values {start, start+1,
222//     start+2, ..., }.
223// Range(start, end, step)
224//   - returns a generator producing a sequence of values {start, start+step,
225//     start+step+step, ..., }.
226// Notes:
227//   * The generated sequences never include end. For example, Range(1, 5)
228//     returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
229//     returns a generator producing {1, 3, 5, 7}.
230//   * start and end must have the same type. That type may be any integral or
231//     floating-point type or a user defined type satisfying these conditions:
232//     * It must be assignable (have operator=() defined).
233//     * It must have operator+() (operator+(int-compatible type) for
234//       two-operand version).
235//     * It must have operator<() defined.
236//     Elements in the resulting sequences will also have that type.
237//   * Condition start < end must be satisfied in order for resulting sequences
238//     to contain any elements.
239//
240template <typename T, typename IncrementT>
241internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
242  return internal::ParamGenerator<T>(
243      new internal::RangeGenerator<T, IncrementT>(start, end, step));
244}
245
246template <typename T>
247internal::ParamGenerator<T> Range(T start, T end) {
248  return Range(start, end, 1);
249}
250
251// ValuesIn() function allows generation of tests with parameters coming from
252// a container.
253//
254// Synopsis:
255// ValuesIn(const T (&array)[N])
256//   - returns a generator producing sequences with elements from
257//     a C-style array.
258// ValuesIn(const Container& container)
259//   - returns a generator producing sequences with elements from
260//     an STL-style container.
261// ValuesIn(Iterator begin, Iterator end)
262//   - returns a generator producing sequences with elements from
263//     a range [begin, end) defined by a pair of STL-style iterators. These
264//     iterators can also be plain C pointers.
265//
266// Please note that ValuesIn copies the values from the containers
267// passed in and keeps them to generate tests in RUN_ALL_TESTS().
268//
269// Examples:
270//
271// This instantiates tests from test case StringTest
272// each with C-string values of "foo", "bar", and "baz":
273//
274// const char* strings[] = {"foo", "bar", "baz"};
275// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings));
276//
277// This instantiates tests from test case StlStringTest
278// each with STL strings with values "a" and "b":
279//
280// ::std::vector< ::std::string> GetParameterStrings() {
281//   ::std::vector< ::std::string> v;
282//   v.push_back("a");
283//   v.push_back("b");
284//   return v;
285// }
286//
287// INSTANTIATE_TEST_CASE_P(CharSequence,
288//                         StlStringTest,
289//                         ValuesIn(GetParameterStrings()));
290//
291//
292// This will also instantiate tests from CharTest
293// each with parameter values 'a' and 'b':
294//
295// ::std::list<char> GetParameterChars() {
296//   ::std::list<char> list;
297//   list.push_back('a');
298//   list.push_back('b');
299//   return list;
300// }
301// ::std::list<char> l = GetParameterChars();
302// INSTANTIATE_TEST_CASE_P(CharSequence2,
303//                         CharTest,
304//                         ValuesIn(l.begin(), l.end()));
305//
306template <typename ForwardIterator>
307internal::ParamGenerator<
308  typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type>
309ValuesIn(ForwardIterator begin, ForwardIterator end) {
310  typedef typename ::testing::internal::IteratorTraits<ForwardIterator>
311      ::value_type ParamType;
312  return internal::ParamGenerator<ParamType>(
313      new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
314}
315
316template <typename T, size_t N>
317internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
318  return ValuesIn(array, array + N);
319}
320
321template <class Container>
322internal::ParamGenerator<typename Container::value_type> ValuesIn(
323    const Container& container) {
324  return ValuesIn(container.begin(), container.end());
325}
326
327// Values() allows generating tests from explicitly specified list of
328// parameters.
329//
330// Synopsis:
331// Values(T v1, T v2, ..., T vN)
332//   - returns a generator producing sequences with elements v1, v2, ..., vN.
333//
334// For example, this instantiates tests from test case BarTest each
335// with values "one", "two", and "three":
336//
337// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three"));
338//
339// This instantiates tests from test case BazTest each with values 1, 2, 3.5.
340// The exact type of values will depend on the type of parameter in BazTest.
341//
342// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
343//
344// Currently, Values() supports from 1 to $n parameters.
345//
346$range i 1..n
347$for i [[
348$range j 1..i
349
350template <$for j, [[typename T$j]]>
351internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) {
352  return internal::ValueArray$i<$for j, [[T$j]]>($for j, [[v$j]]);
353}
354
355]]
356
357// Bool() allows generating tests with parameters in a set of (false, true).
358//
359// Synopsis:
360// Bool()
361//   - returns a generator producing sequences with elements {false, true}.
362//
363// It is useful when testing code that depends on Boolean flags. Combinations
364// of multiple flags can be tested when several Bool()'s are combined using
365// Combine() function.
366//
367// In the following example all tests in the test case FlagDependentTest
368// will be instantiated twice with parameters false and true.
369//
370// class FlagDependentTest : public testing::TestWithParam<bool> {
371//   virtual void SetUp() {
372//     external_flag = GetParam();
373//   }
374// }
375// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool());
376//
377inline internal::ParamGenerator<bool> Bool() {
378  return Values(false, true);
379}
380
381# if GTEST_HAS_COMBINE
382// Combine() allows the user to combine two or more sequences to produce
383// values of a Cartesian product of those sequences' elements.
384//
385// Synopsis:
386// Combine(gen1, gen2, ..., genN)
387//   - returns a generator producing sequences with elements coming from
388//     the Cartesian product of elements from the sequences generated by
389//     gen1, gen2, ..., genN. The sequence elements will have a type of
390//     tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
391//     of elements from sequences produces by gen1, gen2, ..., genN.
392//
393// Combine can have up to $maxtuple arguments. This number is currently limited
394// by the maximum number of elements in the tuple implementation used by Google
395// Test.
396//
397// Example:
398//
399// This will instantiate tests in test case AnimalTest each one with
400// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
401// tuple("dog", BLACK), and tuple("dog", WHITE):
402//
403// enum Color { BLACK, GRAY, WHITE };
404// class AnimalTest
405//     : public testing::TestWithParam<tuple<const char*, Color> > {...};
406//
407// TEST_P(AnimalTest, AnimalLooksNice) {...}
408//
409// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest,
410//                         Combine(Values("cat", "dog"),
411//                                 Values(BLACK, WHITE)));
412//
413// This will instantiate tests in FlagDependentTest with all variations of two
414// Boolean flags:
415//
416// class FlagDependentTest
417//     : public testing::TestWithParam<tuple<bool, bool> > {
418//   virtual void SetUp() {
419//     // Assigns external_flag_1 and external_flag_2 values from the tuple.
420//     tie(external_flag_1, external_flag_2) = GetParam();
421//   }
422// };
423//
424// TEST_P(FlagDependentTest, TestFeature1) {
425//   // Test your code using external_flag_1 and external_flag_2 here.
426// }
427// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest,
428//                         Combine(Bool(), Bool()));
429//
430$range i 2..maxtuple
431$for i [[
432$range j 1..i
433
434template <$for j, [[typename Generator$j]]>
435internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine(
436    $for j, [[const Generator$j& g$j]]) {
437  return internal::CartesianProductHolder$i<$for j, [[Generator$j]]>(
438      $for j, [[g$j]]);
439}
440
441]]
442# endif  // GTEST_HAS_COMBINE
443
444
445
446# define TEST_P(test_case_name, test_name) \
447  class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
448      : public test_case_name { \
449   public: \
450    GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \
451    virtual void TestBody(); \
452   private: \
453    static int AddToRegistry() { \
454      ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \
455          GetTestCasePatternHolder<test_case_name>(\
456              #test_case_name, \
457              ::testing::internal::CodeLocation(\
458                  __FILE__, __LINE__))->AddTestPattern(\
459                      #test_case_name, \
460                      #test_name, \
461                      new ::testing::internal::TestMetaFactory< \
462                          GTEST_TEST_CLASS_NAME_(\
463                              test_case_name, test_name)>()); \
464      return 0; \
465    } \
466    static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
467    GTEST_DISALLOW_COPY_AND_ASSIGN_(\
468        GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \
469  }; \
470  int GTEST_TEST_CLASS_NAME_(test_case_name, \
471                             test_name)::gtest_registering_dummy_ = \
472      GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \
473  void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
474
475// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user
476// to specify a function or functor that generates custom test name suffixes
477// based on the test parameters. The function should accept one argument of
478// type testing::TestParamInfo<class ParamType>, and return std::string.
479//
480// testing::PrintToStringParamName is a builtin test suffix generator that
481// returns the value of testing::PrintToString(GetParam()).
482//
483// Note: test names must be non-empty, unique, and may only contain ASCII
484// alphanumeric characters or underscore. Because PrintToString adds quotes
485// to std::string and C strings, it won't work for these types.
486
487# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \
488  ::testing::internal::ParamGenerator<test_case_name::ParamType> \
489      gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \
490  ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \
491      const ::testing::TestParamInfo<test_case_name::ParamType>& info) { \
492    return ::testing::internal::GetParamNameGen<test_case_name::ParamType> \
493        (__VA_ARGS__)(info); \
494  } \
495  int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \
496      ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \
497          GetTestCasePatternHolder<test_case_name>(\
498              #test_case_name, \
499              ::testing::internal::CodeLocation(\
500                  __FILE__, __LINE__))->AddTestCaseInstantiation(\
501                      #prefix, \
502                      &gtest_##prefix##test_case_name##_EvalGenerator_, \
503                      &gtest_##prefix##test_case_name##_EvalGenerateName_, \
504                      __FILE__, __LINE__)
505
506}  // namespace testing
507
508#endif  // GTEST_HAS_PARAM_TEST
509
510#endif  // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest-printers.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Test - The Google C++ Testing Framework
33//
34// This file implements a universal value printer that can print a
35// value of any type T:
36//
37//   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
38//
39// A user can teach this function how to print a class type T by
40// defining either operator<<() or PrintTo() in the namespace that
41// defines T.  More specifically, the FIRST defined function in the
42// following list will be used (assuming T is defined in namespace
43// foo):
44//
45//   1. foo::PrintTo(const T&, ostream*)
46//   2. operator<<(ostream&, const T&) defined in either foo or the
47//      global namespace.
48//
49// If none of the above is defined, it will print the debug string of
50// the value if it is a protocol buffer, or print the raw bytes in the
51// value otherwise.
52//
53// To aid debugging: when T is a reference type, the address of the
54// value is also printed; when T is a (const) char pointer, both the
55// pointer value and the NUL-terminated string it points to are
56// printed.
57//
58// We also provide some convenient wrappers:
59//
60//   // Prints a value to a string.  For a (const or not) char
61//   // pointer, the NUL-terminated string (but not the pointer) is
62//   // printed.
63//   std::string ::testing::PrintToString(const T& value);
64//
65//   // Prints a value tersely: for a reference type, the referenced
66//   // value (but not the address) is printed; for a (const or not) char
67//   // pointer, the NUL-terminated string (but not the pointer) is
68//   // printed.
69//   void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
70//
71//   // Prints value using the type inferred by the compiler.  The difference
72//   // from UniversalTersePrint() is that this function prints both the
73//   // pointer and the NUL-terminated string for a (const or not) char pointer.
74//   void ::testing::internal::UniversalPrint(const T& value, ostream*);
75//
76//   // Prints the fields of a tuple tersely to a string vector, one
77//   // element for each field. Tuple support must be enabled in
78//   // gtest-port.h.
79//   std::vector<string> UniversalTersePrintTupleFieldsToStrings(
80//       const Tuple& value);
81//
82// Known limitation:
83//
84// The print primitives print the elements of an STL-style container
85// using the compiler-inferred type of *iter where iter is a
86// const_iterator of the container.  When const_iterator is an input
87// iterator but not a forward iterator, this inferred type may not
88// match value_type, and the print output may be incorrect.  In
89// practice, this is rarely a problem as for most containers
90// const_iterator is a forward iterator.  We'll fix this if there's an
91// actual need for it.  Note that this fix cannot rely on value_type
92// being defined as many user-defined container types don't have
93// value_type.
94
95#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
96#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
97
98#include <ostream>  // NOLINT
99#include <sstream>
100#include <string>
101#include <utility>
102#include <vector>
103#include "gtest/internal/gtest-port.h"
104#include "gtest/internal/gtest-internal.h"
105
106#if GTEST_HAS_STD_TUPLE_
107# include <tuple>
108#endif
109
110namespace testing {
111
112// Definitions in the 'internal' and 'internal2' name spaces are
113// subject to change without notice.  DO NOT USE THEM IN USER CODE!
114namespace internal2 {
115
116// Prints the given number of bytes in the given object to the given
117// ostream.
118GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
119                                     size_t count,
120                                     ::std::ostream* os);
121
122// For selecting which printer to use when a given type has neither <<
123// nor PrintTo().
124enum TypeKind {
125  kProtobuf,              // a protobuf type
126  kConvertibleToInteger,  // a type implicitly convertible to BiggestInt
127                          // (e.g. a named or unnamed enum type)
128  kOtherType              // anything else
129};
130
131// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
132// by the universal printer to print a value of type T when neither
133// operator<< nor PrintTo() is defined for T, where kTypeKind is the
134// "kind" of T as defined by enum TypeKind.
135template <typename T, TypeKind kTypeKind>
136class TypeWithoutFormatter {
137 public:
138  // This default version is called when kTypeKind is kOtherType.
139  static void PrintValue(const T& value, ::std::ostream* os) {
140    PrintBytesInObjectTo(reinterpret_cast<const unsigned char*>(&value),
141                         sizeof(value), os);
142  }
143};
144
145// We print a protobuf using its ShortDebugString() when the string
146// doesn't exceed this many characters; otherwise we print it using
147// DebugString() for better readability.
148const size_t kProtobufOneLinerMaxLength = 50;
149
150template <typename T>
151class TypeWithoutFormatter<T, kProtobuf> {
152 public:
153  static void PrintValue(const T& value, ::std::ostream* os) {
154    const ::testing::internal::string short_str = value.ShortDebugString();
155    const ::testing::internal::string pretty_str =
156        short_str.length() <= kProtobufOneLinerMaxLength ?
157        short_str : ("\n" + value.DebugString());
158    *os << ("<" + pretty_str + ">");
159  }
160};
161
162template <typename T>
163class TypeWithoutFormatter<T, kConvertibleToInteger> {
164 public:
165  // Since T has no << operator or PrintTo() but can be implicitly
166  // converted to BiggestInt, we print it as a BiggestInt.
167  //
168  // Most likely T is an enum type (either named or unnamed), in which
169  // case printing it as an integer is the desired behavior.  In case
170  // T is not an enum, printing it as an integer is the best we can do
171  // given that it has no user-defined printer.
172  static void PrintValue(const T& value, ::std::ostream* os) {
173    const internal::BiggestInt kBigInt = value;
174    *os << kBigInt;
175  }
176};
177
178// Prints the given value to the given ostream.  If the value is a
179// protocol message, its debug string is printed; if it's an enum or
180// of a type implicitly convertible to BiggestInt, it's printed as an
181// integer; otherwise the bytes in the value are printed.  This is
182// what UniversalPrinter<T>::Print() does when it knows nothing about
183// type T and T has neither << operator nor PrintTo().
184//
185// A user can override this behavior for a class type Foo by defining
186// a << operator in the namespace where Foo is defined.
187//
188// We put this operator in namespace 'internal2' instead of 'internal'
189// to simplify the implementation, as much code in 'internal' needs to
190// use << in STL, which would conflict with our own << were it defined
191// in 'internal'.
192//
193// Note that this operator<< takes a generic std::basic_ostream<Char,
194// CharTraits> type instead of the more restricted std::ostream.  If
195// we define it to take an std::ostream instead, we'll get an
196// "ambiguous overloads" compiler error when trying to print a type
197// Foo that supports streaming to std::basic_ostream<Char,
198// CharTraits>, as the compiler cannot tell whether
199// operator<<(std::ostream&, const T&) or
200// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
201// specific.
202template <typename Char, typename CharTraits, typename T>
203::std::basic_ostream<Char, CharTraits>& operator<<(
204    ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
205  TypeWithoutFormatter<T,
206      (internal::IsAProtocolMessage<T>::value ? kProtobuf :
207       internal::ImplicitlyConvertible<const T&, internal::BiggestInt>::value ?
208       kConvertibleToInteger : kOtherType)>::PrintValue(x, &os);
209  return os;
210}
211
212}  // namespace internal2
213}  // namespace testing
214
215// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
216// magic needed for implementing UniversalPrinter won't work.
217namespace testing_internal {
218
219// Used to print a value that is not an STL-style container when the
220// user doesn't define PrintTo() for it.
221template <typename T>
222void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
223  // With the following statement, during unqualified name lookup,
224  // testing::internal2::operator<< appears as if it was declared in
225  // the nearest enclosing namespace that contains both
226  // ::testing_internal and ::testing::internal2, i.e. the global
227  // namespace.  For more details, refer to the C++ Standard section
228  // 7.3.4-1 [namespace.udir].  This allows us to fall back onto
229  // testing::internal2::operator<< in case T doesn't come with a <<
230  // operator.
231  //
232  // We cannot write 'using ::testing::internal2::operator<<;', which
233  // gcc 3.3 fails to compile due to a compiler bug.
234  using namespace ::testing::internal2;  // NOLINT
235
236  // Assuming T is defined in namespace foo, in the next statement,
237  // the compiler will consider all of:
238  //
239  //   1. foo::operator<< (thanks to Koenig look-up),
240  //   2. ::operator<< (as the current namespace is enclosed in ::),
241  //   3. testing::internal2::operator<< (thanks to the using statement above).
242  //
243  // The operator<< whose type matches T best will be picked.
244  //
245  // We deliberately allow #2 to be a candidate, as sometimes it's
246  // impossible to define #1 (e.g. when foo is ::std, defining
247  // anything in it is undefined behavior unless you are a compiler
248  // vendor.).
249  *os << value;
250}
251
252}  // namespace testing_internal
253
254namespace testing {
255namespace internal {
256
257// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
258// value of type ToPrint that is an operand of a comparison assertion
259// (e.g. ASSERT_EQ).  OtherOperand is the type of the other operand in
260// the comparison, and is used to help determine the best way to
261// format the value.  In particular, when the value is a C string
262// (char pointer) and the other operand is an STL string object, we
263// want to format the C string as a string, since we know it is
264// compared by value with the string object.  If the value is a char
265// pointer but the other operand is not an STL string object, we don't
266// know whether the pointer is supposed to point to a NUL-terminated
267// string, and thus want to print it as a pointer to be safe.
268//
269// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
270
271// The default case.
272template <typename ToPrint, typename OtherOperand>
273class FormatForComparison {
274 public:
275  static ::std::string Format(const ToPrint& value) {
276    return ::testing::PrintToString(value);
277  }
278};
279
280// Array.
281template <typename ToPrint, size_t N, typename OtherOperand>
282class FormatForComparison<ToPrint[N], OtherOperand> {
283 public:
284  static ::std::string Format(const ToPrint* value) {
285    return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
286  }
287};
288
289// By default, print C string as pointers to be safe, as we don't know
290// whether they actually point to a NUL-terminated string.
291
292#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType)                \
293  template <typename OtherOperand>                                      \
294  class FormatForComparison<CharType*, OtherOperand> {                  \
295   public:                                                              \
296    static ::std::string Format(CharType* value) {                      \
297      return ::testing::PrintToString(static_cast<const void*>(value)); \
298    }                                                                   \
299  }
300
301GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
302GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
303GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
304GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
305
306#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
307
308// If a C string is compared with an STL string object, we know it's meant
309// to point to a NUL-terminated string, and thus can print it as a string.
310
311#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
312  template <>                                                           \
313  class FormatForComparison<CharType*, OtherStringType> {               \
314   public:                                                              \
315    static ::std::string Format(CharType* value) {                      \
316      return ::testing::PrintToString(value);                           \
317    }                                                                   \
318  }
319
320GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
321GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
322
323#if GTEST_HAS_GLOBAL_STRING
324GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string);
325GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string);
326#endif
327
328#if GTEST_HAS_GLOBAL_WSTRING
329GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring);
330GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring);
331#endif
332
333#if GTEST_HAS_STD_WSTRING
334GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
335GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
336#endif
337
338#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
339
340// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
341// operand to be used in a failure message.  The type (but not value)
342// of the other operand may affect the format.  This allows us to
343// print a char* as a raw pointer when it is compared against another
344// char* or void*, and print it as a C string when it is compared
345// against an std::string object, for example.
346//
347// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
348template <typename T1, typename T2>
349std::string FormatForComparisonFailureMessage(
350    const T1& value, const T2& /* other_operand */) {
351  return FormatForComparison<T1, T2>::Format(value);
352}
353
354// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
355// value to the given ostream.  The caller must ensure that
356// 'ostream_ptr' is not NULL, or the behavior is undefined.
357//
358// We define UniversalPrinter as a class template (as opposed to a
359// function template), as we need to partially specialize it for
360// reference types, which cannot be done with function templates.
361template <typename T>
362class UniversalPrinter;
363
364template <typename T>
365void UniversalPrint(const T& value, ::std::ostream* os);
366
367// Used to print an STL-style container when the user doesn't define
368// a PrintTo() for it.
369template <typename C>
370void DefaultPrintTo(IsContainer /* dummy */,
371                    false_type /* is not a pointer */,
372                    const C& container, ::std::ostream* os) {
373  const size_t kMaxCount = 32;  // The maximum number of elements to print.
374  *os << '{';
375  size_t count = 0;
376  for (typename C::const_iterator it = container.begin();
377       it != container.end(); ++it, ++count) {
378    if (count > 0) {
379      *os << ',';
380      if (count == kMaxCount) {  // Enough has been printed.
381        *os << " ...";
382        break;
383      }
384    }
385    *os << ' ';
386    // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
387    // handle *it being a native array.
388    internal::UniversalPrint(*it, os);
389  }
390
391  if (count > 0) {
392    *os << ' ';
393  }
394  *os << '}';
395}
396
397// Used to print a pointer that is neither a char pointer nor a member
398// pointer, when the user doesn't define PrintTo() for it.  (A member
399// variable pointer or member function pointer doesn't really point to
400// a location in the address space.  Their representation is
401// implementation-defined.  Therefore they will be printed as raw
402// bytes.)
403template <typename T>
404void DefaultPrintTo(IsNotContainer /* dummy */,
405                    true_type /* is a pointer */,
406                    T* p, ::std::ostream* os) {
407  if (p == NULL) {
408    *os << "NULL";
409  } else {
410    // C++ doesn't allow casting from a function pointer to any object
411    // pointer.
412    //
413    // IsTrue() silences warnings: "Condition is always true",
414    // "unreachable code".
415    if (IsTrue(ImplicitlyConvertible<T*, const void*>::value)) {
416      // T is not a function type.  We just call << to print p,
417      // relying on ADL to pick up user-defined << for their pointer
418      // types, if any.
419      *os << p;
420    } else {
421      // T is a function type, so '*os << p' doesn't do what we want
422      // (it just prints p as bool).  We want to print p as a const
423      // void*.  However, we cannot cast it to const void* directly,
424      // even using reinterpret_cast, as earlier versions of gcc
425      // (e.g. 3.4.5) cannot compile the cast when p is a function
426      // pointer.  Casting to UInt64 first solves the problem.
427      *os << reinterpret_cast<const void*>(
428          reinterpret_cast<internal::UInt64>(p));
429    }
430  }
431}
432
433// Used to print a non-container, non-pointer value when the user
434// doesn't define PrintTo() for it.
435template <typename T>
436void DefaultPrintTo(IsNotContainer /* dummy */,
437                    false_type /* is not a pointer */,
438                    const T& value, ::std::ostream* os) {
439  ::testing_internal::DefaultPrintNonContainerTo(value, os);
440}
441
442// Prints the given value using the << operator if it has one;
443// otherwise prints the bytes in it.  This is what
444// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
445// or overloaded for type T.
446//
447// A user can override this behavior for a class type Foo by defining
448// an overload of PrintTo() in the namespace where Foo is defined.  We
449// give the user this option as sometimes defining a << operator for
450// Foo is not desirable (e.g. the coding style may prevent doing it,
451// or there is already a << operator but it doesn't do what the user
452// wants).
453template <typename T>
454void PrintTo(const T& value, ::std::ostream* os) {
455  // DefaultPrintTo() is overloaded.  The type of its first two
456  // arguments determine which version will be picked.  If T is an
457  // STL-style container, the version for container will be called; if
458  // T is a pointer, the pointer version will be called; otherwise the
459  // generic version will be called.
460  //
461  // Note that we check for container types here, prior to we check
462  // for protocol message types in our operator<<.  The rationale is:
463  //
464  // For protocol messages, we want to give people a chance to
465  // override Google Mock's format by defining a PrintTo() or
466  // operator<<.  For STL containers, other formats can be
467  // incompatible with Google Mock's format for the container
468  // elements; therefore we check for container types here to ensure
469  // that our format is used.
470  //
471  // The second argument of DefaultPrintTo() is needed to bypass a bug
472  // in Symbian's C++ compiler that prevents it from picking the right
473  // overload between:
474  //
475  //   PrintTo(const T& x, ...);
476  //   PrintTo(T* x, ...);
477  DefaultPrintTo(IsContainerTest<T>(0), is_pointer<T>(), value, os);
478}
479
480// The following list of PrintTo() overloads tells
481// UniversalPrinter<T>::Print() how to print standard types (built-in
482// types, strings, plain arrays, and pointers).
483
484// Overloads for various char types.
485GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
486GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
487inline void PrintTo(char c, ::std::ostream* os) {
488  // When printing a plain char, we always treat it as unsigned.  This
489  // way, the output won't be affected by whether the compiler thinks
490  // char is signed or not.
491  PrintTo(static_cast<unsigned char>(c), os);
492}
493
494// Overloads for other simple built-in types.
495inline void PrintTo(bool x, ::std::ostream* os) {
496  *os << (x ? "true" : "false");
497}
498
499// Overload for wchar_t type.
500// Prints a wchar_t as a symbol if it is printable or as its internal
501// code otherwise and also as its decimal code (except for L'\0').
502// The L'\0' char is printed as "L'\\0'". The decimal code is printed
503// as signed integer when wchar_t is implemented by the compiler
504// as a signed type and is printed as an unsigned integer when wchar_t
505// is implemented as an unsigned type.
506GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
507
508// Overloads for C strings.
509GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
510inline void PrintTo(char* s, ::std::ostream* os) {
511  PrintTo(ImplicitCast_<const char*>(s), os);
512}
513
514// signed/unsigned char is often used for representing binary data, so
515// we print pointers to it as void* to be safe.
516inline void PrintTo(const signed char* s, ::std::ostream* os) {
517  PrintTo(ImplicitCast_<const void*>(s), os);
518}
519inline void PrintTo(signed char* s, ::std::ostream* os) {
520  PrintTo(ImplicitCast_<const void*>(s), os);
521}
522inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
523  PrintTo(ImplicitCast_<const void*>(s), os);
524}
525inline void PrintTo(unsigned char* s, ::std::ostream* os) {
526  PrintTo(ImplicitCast_<const void*>(s), os);
527}
528
529// MSVC can be configured to define wchar_t as a typedef of unsigned
530// short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
531// type.  When wchar_t is a typedef, defining an overload for const
532// wchar_t* would cause unsigned short* be printed as a wide string,
533// possibly causing invalid memory accesses.
534#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
535// Overloads for wide C strings
536GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
537inline void PrintTo(wchar_t* s, ::std::ostream* os) {
538  PrintTo(ImplicitCast_<const wchar_t*>(s), os);
539}
540#endif
541
542// Overload for C arrays.  Multi-dimensional arrays are printed
543// properly.
544
545// Prints the given number of elements in an array, without printing
546// the curly braces.
547template <typename T>
548void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
549  UniversalPrint(a[0], os);
550  for (size_t i = 1; i != count; i++) {
551    *os << ", ";
552    UniversalPrint(a[i], os);
553  }
554}
555
556// Overloads for ::string and ::std::string.
557#if GTEST_HAS_GLOBAL_STRING
558GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os);
559inline void PrintTo(const ::string& s, ::std::ostream* os) {
560  PrintStringTo(s, os);
561}
562#endif  // GTEST_HAS_GLOBAL_STRING
563
564GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
565inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
566  PrintStringTo(s, os);
567}
568
569// Overloads for ::wstring and ::std::wstring.
570#if GTEST_HAS_GLOBAL_WSTRING
571GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os);
572inline void PrintTo(const ::wstring& s, ::std::ostream* os) {
573  PrintWideStringTo(s, os);
574}
575#endif  // GTEST_HAS_GLOBAL_WSTRING
576
577#if GTEST_HAS_STD_WSTRING
578GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
579inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
580  PrintWideStringTo(s, os);
581}
582#endif  // GTEST_HAS_STD_WSTRING
583
584#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
585// Helper function for printing a tuple.  T must be instantiated with
586// a tuple type.
587template <typename T>
588void PrintTupleTo(const T& t, ::std::ostream* os);
589#endif  // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
590
591#if GTEST_HAS_TR1_TUPLE
592// Overload for ::std::tr1::tuple.  Needed for printing function arguments,
593// which are packed as tuples.
594
595// Overloaded PrintTo() for tuples of various arities.  We support
596// tuples of up-to 10 fields.  The following implementation works
597// regardless of whether tr1::tuple is implemented using the
598// non-standard variadic template feature or not.
599
600inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) {
601  PrintTupleTo(t, os);
602}
603
604template <typename T1>
605void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) {
606  PrintTupleTo(t, os);
607}
608
609template <typename T1, typename T2>
610void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) {
611  PrintTupleTo(t, os);
612}
613
614template <typename T1, typename T2, typename T3>
615void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) {
616  PrintTupleTo(t, os);
617}
618
619template <typename T1, typename T2, typename T3, typename T4>
620void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) {
621  PrintTupleTo(t, os);
622}
623
624template <typename T1, typename T2, typename T3, typename T4, typename T5>
625void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t,
626             ::std::ostream* os) {
627  PrintTupleTo(t, os);
628}
629
630template <typename T1, typename T2, typename T3, typename T4, typename T5,
631          typename T6>
632void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t,
633             ::std::ostream* os) {
634  PrintTupleTo(t, os);
635}
636
637template <typename T1, typename T2, typename T3, typename T4, typename T5,
638          typename T6, typename T7>
639void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t,
640             ::std::ostream* os) {
641  PrintTupleTo(t, os);
642}
643
644template <typename T1, typename T2, typename T3, typename T4, typename T5,
645          typename T6, typename T7, typename T8>
646void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t,
647             ::std::ostream* os) {
648  PrintTupleTo(t, os);
649}
650
651template <typename T1, typename T2, typename T3, typename T4, typename T5,
652          typename T6, typename T7, typename T8, typename T9>
653void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t,
654             ::std::ostream* os) {
655  PrintTupleTo(t, os);
656}
657
658template <typename T1, typename T2, typename T3, typename T4, typename T5,
659          typename T6, typename T7, typename T8, typename T9, typename T10>
660void PrintTo(
661    const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t,
662    ::std::ostream* os) {
663  PrintTupleTo(t, os);
664}
665#endif  // GTEST_HAS_TR1_TUPLE
666
667#if GTEST_HAS_STD_TUPLE_
668template <typename... Types>
669void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
670  PrintTupleTo(t, os);
671}
672#endif  // GTEST_HAS_STD_TUPLE_
673
674// Overload for std::pair.
675template <typename T1, typename T2>
676void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
677  *os << '(';
678  // We cannot use UniversalPrint(value.first, os) here, as T1 may be
679  // a reference type.  The same for printing value.second.
680  UniversalPrinter<T1>::Print(value.first, os);
681  *os << ", ";
682  UniversalPrinter<T2>::Print(value.second, os);
683  *os << ')';
684}
685
686// Implements printing a non-reference type T by letting the compiler
687// pick the right overload of PrintTo() for T.
688template <typename T>
689class UniversalPrinter {
690 public:
691  // MSVC warns about adding const to a function type, so we want to
692  // disable the warning.
693  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
694
695  // Note: we deliberately don't call this PrintTo(), as that name
696  // conflicts with ::testing::internal::PrintTo in the body of the
697  // function.
698  static void Print(const T& value, ::std::ostream* os) {
699    // By default, ::testing::internal::PrintTo() is used for printing
700    // the value.
701    //
702    // Thanks to Koenig look-up, if T is a class and has its own
703    // PrintTo() function defined in its namespace, that function will
704    // be visible here.  Since it is more specific than the generic ones
705    // in ::testing::internal, it will be picked by the compiler in the
706    // following statement - exactly what we want.
707    PrintTo(value, os);
708  }
709
710  GTEST_DISABLE_MSC_WARNINGS_POP_()
711};
712
713// UniversalPrintArray(begin, len, os) prints an array of 'len'
714// elements, starting at address 'begin'.
715template <typename T>
716void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
717  if (len == 0) {
718    *os << "{}";
719  } else {
720    *os << "{ ";
721    const size_t kThreshold = 18;
722    const size_t kChunkSize = 8;
723    // If the array has more than kThreshold elements, we'll have to
724    // omit some details by printing only the first and the last
725    // kChunkSize elements.
726    // TODO(wan@google.com): let the user control the threshold using a flag.
727    if (len <= kThreshold) {
728      PrintRawArrayTo(begin, len, os);
729    } else {
730      PrintRawArrayTo(begin, kChunkSize, os);
731      *os << ", ..., ";
732      PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
733    }
734    *os << " }";
735  }
736}
737// This overload prints a (const) char array compactly.
738GTEST_API_ void UniversalPrintArray(
739    const char* begin, size_t len, ::std::ostream* os);
740
741// This overload prints a (const) wchar_t array compactly.
742GTEST_API_ void UniversalPrintArray(
743    const wchar_t* begin, size_t len, ::std::ostream* os);
744
745// Implements printing an array type T[N].
746template <typename T, size_t N>
747class UniversalPrinter<T[N]> {
748 public:
749  // Prints the given array, omitting some elements when there are too
750  // many.
751  static void Print(const T (&a)[N], ::std::ostream* os) {
752    UniversalPrintArray(a, N, os);
753  }
754};
755
756// Implements printing a reference type T&.
757template <typename T>
758class UniversalPrinter<T&> {
759 public:
760  // MSVC warns about adding const to a function type, so we want to
761  // disable the warning.
762  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
763
764  static void Print(const T& value, ::std::ostream* os) {
765    // Prints the address of the value.  We use reinterpret_cast here
766    // as static_cast doesn't compile when T is a function type.
767    *os << "@" << reinterpret_cast<const void*>(&value) << " ";
768
769    // Then prints the value itself.
770    UniversalPrint(value, os);
771  }
772
773  GTEST_DISABLE_MSC_WARNINGS_POP_()
774};
775
776// Prints a value tersely: for a reference type, the referenced value
777// (but not the address) is printed; for a (const) char pointer, the
778// NUL-terminated string (but not the pointer) is printed.
779
780template <typename T>
781class UniversalTersePrinter {
782 public:
783  static void Print(const T& value, ::std::ostream* os) {
784    UniversalPrint(value, os);
785  }
786};
787template <typename T>
788class UniversalTersePrinter<T&> {
789 public:
790  static void Print(const T& value, ::std::ostream* os) {
791    UniversalPrint(value, os);
792  }
793};
794template <typename T, size_t N>
795class UniversalTersePrinter<T[N]> {
796 public:
797  static void Print(const T (&value)[N], ::std::ostream* os) {
798    UniversalPrinter<T[N]>::Print(value, os);
799  }
800};
801template <>
802class UniversalTersePrinter<const char*> {
803 public:
804  static void Print(const char* str, ::std::ostream* os) {
805    if (str == NULL) {
806      *os << "NULL";
807    } else {
808      UniversalPrint(string(str), os);
809    }
810  }
811};
812template <>
813class UniversalTersePrinter<char*> {
814 public:
815  static void Print(char* str, ::std::ostream* os) {
816    UniversalTersePrinter<const char*>::Print(str, os);
817  }
818};
819
820#if GTEST_HAS_STD_WSTRING
821template <>
822class UniversalTersePrinter<const wchar_t*> {
823 public:
824  static void Print(const wchar_t* str, ::std::ostream* os) {
825    if (str == NULL) {
826      *os << "NULL";
827    } else {
828      UniversalPrint(::std::wstring(str), os);
829    }
830  }
831};
832#endif
833
834template <>
835class UniversalTersePrinter<wchar_t*> {
836 public:
837  static void Print(wchar_t* str, ::std::ostream* os) {
838    UniversalTersePrinter<const wchar_t*>::Print(str, os);
839  }
840};
841
842template <typename T>
843void UniversalTersePrint(const T& value, ::std::ostream* os) {
844  UniversalTersePrinter<T>::Print(value, os);
845}
846
847// Prints a value using the type inferred by the compiler.  The
848// difference between this and UniversalTersePrint() is that for a
849// (const) char pointer, this prints both the pointer and the
850// NUL-terminated string.
851template <typename T>
852void UniversalPrint(const T& value, ::std::ostream* os) {
853  // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
854  // UniversalPrinter with T directly.
855  typedef T T1;
856  UniversalPrinter<T1>::Print(value, os);
857}
858
859typedef ::std::vector<string> Strings;
860
861// TuplePolicy<TupleT> must provide:
862// - tuple_size
863//     size of tuple TupleT.
864// - get<size_t I>(const TupleT& t)
865//     static function extracting element I of tuple TupleT.
866// - tuple_element<size_t I>::type
867//     type of element I of tuple TupleT.
868template <typename TupleT>
869struct TuplePolicy;
870
871#if GTEST_HAS_TR1_TUPLE
872template <typename TupleT>
873struct TuplePolicy {
874  typedef TupleT Tuple;
875  static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value;
876
877  template <size_t I>
878  struct tuple_element : ::std::tr1::tuple_element<I, Tuple> {};
879
880  template <size_t I>
881  static typename AddReference<
882      const typename ::std::tr1::tuple_element<I, Tuple>::type>::type get(
883      const Tuple& tuple) {
884    return ::std::tr1::get<I>(tuple);
885  }
886};
887template <typename TupleT>
888const size_t TuplePolicy<TupleT>::tuple_size;
889#endif  // GTEST_HAS_TR1_TUPLE
890
891#if GTEST_HAS_STD_TUPLE_
892template <typename... Types>
893struct TuplePolicy< ::std::tuple<Types...> > {
894  typedef ::std::tuple<Types...> Tuple;
895  static const size_t tuple_size = ::std::tuple_size<Tuple>::value;
896
897  template <size_t I>
898  struct tuple_element : ::std::tuple_element<I, Tuple> {};
899
900  template <size_t I>
901  static const typename ::std::tuple_element<I, Tuple>::type& get(
902      const Tuple& tuple) {
903    return ::std::get<I>(tuple);
904  }
905};
906template <typename... Types>
907const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size;
908#endif  // GTEST_HAS_STD_TUPLE_
909
910#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
911// This helper template allows PrintTo() for tuples and
912// UniversalTersePrintTupleFieldsToStrings() to be defined by
913// induction on the number of tuple fields.  The idea is that
914// TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N
915// fields in tuple t, and can be defined in terms of
916// TuplePrefixPrinter<N - 1>.
917//
918// The inductive case.
919template <size_t N>
920struct TuplePrefixPrinter {
921  // Prints the first N fields of a tuple.
922  template <typename Tuple>
923  static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
924    TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
925    GTEST_INTENTIONAL_CONST_COND_PUSH_()
926    if (N > 1) {
927    GTEST_INTENTIONAL_CONST_COND_POP_()
928      *os << ", ";
929    }
930    UniversalPrinter<
931        typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type>
932        ::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os);
933  }
934
935  // Tersely prints the first N fields of a tuple to a string vector,
936  // one element for each field.
937  template <typename Tuple>
938  static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {
939    TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings);
940    ::std::stringstream ss;
941    UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss);
942    strings->push_back(ss.str());
943  }
944};
945
946// Base case.
947template <>
948struct TuplePrefixPrinter<0> {
949  template <typename Tuple>
950  static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}
951
952  template <typename Tuple>
953  static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}
954};
955
956// Helper function for printing a tuple.
957// Tuple must be either std::tr1::tuple or std::tuple type.
958template <typename Tuple>
959void PrintTupleTo(const Tuple& t, ::std::ostream* os) {
960  *os << "(";
961  TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os);
962  *os << ")";
963}
964
965// Prints the fields of a tuple tersely to a string vector, one
966// element for each field.  See the comment before
967// UniversalTersePrint() for how we define "tersely".
968template <typename Tuple>
969Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
970  Strings result;
971  TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::
972      TersePrintPrefixToStrings(value, &result);
973  return result;
974}
975#endif  // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
976
977}  // namespace internal
978
979template <typename T>
980::std::string PrintToString(const T& value) {
981  ::std::stringstream ss;
982  internal::UniversalTersePrinter<T>::Print(value, &ss);
983  return ss.str();
984}
985
986}  // namespace testing
987
988// Include any custom printer added by the local installation.
989// We must include this header at the end to make sure it can use the
990// declarations from this file.
991#include "gtest/internal/custom/gtest-printers.h"
992
993#endif  // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest-spi.h
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Utilities for testing Google Test itself and code that uses Google Test
33// (e.g. frameworks built on top of Google Test).
34
35#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
36#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
37
38#include "gtest/gtest.h"
39
40namespace testing {
41
42// This helper class can be used to mock out Google Test failure reporting
43// so that we can test Google Test or code that builds on Google Test.
44//
45// An object of this class appends a TestPartResult object to the
46// TestPartResultArray object given in the constructor whenever a Google Test
47// failure is reported. It can either intercept only failures that are
48// generated in the same thread that created this object or it can intercept
49// all generated failures. The scope of this mock object can be controlled with
50// the second argument to the two arguments constructor.
51class GTEST_API_ ScopedFakeTestPartResultReporter
52    : public TestPartResultReporterInterface {
53 public:
54  // The two possible mocking modes of this object.
55  enum InterceptMode {
56    INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
57    INTERCEPT_ALL_THREADS           // Intercepts all failures.
58  };
59
60  // The c'tor sets this object as the test part result reporter used
61  // by Google Test.  The 'result' parameter specifies where to report the
62  // results. This reporter will only catch failures generated in the current
63  // thread. DEPRECATED
64  explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
65
66  // Same as above, but you can choose the interception scope of this object.
67  ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
68                                   TestPartResultArray* result);
69
70  // The d'tor restores the previous test part result reporter.
71  virtual ~ScopedFakeTestPartResultReporter();
72
73  // Appends the TestPartResult object to the TestPartResultArray
74  // received in the constructor.
75  //
76  // This method is from the TestPartResultReporterInterface
77  // interface.
78  virtual void ReportTestPartResult(const TestPartResult& result);
79 private:
80  void Init();
81
82  const InterceptMode intercept_mode_;
83  TestPartResultReporterInterface* old_reporter_;
84  TestPartResultArray* const result_;
85
86  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
87};
88
89namespace internal {
90
91// A helper class for implementing EXPECT_FATAL_FAILURE() and
92// EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
93// TestPartResultArray contains exactly one failure that has the given
94// type and contains the given substring.  If that's not the case, a
95// non-fatal failure will be generated.
96class GTEST_API_ SingleFailureChecker {
97 public:
98  // The constructor remembers the arguments.
99  SingleFailureChecker(const TestPartResultArray* results,
100                       TestPartResult::Type type,
101                       const string& substr);
102  ~SingleFailureChecker();
103 private:
104  const TestPartResultArray* const results_;
105  const TestPartResult::Type type_;
106  const string substr_;
107
108  GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
109};
110
111}  // namespace internal
112
113}  // namespace testing
114
115// A set of macros for testing Google Test assertions or code that's expected
116// to generate Google Test fatal failures.  It verifies that the given
117// statement will cause exactly one fatal Google Test failure with 'substr'
118// being part of the failure message.
119//
120// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
121// affects and considers failures generated in the current thread and
122// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
123//
124// The verification of the assertion is done correctly even when the statement
125// throws an exception or aborts the current function.
126//
127// Known restrictions:
128//   - 'statement' cannot reference local non-static variables or
129//     non-static members of the current object.
130//   - 'statement' cannot return a value.
131//   - You cannot stream a failure message to this macro.
132//
133// Note that even though the implementations of the following two
134// macros are much alike, we cannot refactor them to use a common
135// helper macro, due to some peculiarity in how the preprocessor
136// works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
137// gtest_unittest.cc will fail to compile if we do that.
138#define EXPECT_FATAL_FAILURE(statement, substr) \
139  do { \
140    class GTestExpectFatalFailureHelper {\
141     public:\
142      static void Execute() { statement; }\
143    };\
144    ::testing::TestPartResultArray gtest_failures;\
145    ::testing::internal::SingleFailureChecker gtest_checker(\
146        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
147    {\
148      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
149          ::testing::ScopedFakeTestPartResultReporter:: \
150          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
151      GTestExpectFatalFailureHelper::Execute();\
152    }\
153  } while (::testing::internal::AlwaysFalse())
154
155#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
156  do { \
157    class GTestExpectFatalFailureHelper {\
158     public:\
159      static void Execute() { statement; }\
160    };\
161    ::testing::TestPartResultArray gtest_failures;\
162    ::testing::internal::SingleFailureChecker gtest_checker(\
163        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
164    {\
165      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
166          ::testing::ScopedFakeTestPartResultReporter:: \
167          INTERCEPT_ALL_THREADS, &gtest_failures);\
168      GTestExpectFatalFailureHelper::Execute();\
169    }\
170  } while (::testing::internal::AlwaysFalse())
171
172// A macro for testing Google Test assertions or code that's expected to
173// generate Google Test non-fatal failures.  It asserts that the given
174// statement will cause exactly one non-fatal Google Test failure with 'substr'
175// being part of the failure message.
176//
177// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
178// affects and considers failures generated in the current thread and
179// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
180//
181// 'statement' is allowed to reference local variables and members of
182// the current object.
183//
184// The verification of the assertion is done correctly even when the statement
185// throws an exception or aborts the current function.
186//
187// Known restrictions:
188//   - You cannot stream a failure message to this macro.
189//
190// Note that even though the implementations of the following two
191// macros are much alike, we cannot refactor them to use a common
192// helper macro, due to some peculiarity in how the preprocessor
193// works.  If we do that, the code won't compile when the user gives
194// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
195// expands to code containing an unprotected comma.  The
196// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
197// catches that.
198//
199// For the same reason, we have to write
200//   if (::testing::internal::AlwaysTrue()) { statement; }
201// instead of
202//   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
203// to avoid an MSVC warning on unreachable code.
204#define EXPECT_NONFATAL_FAILURE(statement, substr) \
205  do {\
206    ::testing::TestPartResultArray gtest_failures;\
207    ::testing::internal::SingleFailureChecker gtest_checker(\
208        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
209        (substr));\
210    {\
211      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
212          ::testing::ScopedFakeTestPartResultReporter:: \
213          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
214      if (::testing::internal::AlwaysTrue()) { statement; }\
215    }\
216  } while (::testing::internal::AlwaysFalse())
217
218#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
219  do {\
220    ::testing::TestPartResultArray gtest_failures;\
221    ::testing::internal::SingleFailureChecker gtest_checker(\
222        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
223        (substr));\
224    {\
225      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
226          ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
227          &gtest_failures);\
228      if (::testing::internal::AlwaysTrue()) { statement; }\
229    }\
230  } while (::testing::internal::AlwaysFalse())
231
232#endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest-test-part.h
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: mheule@google.com (Markus Heule)
31//
32
33#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
34#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
35
36#include <iosfwd>
37#include <vector>
38#include "gtest/internal/gtest-internal.h"
39#include "gtest/internal/gtest-string.h"
40
41namespace testing {
42
43// A copyable object representing the result of a test part (i.e. an
44// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
45//
46// Don't inherit from TestPartResult as its destructor is not virtual.
47class GTEST_API_ TestPartResult {
48 public:
49  // The possible outcomes of a test part (i.e. an assertion or an
50  // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
51  enum Type {
52    kSuccess,          // Succeeded.
53    kNonFatalFailure,  // Failed but the test can continue.
54    kFatalFailure      // Failed and the test should be terminated.
55  };
56
57  // C'tor.  TestPartResult does NOT have a default constructor.
58  // Always use this constructor (with parameters) to create a
59  // TestPartResult object.
60  TestPartResult(Type a_type,
61                 const char* a_file_name,
62                 int a_line_number,
63                 const char* a_message)
64      : type_(a_type),
65        file_name_(a_file_name == NULL ? "" : a_file_name),
66        line_number_(a_line_number),
67        summary_(ExtractSummary(a_message)),
68        message_(a_message) {
69  }
70
71  // Gets the outcome of the test part.
72  Type type() const { return type_; }
73
74  // Gets the name of the source file where the test part took place, or
75  // NULL if it's unknown.
76  const char* file_name() const {
77    return file_name_.empty() ? NULL : file_name_.c_str();
78  }
79
80  // Gets the line in the source file where the test part took place,
81  // or -1 if it's unknown.
82  int line_number() const { return line_number_; }
83
84  // Gets the summary of the failure message.
85  const char* summary() const { return summary_.c_str(); }
86
87  // Gets the message associated with the test part.
88  const char* message() const { return message_.c_str(); }
89
90  // Returns true iff the test part passed.
91  bool passed() const { return type_ == kSuccess; }
92
93  // Returns true iff the test part failed.
94  bool failed() const { return type_ != kSuccess; }
95
96  // Returns true iff the test part non-fatally failed.
97  bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
98
99  // Returns true iff the test part fatally failed.
100  bool fatally_failed() const { return type_ == kFatalFailure; }
101
102 private:
103  Type type_;
104
105  // Gets the summary of the failure message by omitting the stack
106  // trace in it.
107  static std::string ExtractSummary(const char* message);
108
109  // The name of the source file where the test part took place, or
110  // "" if the source file is unknown.
111  std::string file_name_;
112  // The line in the source file where the test part took place, or -1
113  // if the line number is unknown.
114  int line_number_;
115  std::string summary_;  // The test failure summary.
116  std::string message_;  // The test failure message.
117};
118
119// Prints a TestPartResult object.
120std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
121
122// An array of TestPartResult objects.
123//
124// Don't inherit from TestPartResultArray as its destructor is not
125// virtual.
126class GTEST_API_ TestPartResultArray {
127 public:
128  TestPartResultArray() {}
129
130  // Appends the given TestPartResult to the array.
131  void Append(const TestPartResult& result);
132
133  // Returns the TestPartResult at the given index (0-based).
134  const TestPartResult& GetTestPartResult(int index) const;
135
136  // Returns the number of TestPartResult objects in the array.
137  int size() const;
138
139 private:
140  std::vector<TestPartResult> array_;
141
142  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
143};
144
145// This interface knows how to report a test part result.
146class TestPartResultReporterInterface {
147 public:
148  virtual ~TestPartResultReporterInterface() {}
149
150  virtual void ReportTestPartResult(const TestPartResult& result) = 0;
151};
152
153namespace internal {
154
155// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
156// statement generates new fatal failures. To do so it registers itself as the
157// current test part result reporter. Besides checking if fatal failures were
158// reported, it only delegates the reporting to the former result reporter.
159// The original result reporter is restored in the destructor.
160// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
161class GTEST_API_ HasNewFatalFailureHelper
162    : public TestPartResultReporterInterface {
163 public:
164  HasNewFatalFailureHelper();
165  virtual ~HasNewFatalFailureHelper();
166  virtual void ReportTestPartResult(const TestPartResult& result);
167  bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
168 private:
169  bool has_new_fatal_failure_;
170  TestPartResultReporterInterface* original_reporter_;
171
172  GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
173};
174
175}  // namespace internal
176
177}  // namespace testing
178
179#endif  // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest-typed-test.h
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
33#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
34
35// This header implements typed tests and type-parameterized tests.
36
37// Typed (aka type-driven) tests repeat the same test for types in a
38// list.  You must know which types you want to test with when writing
39// typed tests. Here's how you do it:
40
41#if 0
42
43// First, define a fixture class template.  It should be parameterized
44// by a type.  Remember to derive it from testing::Test.
45template <typename T>
46class FooTest : public testing::Test {
47 public:
48  ...
49  typedef std::list<T> List;
50  static T shared_;
51  T value_;
52};
53
54// Next, associate a list of types with the test case, which will be
55// repeated for each type in the list.  The typedef is necessary for
56// the macro to parse correctly.
57typedef testing::Types<char, int, unsigned int> MyTypes;
58TYPED_TEST_CASE(FooTest, MyTypes);
59
60// If the type list contains only one type, you can write that type
61// directly without Types<...>:
62//   TYPED_TEST_CASE(FooTest, int);
63
64// Then, use TYPED_TEST() instead of TEST_F() to define as many typed
65// tests for this test case as you want.
66TYPED_TEST(FooTest, DoesBlah) {
67  // Inside a test, refer to TypeParam to get the type parameter.
68  // Since we are inside a derived class template, C++ requires use to
69  // visit the members of FooTest via 'this'.
70  TypeParam n = this->value_;
71
72  // To visit static members of the fixture, add the TestFixture::
73  // prefix.
74  n += TestFixture::shared_;
75
76  // To refer to typedefs in the fixture, add the "typename
77  // TestFixture::" prefix.
78  typename TestFixture::List values;
79  values.push_back(n);
80  ...
81}
82
83TYPED_TEST(FooTest, HasPropertyA) { ... }
84
85#endif  // 0
86
87// Type-parameterized tests are abstract test patterns parameterized
88// by a type.  Compared with typed tests, type-parameterized tests
89// allow you to define the test pattern without knowing what the type
90// parameters are.  The defined pattern can be instantiated with
91// different types any number of times, in any number of translation
92// units.
93//
94// If you are designing an interface or concept, you can define a
95// suite of type-parameterized tests to verify properties that any
96// valid implementation of the interface/concept should have.  Then,
97// each implementation can easily instantiate the test suite to verify
98// that it conforms to the requirements, without having to write
99// similar tests repeatedly.  Here's an example:
100
101#if 0
102
103// First, define a fixture class template.  It should be parameterized
104// by a type.  Remember to derive it from testing::Test.
105template <typename T>
106class FooTest : public testing::Test {
107  ...
108};
109
110// Next, declare that you will define a type-parameterized test case
111// (the _P suffix is for "parameterized" or "pattern", whichever you
112// prefer):
113TYPED_TEST_CASE_P(FooTest);
114
115// Then, use TYPED_TEST_P() to define as many type-parameterized tests
116// for this type-parameterized test case as you want.
117TYPED_TEST_P(FooTest, DoesBlah) {
118  // Inside a test, refer to TypeParam to get the type parameter.
119  TypeParam n = 0;
120  ...
121}
122
123TYPED_TEST_P(FooTest, HasPropertyA) { ... }
124
125// Now the tricky part: you need to register all test patterns before
126// you can instantiate them.  The first argument of the macro is the
127// test case name; the rest are the names of the tests in this test
128// case.
129REGISTER_TYPED_TEST_CASE_P(FooTest,
130                           DoesBlah, HasPropertyA);
131
132// Finally, you are free to instantiate the pattern with the types you
133// want.  If you put the above code in a header file, you can #include
134// it in multiple C++ source files and instantiate it multiple times.
135//
136// To distinguish different instances of the pattern, the first
137// argument to the INSTANTIATE_* macro is a prefix that will be added
138// to the actual test case name.  Remember to pick unique prefixes for
139// different instances.
140typedef testing::Types<char, int, unsigned int> MyTypes;
141INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
142
143// If the type list contains only one type, you can write that type
144// directly without Types<...>:
145//   INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
146
147#endif  // 0
148
149#include "gtest/internal/gtest-port.h"
150#include "gtest/internal/gtest-type-util.h"
151
152// Implements typed tests.
153
154#if GTEST_HAS_TYPED_TEST
155
156// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
157//
158// Expands to the name of the typedef for the type parameters of the
159// given test case.
160# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_
161
162// The 'Types' template argument below must have spaces around it
163// since some compilers may choke on '>>' when passing a template
164// instance (e.g. Types<int>)
165# define TYPED_TEST_CASE(CaseName, Types) \
166  typedef ::testing::internal::TypeList< Types >::type \
167      GTEST_TYPE_PARAMS_(CaseName)
168
169# define TYPED_TEST(CaseName, TestName) \
170  template <typename gtest_TypeParam_> \
171  class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
172      : public CaseName<gtest_TypeParam_> { \
173   private: \
174    typedef CaseName<gtest_TypeParam_> TestFixture; \
175    typedef gtest_TypeParam_ TypeParam; \
176    virtual void TestBody(); \
177  }; \
178  bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \
179      ::testing::internal::TypeParameterizedTest< \
180          CaseName, \
181          ::testing::internal::TemplateSel< \
182              GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \
183          GTEST_TYPE_PARAMS_(CaseName)>::Register(\
184              "", ::testing::internal::CodeLocation(__FILE__, __LINE__), \
185              #CaseName, #TestName, 0); \
186  template <typename gtest_TypeParam_> \
187  void GTEST_TEST_CLASS_NAME_(CaseName, TestName)<gtest_TypeParam_>::TestBody()
188
189#endif  // GTEST_HAS_TYPED_TEST
190
191// Implements type-parameterized tests.
192
193#if GTEST_HAS_TYPED_TEST_P
194
195// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
196//
197// Expands to the namespace name that the type-parameterized tests for
198// the given type-parameterized test case are defined in.  The exact
199// name of the namespace is subject to change without notice.
200# define GTEST_CASE_NAMESPACE_(TestCaseName) \
201  gtest_case_##TestCaseName##_
202
203// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
204//
205// Expands to the name of the variable used to remember the names of
206// the defined tests in the given test case.
207# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \
208  gtest_typed_test_case_p_state_##TestCaseName##_
209
210// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
211//
212// Expands to the name of the variable used to remember the names of
213// the registered tests in the given test case.
214# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \
215  gtest_registered_test_names_##TestCaseName##_
216
217// The variables defined in the type-parameterized test macros are
218// static as typically these macros are used in a .h file that can be
219// #included in multiple translation units linked together.
220# define TYPED_TEST_CASE_P(CaseName) \
221  static ::testing::internal::TypedTestCasePState \
222      GTEST_TYPED_TEST_CASE_P_STATE_(CaseName)
223
224# define TYPED_TEST_P(CaseName, TestName) \
225  namespace GTEST_CASE_NAMESPACE_(CaseName) { \
226  template <typename gtest_TypeParam_> \
227  class TestName : public CaseName<gtest_TypeParam_> { \
228   private: \
229    typedef CaseName<gtest_TypeParam_> TestFixture; \
230    typedef gtest_TypeParam_ TypeParam; \
231    virtual void TestBody(); \
232  }; \
233  static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
234      GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\
235          __FILE__, __LINE__, #CaseName, #TestName); \
236  } \
237  template <typename gtest_TypeParam_> \
238  void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody()
239
240# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \
241  namespace GTEST_CASE_NAMESPACE_(CaseName) { \
242  typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \
243  } \
244  static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \
245      GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\
246          __FILE__, __LINE__, #__VA_ARGS__)
247
248// The 'Types' template argument below must have spaces around it
249// since some compilers may choke on '>>' when passing a template
250// instance (e.g. Types<int>)
251# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \
252  bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \
253      ::testing::internal::TypeParameterizedTestCase<CaseName, \
254          GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \
255          ::testing::internal::TypeList< Types >::type>::Register(\
256              #Prefix, \
257              ::testing::internal::CodeLocation(__FILE__, __LINE__), \
258              &GTEST_TYPED_TEST_CASE_P_STATE_(CaseName), \
259              #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName))
260
261#endif  // GTEST_HAS_TYPED_TEST_P
262
263#endif  // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file defines the public API for Google Test.  It should be
35// included by any test program that uses Google Test.
36//
37// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
38// leave some internal implementation details in this header file.
39// They are clearly marked by comments like this:
40//
41//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
42//
43// Such code is NOT meant to be used by a user directly, and is subject
44// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
45// program!
46//
47// Acknowledgment: Google Test borrowed the idea of automatic test
48// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
49// easyUnit framework.
50
51#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
52#define GTEST_INCLUDE_GTEST_GTEST_H_
53
54#include <limits>
55#include <ostream>
56#include <vector>
57
58#include "gtest/internal/gtest-internal.h"
59#include "gtest/internal/gtest-string.h"
60#include "gtest/gtest-death-test.h"
61#include "gtest/gtest-message.h"
62#include "gtest/gtest-param-test.h"
63#include "gtest/gtest-printers.h"
64#include "gtest/gtest_prod.h"
65#include "gtest/gtest-test-part.h"
66#include "gtest/gtest-typed-test.h"
67
68// Depending on the platform, different string classes are available.
69// On Linux, in addition to ::std::string, Google also makes use of
70// class ::string, which has the same interface as ::std::string, but
71// has a different implementation.
72//
73// You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
74// ::string is available AND is a distinct type to ::std::string, or
75// define it to 0 to indicate otherwise.
76//
77// If ::std::string and ::string are the same class on your platform
78// due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0.
79//
80// If you do not define GTEST_HAS_GLOBAL_STRING, it is defined
81// heuristically.
82
83namespace testing {
84
85// Declares the flags.
86
87// This flag temporary enables the disabled tests.
88GTEST_DECLARE_bool_(also_run_disabled_tests);
89
90// This flag brings the debugger on an assertion failure.
91GTEST_DECLARE_bool_(break_on_failure);
92
93// This flag controls whether Google Test catches all test-thrown exceptions
94// and logs them as failures.
95GTEST_DECLARE_bool_(catch_exceptions);
96
97// This flag enables using colors in terminal output. Available values are
98// "yes" to enable colors, "no" (disable colors), or "auto" (the default)
99// to let Google Test decide.
100GTEST_DECLARE_string_(color);
101
102// This flag sets up the filter to select by name using a glob pattern
103// the tests to run. If the filter is not given all tests are executed.
104GTEST_DECLARE_string_(filter);
105
106// This flag causes the Google Test to list tests. None of the tests listed
107// are actually run if the flag is provided.
108GTEST_DECLARE_bool_(list_tests);
109
110// This flag controls whether Google Test emits a detailed XML report to a file
111// in addition to its normal textual output.
112GTEST_DECLARE_string_(output);
113
114// This flags control whether Google Test prints the elapsed time for each
115// test.
116GTEST_DECLARE_bool_(print_time);
117
118// This flag specifies the random number seed.
119GTEST_DECLARE_int32_(random_seed);
120
121// This flag sets how many times the tests are repeated. The default value
122// is 1. If the value is -1 the tests are repeating forever.
123GTEST_DECLARE_int32_(repeat);
124
125// This flag controls whether Google Test includes Google Test internal
126// stack frames in failure stack traces.
127GTEST_DECLARE_bool_(show_internal_stack_frames);
128
129// When this flag is specified, tests' order is randomized on every iteration.
130GTEST_DECLARE_bool_(shuffle);
131
132// This flag specifies the maximum number of stack frames to be
133// printed in a failure message.
134GTEST_DECLARE_int32_(stack_trace_depth);
135
136// When this flag is specified, a failed assertion will throw an
137// exception if exceptions are enabled, or exit the program with a
138// non-zero code otherwise.
139GTEST_DECLARE_bool_(throw_on_failure);
140
141// When this flag is set with a "host:port" string, on supported
142// platforms test results are streamed to the specified port on
143// the specified host machine.
144GTEST_DECLARE_string_(stream_result_to);
145
146// The upper limit for valid stack trace depths.
147const int kMaxStackTraceDepth = 100;
148
149namespace internal {
150
151class AssertHelper;
152class DefaultGlobalTestPartResultReporter;
153class ExecDeathTest;
154class NoExecDeathTest;
155class FinalSuccessChecker;
156class GTestFlagSaver;
157class StreamingListenerTest;
158class TestResultAccessor;
159class TestEventListenersAccessor;
160class TestEventRepeater;
161class UnitTestRecordPropertyTestHelper;
162class WindowsDeathTest;
163class UnitTestImpl* GetUnitTestImpl();
164void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
165                                    const std::string& message);
166
167}  // namespace internal
168
169// The friend relationship of some of these classes is cyclic.
170// If we don't forward declare them the compiler might confuse the classes
171// in friendship clauses with same named classes on the scope.
172class Test;
173class TestCase;
174class TestInfo;
175class UnitTest;
176
177// A class for indicating whether an assertion was successful.  When
178// the assertion wasn't successful, the AssertionResult object
179// remembers a non-empty message that describes how it failed.
180//
181// To create an instance of this class, use one of the factory functions
182// (AssertionSuccess() and AssertionFailure()).
183//
184// This class is useful for two purposes:
185//   1. Defining predicate functions to be used with Boolean test assertions
186//      EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
187//   2. Defining predicate-format functions to be
188//      used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
189//
190// For example, if you define IsEven predicate:
191//
192//   testing::AssertionResult IsEven(int n) {
193//     if ((n % 2) == 0)
194//       return testing::AssertionSuccess();
195//     else
196//       return testing::AssertionFailure() << n << " is odd";
197//   }
198//
199// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
200// will print the message
201//
202//   Value of: IsEven(Fib(5))
203//     Actual: false (5 is odd)
204//   Expected: true
205//
206// instead of a more opaque
207//
208//   Value of: IsEven(Fib(5))
209//     Actual: false
210//   Expected: true
211//
212// in case IsEven is a simple Boolean predicate.
213//
214// If you expect your predicate to be reused and want to support informative
215// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
216// about half as often as positive ones in our tests), supply messages for
217// both success and failure cases:
218//
219//   testing::AssertionResult IsEven(int n) {
220//     if ((n % 2) == 0)
221//       return testing::AssertionSuccess() << n << " is even";
222//     else
223//       return testing::AssertionFailure() << n << " is odd";
224//   }
225//
226// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
227//
228//   Value of: IsEven(Fib(6))
229//     Actual: true (8 is even)
230//   Expected: false
231//
232// NB: Predicates that support negative Boolean assertions have reduced
233// performance in positive ones so be careful not to use them in tests
234// that have lots (tens of thousands) of positive Boolean assertions.
235//
236// To use this class with EXPECT_PRED_FORMAT assertions such as:
237//
238//   // Verifies that Foo() returns an even number.
239//   EXPECT_PRED_FORMAT1(IsEven, Foo());
240//
241// you need to define:
242//
243//   testing::AssertionResult IsEven(const char* expr, int n) {
244//     if ((n % 2) == 0)
245//       return testing::AssertionSuccess();
246//     else
247//       return testing::AssertionFailure()
248//         << "Expected: " << expr << " is even\n  Actual: it's " << n;
249//   }
250//
251// If Foo() returns 5, you will see the following message:
252//
253//   Expected: Foo() is even
254//     Actual: it's 5
255//
256class GTEST_API_ AssertionResult {
257 public:
258  // Copy constructor.
259  // Used in EXPECT_TRUE/FALSE(assertion_result).
260  AssertionResult(const AssertionResult& other);
261
262  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
263
264  // Used in the EXPECT_TRUE/FALSE(bool_expression).
265  //
266  // T must be contextually convertible to bool.
267  //
268  // The second parameter prevents this overload from being considered if
269  // the argument is implicitly convertible to AssertionResult. In that case
270  // we want AssertionResult's copy constructor to be used.
271  template <typename T>
272  explicit AssertionResult(
273      const T& success,
274      typename internal::EnableIf<
275          !internal::ImplicitlyConvertible<T, AssertionResult>::value>::type*
276          /*enabler*/ = NULL)
277      : success_(success) {}
278
279  GTEST_DISABLE_MSC_WARNINGS_POP_()
280
281  // Assignment operator.
282  AssertionResult& operator=(AssertionResult other) {
283    swap(other);
284    return *this;
285  }
286
287  // Returns true iff the assertion succeeded.
288  operator bool() const { return success_; }  // NOLINT
289
290  // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
291  AssertionResult operator!() const;
292
293  // Returns the text streamed into this AssertionResult. Test assertions
294  // use it when they fail (i.e., the predicate's outcome doesn't match the
295  // assertion's expectation). When nothing has been streamed into the
296  // object, returns an empty string.
297  const char* message() const {
298    return message_.get() != NULL ?  message_->c_str() : "";
299  }
300  // TODO(vladl@google.com): Remove this after making sure no clients use it.
301  // Deprecated; please use message() instead.
302  const char* failure_message() const { return message(); }
303
304  // Streams a custom failure message into this object.
305  template <typename T> AssertionResult& operator<<(const T& value) {
306    AppendMessage(Message() << value);
307    return *this;
308  }
309
310  // Allows streaming basic output manipulators such as endl or flush into
311  // this object.
312  AssertionResult& operator<<(
313      ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
314    AppendMessage(Message() << basic_manipulator);
315    return *this;
316  }
317
318 private:
319  // Appends the contents of message to message_.
320  void AppendMessage(const Message& a_message) {
321    if (message_.get() == NULL)
322      message_.reset(new ::std::string);
323    message_->append(a_message.GetString().c_str());
324  }
325
326  // Swap the contents of this AssertionResult with other.
327  void swap(AssertionResult& other);
328
329  // Stores result of the assertion predicate.
330  bool success_;
331  // Stores the message describing the condition in case the expectation
332  // construct is not satisfied with the predicate's outcome.
333  // Referenced via a pointer to avoid taking too much stack frame space
334  // with test assertions.
335  internal::scoped_ptr< ::std::string> message_;
336};
337
338// Makes a successful assertion result.
339GTEST_API_ AssertionResult AssertionSuccess();
340
341// Makes a failed assertion result.
342GTEST_API_ AssertionResult AssertionFailure();
343
344// Makes a failed assertion result with the given failure message.
345// Deprecated; use AssertionFailure() << msg.
346GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
347
348// The abstract class that all tests inherit from.
349//
350// In Google Test, a unit test program contains one or many TestCases, and
351// each TestCase contains one or many Tests.
352//
353// When you define a test using the TEST macro, you don't need to
354// explicitly derive from Test - the TEST macro automatically does
355// this for you.
356//
357// The only time you derive from Test is when defining a test fixture
358// to be used a TEST_F.  For example:
359//
360//   class FooTest : public testing::Test {
361//    protected:
362//     void SetUp() override { ... }
363//     void TearDown() override { ... }
364//     ...
365//   };
366//
367//   TEST_F(FooTest, Bar) { ... }
368//   TEST_F(FooTest, Baz) { ... }
369//
370// Test is not copyable.
371class GTEST_API_ Test {
372 public:
373  friend class TestInfo;
374
375  // Defines types for pointers to functions that set up and tear down
376  // a test case.
377  typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
378  typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
379
380  // The d'tor is virtual as we intend to inherit from Test.
381  virtual ~Test();
382
383  // Sets up the stuff shared by all tests in this test case.
384  //
385  // Google Test will call Foo::SetUpTestCase() before running the first
386  // test in test case Foo.  Hence a sub-class can define its own
387  // SetUpTestCase() method to shadow the one defined in the super
388  // class.
389  static void SetUpTestCase() {}
390
391  // Tears down the stuff shared by all tests in this test case.
392  //
393  // Google Test will call Foo::TearDownTestCase() after running the last
394  // test in test case Foo.  Hence a sub-class can define its own
395  // TearDownTestCase() method to shadow the one defined in the super
396  // class.
397  static void TearDownTestCase() {}
398
399  // Returns true iff the current test has a fatal failure.
400  static bool HasFatalFailure();
401
402  // Returns true iff the current test has a non-fatal failure.
403  static bool HasNonfatalFailure();
404
405  // Returns true iff the current test has a (either fatal or
406  // non-fatal) failure.
407  static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
408
409  // Logs a property for the current test, test case, or for the entire
410  // invocation of the test program when used outside of the context of a
411  // test case.  Only the last value for a given key is remembered.  These
412  // are public static so they can be called from utility functions that are
413  // not members of the test fixture.  Calls to RecordProperty made during
414  // lifespan of the test (from the moment its constructor starts to the
415  // moment its destructor finishes) will be output in XML as attributes of
416  // the <testcase> element.  Properties recorded from fixture's
417  // SetUpTestCase or TearDownTestCase are logged as attributes of the
418  // corresponding <testsuite> element.  Calls to RecordProperty made in the
419  // global context (before or after invocation of RUN_ALL_TESTS and from
420  // SetUp/TearDown method of Environment objects registered with Google
421  // Test) will be output as attributes of the <testsuites> element.
422  static void RecordProperty(const std::string& key, const std::string& value);
423  static void RecordProperty(const std::string& key, int value);
424
425 protected:
426  // Creates a Test object.
427  Test();
428
429  // Sets up the test fixture.
430  virtual void SetUp();
431
432  // Tears down the test fixture.
433  virtual void TearDown();
434
435 private:
436  // Returns true iff the current test has the same fixture class as
437  // the first test in the current test case.
438  static bool HasSameFixtureClass();
439
440  // Runs the test after the test fixture has been set up.
441  //
442  // A sub-class must implement this to define the test logic.
443  //
444  // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
445  // Instead, use the TEST or TEST_F macro.
446  virtual void TestBody() = 0;
447
448  // Sets up, executes, and tears down the test.
449  void Run();
450
451  // Deletes self.  We deliberately pick an unusual name for this
452  // internal method to avoid clashing with names used in user TESTs.
453  void DeleteSelf_() { delete this; }
454
455  const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_;
456
457  // Often a user misspells SetUp() as Setup() and spends a long time
458  // wondering why it is never called by Google Test.  The declaration of
459  // the following method is solely for catching such an error at
460  // compile time:
461  //
462  //   - The return type is deliberately chosen to be not void, so it
463  //   will be a conflict if void Setup() is declared in the user's
464  //   test fixture.
465  //
466  //   - This method is private, so it will be another compiler error
467  //   if the method is called from the user's test fixture.
468  //
469  // DO NOT OVERRIDE THIS FUNCTION.
470  //
471  // If you see an error about overriding the following function or
472  // about it being private, you have mis-spelled SetUp() as Setup().
473  struct Setup_should_be_spelled_SetUp {};
474  virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
475
476  // We disallow copying Tests.
477  GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
478};
479
480typedef internal::TimeInMillis TimeInMillis;
481
482// A copyable object representing a user specified test property which can be
483// output as a key/value string pair.
484//
485// Don't inherit from TestProperty as its destructor is not virtual.
486class TestProperty {
487 public:
488  // C'tor.  TestProperty does NOT have a default constructor.
489  // Always use this constructor (with parameters) to create a
490  // TestProperty object.
491  TestProperty(const std::string& a_key, const std::string& a_value) :
492    key_(a_key), value_(a_value) {
493  }
494
495  // Gets the user supplied key.
496  const char* key() const {
497    return key_.c_str();
498  }
499
500  // Gets the user supplied value.
501  const char* value() const {
502    return value_.c_str();
503  }
504
505  // Sets a new value, overriding the one supplied in the constructor.
506  void SetValue(const std::string& new_value) {
507    value_ = new_value;
508  }
509
510 private:
511  // The key supplied by the user.
512  std::string key_;
513  // The value supplied by the user.
514  std::string value_;
515};
516
517// The result of a single Test.  This includes a list of
518// TestPartResults, a list of TestProperties, a count of how many
519// death tests there are in the Test, and how much time it took to run
520// the Test.
521//
522// TestResult is not copyable.
523class GTEST_API_ TestResult {
524 public:
525  // Creates an empty TestResult.
526  TestResult();
527
528  // D'tor.  Do not inherit from TestResult.
529  ~TestResult();
530
531  // Gets the number of all test parts.  This is the sum of the number
532  // of successful test parts and the number of failed test parts.
533  int total_part_count() const;
534
535  // Returns the number of the test properties.
536  int test_property_count() const;
537
538  // Returns true iff the test passed (i.e. no test part failed).
539  bool Passed() const { return !Failed(); }
540
541  // Returns true iff the test failed.
542  bool Failed() const;
543
544  // Returns true iff the test fatally failed.
545  bool HasFatalFailure() const;
546
547  // Returns true iff the test has a non-fatal failure.
548  bool HasNonfatalFailure() const;
549
550  // Returns the elapsed time, in milliseconds.
551  TimeInMillis elapsed_time() const { return elapsed_time_; }
552
553  // Returns the i-th test part result among all the results. i can range
554  // from 0 to test_property_count() - 1. If i is not in that range, aborts
555  // the program.
556  const TestPartResult& GetTestPartResult(int i) const;
557
558  // Returns the i-th test property. i can range from 0 to
559  // test_property_count() - 1. If i is not in that range, aborts the
560  // program.
561  const TestProperty& GetTestProperty(int i) const;
562
563 private:
564  friend class TestInfo;
565  friend class TestCase;
566  friend class UnitTest;
567  friend class internal::DefaultGlobalTestPartResultReporter;
568  friend class internal::ExecDeathTest;
569  friend class internal::TestResultAccessor;
570  friend class internal::UnitTestImpl;
571  friend class internal::WindowsDeathTest;
572
573  // Gets the vector of TestPartResults.
574  const std::vector<TestPartResult>& test_part_results() const {
575    return test_part_results_;
576  }
577
578  // Gets the vector of TestProperties.
579  const std::vector<TestProperty>& test_properties() const {
580    return test_properties_;
581  }
582
583  // Sets the elapsed time.
584  void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
585
586  // Adds a test property to the list. The property is validated and may add
587  // a non-fatal failure if invalid (e.g., if it conflicts with reserved
588  // key names). If a property is already recorded for the same key, the
589  // value will be updated, rather than storing multiple values for the same
590  // key.  xml_element specifies the element for which the property is being
591  // recorded and is used for validation.
592  void RecordProperty(const std::string& xml_element,
593                      const TestProperty& test_property);
594
595  // Adds a failure if the key is a reserved attribute of Google Test
596  // testcase tags.  Returns true if the property is valid.
597  // TODO(russr): Validate attribute names are legal and human readable.
598  static bool ValidateTestProperty(const std::string& xml_element,
599                                   const TestProperty& test_property);
600
601  // Adds a test part result to the list.
602  void AddTestPartResult(const TestPartResult& test_part_result);
603
604  // Returns the death test count.
605  int death_test_count() const { return death_test_count_; }
606
607  // Increments the death test count, returning the new count.
608  int increment_death_test_count() { return ++death_test_count_; }
609
610  // Clears the test part results.
611  void ClearTestPartResults();
612
613  // Clears the object.
614  void Clear();
615
616  // Protects mutable state of the property vector and of owned
617  // properties, whose values may be updated.
618  internal::Mutex test_properites_mutex_;
619
620  // The vector of TestPartResults
621  std::vector<TestPartResult> test_part_results_;
622  // The vector of TestProperties
623  std::vector<TestProperty> test_properties_;
624  // Running count of death tests.
625  int death_test_count_;
626  // The elapsed time, in milliseconds.
627  TimeInMillis elapsed_time_;
628
629  // We disallow copying TestResult.
630  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
631};  // class TestResult
632
633// A TestInfo object stores the following information about a test:
634//
635//   Test case name
636//   Test name
637//   Whether the test should be run
638//   A function pointer that creates the test object when invoked
639//   Test result
640//
641// The constructor of TestInfo registers itself with the UnitTest
642// singleton such that the RUN_ALL_TESTS() macro knows which tests to
643// run.
644class GTEST_API_ TestInfo {
645 public:
646  // Destructs a TestInfo object.  This function is not virtual, so
647  // don't inherit from TestInfo.
648  ~TestInfo();
649
650  // Returns the test case name.
651  const char* test_case_name() const { return test_case_name_.c_str(); }
652
653  // Returns the test name.
654  const char* name() const { return name_.c_str(); }
655
656  // Returns the name of the parameter type, or NULL if this is not a typed
657  // or a type-parameterized test.
658  const char* type_param() const {
659    if (type_param_.get() != NULL)
660      return type_param_->c_str();
661    return NULL;
662  }
663
664  // Returns the text representation of the value parameter, or NULL if this
665  // is not a value-parameterized test.
666  const char* value_param() const {
667    if (value_param_.get() != NULL)
668      return value_param_->c_str();
669    return NULL;
670  }
671
672  // Returns the file name where this test is defined.
673  const char* file() const { return location_.file.c_str(); }
674
675  // Returns the line where this test is defined.
676  int line() const { return location_.line; }
677
678  // Returns true if this test should run, that is if the test is not
679  // disabled (or it is disabled but the also_run_disabled_tests flag has
680  // been specified) and its full name matches the user-specified filter.
681  //
682  // Google Test allows the user to filter the tests by their full names.
683  // The full name of a test Bar in test case Foo is defined as
684  // "Foo.Bar".  Only the tests that match the filter will run.
685  //
686  // A filter is a colon-separated list of glob (not regex) patterns,
687  // optionally followed by a '-' and a colon-separated list of
688  // negative patterns (tests to exclude).  A test is run if it
689  // matches one of the positive patterns and does not match any of
690  // the negative patterns.
691  //
692  // For example, *A*:Foo.* is a filter that matches any string that
693  // contains the character 'A' or starts with "Foo.".
694  bool should_run() const { return should_run_; }
695
696  // Returns true iff this test will appear in the XML report.
697  bool is_reportable() const {
698    // For now, the XML report includes all tests matching the filter.
699    // In the future, we may trim tests that are excluded because of
700    // sharding.
701    return matches_filter_;
702  }
703
704  // Returns the result of the test.
705  const TestResult* result() const { return &result_; }
706
707 private:
708#if GTEST_HAS_DEATH_TEST
709  friend class internal::DefaultDeathTestFactory;
710#endif  // GTEST_HAS_DEATH_TEST
711  friend class Test;
712  friend class TestCase;
713  friend class internal::UnitTestImpl;
714  friend class internal::StreamingListenerTest;
715  friend TestInfo* internal::MakeAndRegisterTestInfo(
716      const char* test_case_name,
717      const char* name,
718      const char* type_param,
719      const char* value_param,
720      internal::CodeLocation code_location,
721      internal::TypeId fixture_class_id,
722      Test::SetUpTestCaseFunc set_up_tc,
723      Test::TearDownTestCaseFunc tear_down_tc,
724      internal::TestFactoryBase* factory);
725
726  // Constructs a TestInfo object. The newly constructed instance assumes
727  // ownership of the factory object.
728  TestInfo(const std::string& test_case_name,
729           const std::string& name,
730           const char* a_type_param,   // NULL if not a type-parameterized test
731           const char* a_value_param,  // NULL if not a value-parameterized test
732           internal::CodeLocation a_code_location,
733           internal::TypeId fixture_class_id,
734           internal::TestFactoryBase* factory);
735
736  // Increments the number of death tests encountered in this test so
737  // far.
738  int increment_death_test_count() {
739    return result_.increment_death_test_count();
740  }
741
742  // Creates the test object, runs it, records its result, and then
743  // deletes it.
744  void Run();
745
746  static void ClearTestResult(TestInfo* test_info) {
747    test_info->result_.Clear();
748  }
749
750  // These fields are immutable properties of the test.
751  const std::string test_case_name_;     // Test case name
752  const std::string name_;               // Test name
753  // Name of the parameter type, or NULL if this is not a typed or a
754  // type-parameterized test.
755  const internal::scoped_ptr<const ::std::string> type_param_;
756  // Text representation of the value parameter, or NULL if this is not a
757  // value-parameterized test.
758  const internal::scoped_ptr<const ::std::string> value_param_;
759  internal::CodeLocation location_;
760  const internal::TypeId fixture_class_id_;   // ID of the test fixture class
761  bool should_run_;                 // True iff this test should run
762  bool is_disabled_;                // True iff this test is disabled
763  bool matches_filter_;             // True if this test matches the
764                                    // user-specified filter.
765  internal::TestFactoryBase* const factory_;  // The factory that creates
766                                              // the test object
767
768  // This field is mutable and needs to be reset before running the
769  // test for the second time.
770  TestResult result_;
771
772  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
773};
774
775// A test case, which consists of a vector of TestInfos.
776//
777// TestCase is not copyable.
778class GTEST_API_ TestCase {
779 public:
780  // Creates a TestCase with the given name.
781  //
782  // TestCase does NOT have a default constructor.  Always use this
783  // constructor to create a TestCase object.
784  //
785  // Arguments:
786  //
787  //   name:         name of the test case
788  //   a_type_param: the name of the test's type parameter, or NULL if
789  //                 this is not a type-parameterized test.
790  //   set_up_tc:    pointer to the function that sets up the test case
791  //   tear_down_tc: pointer to the function that tears down the test case
792  TestCase(const char* name, const char* a_type_param,
793           Test::SetUpTestCaseFunc set_up_tc,
794           Test::TearDownTestCaseFunc tear_down_tc);
795
796  // Destructor of TestCase.
797  virtual ~TestCase();
798
799  // Gets the name of the TestCase.
800  const char* name() const { return name_.c_str(); }
801
802  // Returns the name of the parameter type, or NULL if this is not a
803  // type-parameterized test case.
804  const char* type_param() const {
805    if (type_param_.get() != NULL)
806      return type_param_->c_str();
807    return NULL;
808  }
809
810  // Returns true if any test in this test case should run.
811  bool should_run() const { return should_run_; }
812
813  // Gets the number of successful tests in this test case.
814  int successful_test_count() const;
815
816  // Gets the number of failed tests in this test case.
817  int failed_test_count() const;
818
819  // Gets the number of disabled tests that will be reported in the XML report.
820  int reportable_disabled_test_count() const;
821
822  // Gets the number of disabled tests in this test case.
823  int disabled_test_count() const;
824
825  // Gets the number of tests to be printed in the XML report.
826  int reportable_test_count() const;
827
828  // Get the number of tests in this test case that should run.
829  int test_to_run_count() const;
830
831  // Gets the number of all tests in this test case.
832  int total_test_count() const;
833
834  // Returns true iff the test case passed.
835  bool Passed() const { return !Failed(); }
836
837  // Returns true iff the test case failed.
838  bool Failed() const { return failed_test_count() > 0; }
839
840  // Returns the elapsed time, in milliseconds.
841  TimeInMillis elapsed_time() const { return elapsed_time_; }
842
843  // Returns the i-th test among all the tests. i can range from 0 to
844  // total_test_count() - 1. If i is not in that range, returns NULL.
845  const TestInfo* GetTestInfo(int i) const;
846
847  // Returns the TestResult that holds test properties recorded during
848  // execution of SetUpTestCase and TearDownTestCase.
849  const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
850
851 private:
852  friend class Test;
853  friend class internal::UnitTestImpl;
854
855  // Gets the (mutable) vector of TestInfos in this TestCase.
856  std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
857
858  // Gets the (immutable) vector of TestInfos in this TestCase.
859  const std::vector<TestInfo*>& test_info_list() const {
860    return test_info_list_;
861  }
862
863  // Returns the i-th test among all the tests. i can range from 0 to
864  // total_test_count() - 1. If i is not in that range, returns NULL.
865  TestInfo* GetMutableTestInfo(int i);
866
867  // Sets the should_run member.
868  void set_should_run(bool should) { should_run_ = should; }
869
870  // Adds a TestInfo to this test case.  Will delete the TestInfo upon
871  // destruction of the TestCase object.
872  void AddTestInfo(TestInfo * test_info);
873
874  // Clears the results of all tests in this test case.
875  void ClearResult();
876
877  // Clears the results of all tests in the given test case.
878  static void ClearTestCaseResult(TestCase* test_case) {
879    test_case->ClearResult();
880  }
881
882  // Runs every test in this TestCase.
883  void Run();
884
885  // Runs SetUpTestCase() for this TestCase.  This wrapper is needed
886  // for catching exceptions thrown from SetUpTestCase().
887  void RunSetUpTestCase() { (*set_up_tc_)(); }
888
889  // Runs TearDownTestCase() for this TestCase.  This wrapper is
890  // needed for catching exceptions thrown from TearDownTestCase().
891  void RunTearDownTestCase() { (*tear_down_tc_)(); }
892
893  // Returns true iff test passed.
894  static bool TestPassed(const TestInfo* test_info) {
895    return test_info->should_run() && test_info->result()->Passed();
896  }
897
898  // Returns true iff test failed.
899  static bool TestFailed(const TestInfo* test_info) {
900    return test_info->should_run() && test_info->result()->Failed();
901  }
902
903  // Returns true iff the test is disabled and will be reported in the XML
904  // report.
905  static bool TestReportableDisabled(const TestInfo* test_info) {
906    return test_info->is_reportable() && test_info->is_disabled_;
907  }
908
909  // Returns true iff test is disabled.
910  static bool TestDisabled(const TestInfo* test_info) {
911    return test_info->is_disabled_;
912  }
913
914  // Returns true iff this test will appear in the XML report.
915  static bool TestReportable(const TestInfo* test_info) {
916    return test_info->is_reportable();
917  }
918
919  // Returns true if the given test should run.
920  static bool ShouldRunTest(const TestInfo* test_info) {
921    return test_info->should_run();
922  }
923
924  // Shuffles the tests in this test case.
925  void ShuffleTests(internal::Random* random);
926
927  // Restores the test order to before the first shuffle.
928  void UnshuffleTests();
929
930  // Name of the test case.
931  std::string name_;
932  // Name of the parameter type, or NULL if this is not a typed or a
933  // type-parameterized test.
934  const internal::scoped_ptr<const ::std::string> type_param_;
935  // The vector of TestInfos in their original order.  It owns the
936  // elements in the vector.
937  std::vector<TestInfo*> test_info_list_;
938  // Provides a level of indirection for the test list to allow easy
939  // shuffling and restoring the test order.  The i-th element in this
940  // vector is the index of the i-th test in the shuffled test list.
941  std::vector<int> test_indices_;
942  // Pointer to the function that sets up the test case.
943  Test::SetUpTestCaseFunc set_up_tc_;
944  // Pointer to the function that tears down the test case.
945  Test::TearDownTestCaseFunc tear_down_tc_;
946  // True iff any test in this test case should run.
947  bool should_run_;
948  // Elapsed time, in milliseconds.
949  TimeInMillis elapsed_time_;
950  // Holds test properties recorded during execution of SetUpTestCase and
951  // TearDownTestCase.
952  TestResult ad_hoc_test_result_;
953
954  // We disallow copying TestCases.
955  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
956};
957
958// An Environment object is capable of setting up and tearing down an
959// environment.  You should subclass this to define your own
960// environment(s).
961//
962// An Environment object does the set-up and tear-down in virtual
963// methods SetUp() and TearDown() instead of the constructor and the
964// destructor, as:
965//
966//   1. You cannot safely throw from a destructor.  This is a problem
967//      as in some cases Google Test is used where exceptions are enabled, and
968//      we may want to implement ASSERT_* using exceptions where they are
969//      available.
970//   2. You cannot use ASSERT_* directly in a constructor or
971//      destructor.
972class Environment {
973 public:
974  // The d'tor is virtual as we need to subclass Environment.
975  virtual ~Environment() {}
976
977  // Override this to define how to set up the environment.
978  virtual void SetUp() {}
979
980  // Override this to define how to tear down the environment.
981  virtual void TearDown() {}
982 private:
983  // If you see an error about overriding the following function or
984  // about it being private, you have mis-spelled SetUp() as Setup().
985  struct Setup_should_be_spelled_SetUp {};
986  virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
987};
988
989// The interface for tracing execution of tests. The methods are organized in
990// the order the corresponding events are fired.
991class TestEventListener {
992 public:
993  virtual ~TestEventListener() {}
994
995  // Fired before any test activity starts.
996  virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
997
998  // Fired before each iteration of tests starts.  There may be more than
999  // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
1000  // index, starting from 0.
1001  virtual void OnTestIterationStart(const UnitTest& unit_test,
1002                                    int iteration) = 0;
1003
1004  // Fired before environment set-up for each iteration of tests starts.
1005  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
1006
1007  // Fired after environment set-up for each iteration of tests ends.
1008  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
1009
1010  // Fired before the test case starts.
1011  virtual void OnTestCaseStart(const TestCase& test_case) = 0;
1012
1013  // Fired before the test starts.
1014  virtual void OnTestStart(const TestInfo& test_info) = 0;
1015
1016  // Fired after a failed assertion or a SUCCEED() invocation.
1017  virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
1018
1019  // Fired after the test ends.
1020  virtual void OnTestEnd(const TestInfo& test_info) = 0;
1021
1022  // Fired after the test case ends.
1023  virtual void OnTestCaseEnd(const TestCase& test_case) = 0;
1024
1025  // Fired before environment tear-down for each iteration of tests starts.
1026  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
1027
1028  // Fired after environment tear-down for each iteration of tests ends.
1029  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
1030
1031  // Fired after each iteration of tests finishes.
1032  virtual void OnTestIterationEnd(const UnitTest& unit_test,
1033                                  int iteration) = 0;
1034
1035  // Fired after all test activities have ended.
1036  virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
1037};
1038
1039// The convenience class for users who need to override just one or two
1040// methods and are not concerned that a possible change to a signature of
1041// the methods they override will not be caught during the build.  For
1042// comments about each method please see the definition of TestEventListener
1043// above.
1044class EmptyTestEventListener : public TestEventListener {
1045 public:
1046  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
1047  virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
1048                                    int /*iteration*/) {}
1049  virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}
1050  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
1051  virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
1052  virtual void OnTestStart(const TestInfo& /*test_info*/) {}
1053  virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}
1054  virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
1055  virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
1056  virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
1057  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
1058  virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
1059                                  int /*iteration*/) {}
1060  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
1061};
1062
1063// TestEventListeners lets users add listeners to track events in Google Test.
1064class GTEST_API_ TestEventListeners {
1065 public:
1066  TestEventListeners();
1067  ~TestEventListeners();
1068
1069  // Appends an event listener to the end of the list. Google Test assumes
1070  // the ownership of the listener (i.e. it will delete the listener when
1071  // the test program finishes).
1072  void Append(TestEventListener* listener);
1073
1074  // Removes the given event listener from the list and returns it.  It then
1075  // becomes the caller's responsibility to delete the listener. Returns
1076  // NULL if the listener is not found in the list.
1077  TestEventListener* Release(TestEventListener* listener);
1078
1079  // Returns the standard listener responsible for the default console
1080  // output.  Can be removed from the listeners list to shut down default
1081  // console output.  Note that removing this object from the listener list
1082  // with Release transfers its ownership to the caller and makes this
1083  // function return NULL the next time.
1084  TestEventListener* default_result_printer() const {
1085    return default_result_printer_;
1086  }
1087
1088  // Returns the standard listener responsible for the default XML output
1089  // controlled by the --gtest_output=xml flag.  Can be removed from the
1090  // listeners list by users who want to shut down the default XML output
1091  // controlled by this flag and substitute it with custom one.  Note that
1092  // removing this object from the listener list with Release transfers its
1093  // ownership to the caller and makes this function return NULL the next
1094  // time.
1095  TestEventListener* default_xml_generator() const {
1096    return default_xml_generator_;
1097  }
1098
1099 private:
1100  friend class TestCase;
1101  friend class TestInfo;
1102  friend class internal::DefaultGlobalTestPartResultReporter;
1103  friend class internal::NoExecDeathTest;
1104  friend class internal::TestEventListenersAccessor;
1105  friend class internal::UnitTestImpl;
1106
1107  // Returns repeater that broadcasts the TestEventListener events to all
1108  // subscribers.
1109  TestEventListener* repeater();
1110
1111  // Sets the default_result_printer attribute to the provided listener.
1112  // The listener is also added to the listener list and previous
1113  // default_result_printer is removed from it and deleted. The listener can
1114  // also be NULL in which case it will not be added to the list. Does
1115  // nothing if the previous and the current listener objects are the same.
1116  void SetDefaultResultPrinter(TestEventListener* listener);
1117
1118  // Sets the default_xml_generator attribute to the provided listener.  The
1119  // listener is also added to the listener list and previous
1120  // default_xml_generator is removed from it and deleted. The listener can
1121  // also be NULL in which case it will not be added to the list. Does
1122  // nothing if the previous and the current listener objects are the same.
1123  void SetDefaultXmlGenerator(TestEventListener* listener);
1124
1125  // Controls whether events will be forwarded by the repeater to the
1126  // listeners in the list.
1127  bool EventForwardingEnabled() const;
1128  void SuppressEventForwarding();
1129
1130  // The actual list of listeners.
1131  internal::TestEventRepeater* repeater_;
1132  // Listener responsible for the standard result output.
1133  TestEventListener* default_result_printer_;
1134  // Listener responsible for the creation of the XML output file.
1135  TestEventListener* default_xml_generator_;
1136
1137  // We disallow copying TestEventListeners.
1138  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
1139};
1140
1141// A UnitTest consists of a vector of TestCases.
1142//
1143// This is a singleton class.  The only instance of UnitTest is
1144// created when UnitTest::GetInstance() is first called.  This
1145// instance is never deleted.
1146//
1147// UnitTest is not copyable.
1148//
1149// This class is thread-safe as long as the methods are called
1150// according to their specification.
1151class GTEST_API_ UnitTest {
1152 public:
1153  // Gets the singleton UnitTest object.  The first time this method
1154  // is called, a UnitTest object is constructed and returned.
1155  // Consecutive calls will return the same object.
1156  static UnitTest* GetInstance();
1157
1158  // Runs all tests in this UnitTest object and prints the result.
1159  // Returns 0 if successful, or 1 otherwise.
1160  //
1161  // This method can only be called from the main thread.
1162  //
1163  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1164  int Run() GTEST_MUST_USE_RESULT_;
1165
1166  // Returns the working directory when the first TEST() or TEST_F()
1167  // was executed.  The UnitTest object owns the string.
1168  const char* original_working_dir() const;
1169
1170  // Returns the TestCase object for the test that's currently running,
1171  // or NULL if no test is running.
1172  const TestCase* current_test_case() const
1173      GTEST_LOCK_EXCLUDED_(mutex_);
1174
1175  // Returns the TestInfo object for the test that's currently running,
1176  // or NULL if no test is running.
1177  const TestInfo* current_test_info() const
1178      GTEST_LOCK_EXCLUDED_(mutex_);
1179
1180  // Returns the random seed used at the start of the current test run.
1181  int random_seed() const;
1182
1183#if GTEST_HAS_PARAM_TEST
1184  // Returns the ParameterizedTestCaseRegistry object used to keep track of
1185  // value-parameterized tests and instantiate and register them.
1186  //
1187  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1188  internal::ParameterizedTestCaseRegistry& parameterized_test_registry()
1189      GTEST_LOCK_EXCLUDED_(mutex_);
1190#endif  // GTEST_HAS_PARAM_TEST
1191
1192  // Gets the number of successful test cases.
1193  int successful_test_case_count() const;
1194
1195  // Gets the number of failed test cases.
1196  int failed_test_case_count() const;
1197
1198  // Gets the number of all test cases.
1199  int total_test_case_count() const;
1200
1201  // Gets the number of all test cases that contain at least one test
1202  // that should run.
1203  int test_case_to_run_count() const;
1204
1205  // Gets the number of successful tests.
1206  int successful_test_count() const;
1207
1208  // Gets the number of failed tests.
1209  int failed_test_count() const;
1210
1211  // Gets the number of disabled tests that will be reported in the XML report.
1212  int reportable_disabled_test_count() const;
1213
1214  // Gets the number of disabled tests.
1215  int disabled_test_count() const;
1216
1217  // Gets the number of tests to be printed in the XML report.
1218  int reportable_test_count() const;
1219
1220  // Gets the number of all tests.
1221  int total_test_count() const;
1222
1223  // Gets the number of tests that should run.
1224  int test_to_run_count() const;
1225
1226  // Gets the time of the test program start, in ms from the start of the
1227  // UNIX epoch.
1228  TimeInMillis start_timestamp() const;
1229
1230  // Gets the elapsed time, in milliseconds.
1231  TimeInMillis elapsed_time() const;
1232
1233  // Returns true iff the unit test passed (i.e. all test cases passed).
1234  bool Passed() const;
1235
1236  // Returns true iff the unit test failed (i.e. some test case failed
1237  // or something outside of all tests failed).
1238  bool Failed() const;
1239
1240  // Gets the i-th test case among all the test cases. i can range from 0 to
1241  // total_test_case_count() - 1. If i is not in that range, returns NULL.
1242  const TestCase* GetTestCase(int i) const;
1243
1244  // Returns the TestResult containing information on test failures and
1245  // properties logged outside of individual test cases.
1246  const TestResult& ad_hoc_test_result() const;
1247
1248  // Returns the list of event listeners that can be used to track events
1249  // inside Google Test.
1250  TestEventListeners& listeners();
1251
1252 private:
1253  // Registers and returns a global test environment.  When a test
1254  // program is run, all global test environments will be set-up in
1255  // the order they were registered.  After all tests in the program
1256  // have finished, all global test environments will be torn-down in
1257  // the *reverse* order they were registered.
1258  //
1259  // The UnitTest object takes ownership of the given environment.
1260  //
1261  // This method can only be called from the main thread.
1262  Environment* AddEnvironment(Environment* env);
1263
1264  // Adds a TestPartResult to the current TestResult object.  All
1265  // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
1266  // eventually call this to report their results.  The user code
1267  // should use the assertion macros instead of calling this directly.
1268  void AddTestPartResult(TestPartResult::Type result_type,
1269                         const char* file_name,
1270                         int line_number,
1271                         const std::string& message,
1272                         const std::string& os_stack_trace)
1273      GTEST_LOCK_EXCLUDED_(mutex_);
1274
1275  // Adds a TestProperty to the current TestResult object when invoked from
1276  // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
1277  // from SetUpTestCase or TearDownTestCase, or to the global property set
1278  // when invoked elsewhere.  If the result already contains a property with
1279  // the same key, the value will be updated.
1280  void RecordProperty(const std::string& key, const std::string& value);
1281
1282  // Gets the i-th test case among all the test cases. i can range from 0 to
1283  // total_test_case_count() - 1. If i is not in that range, returns NULL.
1284  TestCase* GetMutableTestCase(int i);
1285
1286  // Accessors for the implementation object.
1287  internal::UnitTestImpl* impl() { return impl_; }
1288  const internal::UnitTestImpl* impl() const { return impl_; }
1289
1290  // These classes and funcions are friends as they need to access private
1291  // members of UnitTest.
1292  friend class Test;
1293  friend class internal::AssertHelper;
1294  friend class internal::ScopedTrace;
1295  friend class internal::StreamingListenerTest;
1296  friend class internal::UnitTestRecordPropertyTestHelper;
1297  friend Environment* AddGlobalTestEnvironment(Environment* env);
1298  friend internal::UnitTestImpl* internal::GetUnitTestImpl();
1299  friend void internal::ReportFailureInUnknownLocation(
1300      TestPartResult::Type result_type,
1301      const std::string& message);
1302
1303  // Creates an empty UnitTest.
1304  UnitTest();
1305
1306  // D'tor
1307  virtual ~UnitTest();
1308
1309  // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
1310  // Google Test trace stack.
1311  void PushGTestTrace(const internal::TraceInfo& trace)
1312      GTEST_LOCK_EXCLUDED_(mutex_);
1313
1314  // Pops a trace from the per-thread Google Test trace stack.
1315  void PopGTestTrace()
1316      GTEST_LOCK_EXCLUDED_(mutex_);
1317
1318  // Protects mutable state in *impl_.  This is mutable as some const
1319  // methods need to lock it too.
1320  mutable internal::Mutex mutex_;
1321
1322  // Opaque implementation object.  This field is never changed once
1323  // the object is constructed.  We don't mark it as const here, as
1324  // doing so will cause a warning in the constructor of UnitTest.
1325  // Mutable state in *impl_ is protected by mutex_.
1326  internal::UnitTestImpl* impl_;
1327
1328  // We disallow copying UnitTest.
1329  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
1330};
1331
1332// A convenient wrapper for adding an environment for the test
1333// program.
1334//
1335// You should call this before RUN_ALL_TESTS() is called, probably in
1336// main().  If you use gtest_main, you need to call this before main()
1337// starts for it to take effect.  For example, you can define a global
1338// variable like this:
1339//
1340//   testing::Environment* const foo_env =
1341//       testing::AddGlobalTestEnvironment(new FooEnvironment);
1342//
1343// However, we strongly recommend you to write your own main() and
1344// call AddGlobalTestEnvironment() there, as relying on initialization
1345// of global variables makes the code harder to read and may cause
1346// problems when you register multiple environments from different
1347// translation units and the environments have dependencies among them
1348// (remember that the compiler doesn't guarantee the order in which
1349// global variables from different translation units are initialized).
1350inline Environment* AddGlobalTestEnvironment(Environment* env) {
1351  return UnitTest::GetInstance()->AddEnvironment(env);
1352}
1353
1354// Initializes Google Test.  This must be called before calling
1355// RUN_ALL_TESTS().  In particular, it parses a command line for the
1356// flags that Google Test recognizes.  Whenever a Google Test flag is
1357// seen, it is removed from argv, and *argc is decremented.
1358//
1359// No value is returned.  Instead, the Google Test flag variables are
1360// updated.
1361//
1362// Calling the function for the second time has no user-visible effect.
1363GTEST_API_ void InitGoogleTest(int* argc, char** argv);
1364
1365// This overloaded version can be used in Windows programs compiled in
1366// UNICODE mode.
1367GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
1368
1369namespace internal {
1370
1371// Separate the error generating code from the code path to reduce the stack
1372// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
1373// when calling EXPECT_* in a tight loop.
1374template <typename T1, typename T2>
1375AssertionResult CmpHelperEQFailure(const char* expected_expression,
1376                                   const char* actual_expression,
1377                                   const T1& expected, const T2& actual) {
1378  return EqFailure(expected_expression,
1379                   actual_expression,
1380                   FormatForComparisonFailureMessage(expected, actual),
1381                   FormatForComparisonFailureMessage(actual, expected),
1382                   false);
1383}
1384
1385// The helper function for {ASSERT|EXPECT}_EQ.
1386template <typename T1, typename T2>
1387AssertionResult CmpHelperEQ(const char* expected_expression,
1388                            const char* actual_expression,
1389                            const T1& expected,
1390                            const T2& actual) {
1391GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */)
1392  if (expected == actual) {
1393    return AssertionSuccess();
1394  }
1395GTEST_DISABLE_MSC_WARNINGS_POP_()
1396
1397  return CmpHelperEQFailure(expected_expression, actual_expression, expected,
1398                            actual);
1399}
1400
1401// With this overloaded version, we allow anonymous enums to be used
1402// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
1403// can be implicitly cast to BiggestInt.
1404GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression,
1405                                       const char* actual_expression,
1406                                       BiggestInt expected,
1407                                       BiggestInt actual);
1408
1409// The helper class for {ASSERT|EXPECT}_EQ.  The template argument
1410// lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
1411// is a null pointer literal.  The following default implementation is
1412// for lhs_is_null_literal being false.
1413template <bool lhs_is_null_literal>
1414class EqHelper {
1415 public:
1416  // This templatized version is for the general case.
1417  template <typename T1, typename T2>
1418  static AssertionResult Compare(const char* expected_expression,
1419                                 const char* actual_expression,
1420                                 const T1& expected,
1421                                 const T2& actual) {
1422    return CmpHelperEQ(expected_expression, actual_expression, expected,
1423                       actual);
1424  }
1425
1426  // With this overloaded version, we allow anonymous enums to be used
1427  // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
1428  // enums can be implicitly cast to BiggestInt.
1429  //
1430  // Even though its body looks the same as the above version, we
1431  // cannot merge the two, as it will make anonymous enums unhappy.
1432  static AssertionResult Compare(const char* expected_expression,
1433                                 const char* actual_expression,
1434                                 BiggestInt expected,
1435                                 BiggestInt actual) {
1436    return CmpHelperEQ(expected_expression, actual_expression, expected,
1437                       actual);
1438  }
1439};
1440
1441// This specialization is used when the first argument to ASSERT_EQ()
1442// is a null pointer literal, like NULL, false, or 0.
1443template <>
1444class EqHelper<true> {
1445 public:
1446  // We define two overloaded versions of Compare().  The first
1447  // version will be picked when the second argument to ASSERT_EQ() is
1448  // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
1449  // EXPECT_EQ(false, a_bool).
1450  template <typename T1, typename T2>
1451  static AssertionResult Compare(
1452      const char* expected_expression,
1453      const char* actual_expression,
1454      const T1& expected,
1455      const T2& actual,
1456      // The following line prevents this overload from being considered if T2
1457      // is not a pointer type.  We need this because ASSERT_EQ(NULL, my_ptr)
1458      // expands to Compare("", "", NULL, my_ptr), which requires a conversion
1459      // to match the Secret* in the other overload, which would otherwise make
1460      // this template match better.
1461      typename EnableIf<!is_pointer<T2>::value>::type* = 0) {
1462    return CmpHelperEQ(expected_expression, actual_expression, expected,
1463                       actual);
1464  }
1465
1466  // This version will be picked when the second argument to ASSERT_EQ() is a
1467  // pointer, e.g. ASSERT_EQ(NULL, a_pointer).
1468  template <typename T>
1469  static AssertionResult Compare(
1470      const char* expected_expression,
1471      const char* actual_expression,
1472      // We used to have a second template parameter instead of Secret*.  That
1473      // template parameter would deduce to 'long', making this a better match
1474      // than the first overload even without the first overload's EnableIf.
1475      // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to
1476      // non-pointer argument" (even a deduced integral argument), so the old
1477      // implementation caused warnings in user code.
1478      Secret* /* expected (NULL) */,
1479      T* actual) {
1480    // We already know that 'expected' is a null pointer.
1481    return CmpHelperEQ(expected_expression, actual_expression,
1482                       static_cast<T*>(NULL), actual);
1483  }
1484};
1485
1486// Separate the error generating code from the code path to reduce the stack
1487// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
1488// when calling EXPECT_OP in a tight loop.
1489template <typename T1, typename T2>
1490AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
1491                                   const T1& val1, const T2& val2,
1492                                   const char* op) {
1493  return AssertionFailure()
1494         << "Expected: (" << expr1 << ") " << op << " (" << expr2
1495         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
1496         << " vs " << FormatForComparisonFailureMessage(val2, val1);
1497}
1498
1499// A macro for implementing the helper functions needed to implement
1500// ASSERT_?? and EXPECT_??.  It is here just to avoid copy-and-paste
1501// of similar code.
1502//
1503// For each templatized helper function, we also define an overloaded
1504// version for BiggestInt in order to reduce code bloat and allow
1505// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
1506// with gcc 4.
1507//
1508// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1509
1510#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1511template <typename T1, typename T2>\
1512AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1513                                   const T1& val1, const T2& val2) {\
1514  if (val1 op val2) {\
1515    return AssertionSuccess();\
1516  } else {\
1517    return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
1518  }\
1519}\
1520GTEST_API_ AssertionResult CmpHelper##op_name(\
1521    const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
1522
1523// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1524
1525// Implements the helper function for {ASSERT|EXPECT}_NE
1526GTEST_IMPL_CMP_HELPER_(NE, !=);
1527// Implements the helper function for {ASSERT|EXPECT}_LE
1528GTEST_IMPL_CMP_HELPER_(LE, <=);
1529// Implements the helper function for {ASSERT|EXPECT}_LT
1530GTEST_IMPL_CMP_HELPER_(LT, <);
1531// Implements the helper function for {ASSERT|EXPECT}_GE
1532GTEST_IMPL_CMP_HELPER_(GE, >=);
1533// Implements the helper function for {ASSERT|EXPECT}_GT
1534GTEST_IMPL_CMP_HELPER_(GT, >);
1535
1536#undef GTEST_IMPL_CMP_HELPER_
1537
1538// The helper function for {ASSERT|EXPECT}_STREQ.
1539//
1540// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1541GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression,
1542                                          const char* actual_expression,
1543                                          const char* expected,
1544                                          const char* actual);
1545
1546// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1547//
1548// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1549GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1550                                              const char* actual_expression,
1551                                              const char* expected,
1552                                              const char* actual);
1553
1554// The helper function for {ASSERT|EXPECT}_STRNE.
1555//
1556// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1557GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1558                                          const char* s2_expression,
1559                                          const char* s1,
1560                                          const char* s2);
1561
1562// The helper function for {ASSERT|EXPECT}_STRCASENE.
1563//
1564// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1565GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1566                                              const char* s2_expression,
1567                                              const char* s1,
1568                                              const char* s2);
1569
1570
1571// Helper function for *_STREQ on wide strings.
1572//
1573// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1574GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression,
1575                                          const char* actual_expression,
1576                                          const wchar_t* expected,
1577                                          const wchar_t* actual);
1578
1579// Helper function for *_STRNE on wide strings.
1580//
1581// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1582GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1583                                          const char* s2_expression,
1584                                          const wchar_t* s1,
1585                                          const wchar_t* s2);
1586
1587}  // namespace internal
1588
1589// IsSubstring() and IsNotSubstring() are intended to be used as the
1590// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
1591// themselves.  They check whether needle is a substring of haystack
1592// (NULL is considered a substring of itself only), and return an
1593// appropriate error message when they fail.
1594//
1595// The {needle,haystack}_expr arguments are the stringified
1596// expressions that generated the two real arguments.
1597GTEST_API_ AssertionResult IsSubstring(
1598    const char* needle_expr, const char* haystack_expr,
1599    const char* needle, const char* haystack);
1600GTEST_API_ AssertionResult IsSubstring(
1601    const char* needle_expr, const char* haystack_expr,
1602    const wchar_t* needle, const wchar_t* haystack);
1603GTEST_API_ AssertionResult IsNotSubstring(
1604    const char* needle_expr, const char* haystack_expr,
1605    const char* needle, const char* haystack);
1606GTEST_API_ AssertionResult IsNotSubstring(
1607    const char* needle_expr, const char* haystack_expr,
1608    const wchar_t* needle, const wchar_t* haystack);
1609GTEST_API_ AssertionResult IsSubstring(
1610    const char* needle_expr, const char* haystack_expr,
1611    const ::std::string& needle, const ::std::string& haystack);
1612GTEST_API_ AssertionResult IsNotSubstring(
1613    const char* needle_expr, const char* haystack_expr,
1614    const ::std::string& needle, const ::std::string& haystack);
1615
1616#if GTEST_HAS_STD_WSTRING
1617GTEST_API_ AssertionResult IsSubstring(
1618    const char* needle_expr, const char* haystack_expr,
1619    const ::std::wstring& needle, const ::std::wstring& haystack);
1620GTEST_API_ AssertionResult IsNotSubstring(
1621    const char* needle_expr, const char* haystack_expr,
1622    const ::std::wstring& needle, const ::std::wstring& haystack);
1623#endif  // GTEST_HAS_STD_WSTRING
1624
1625namespace internal {
1626
1627// Helper template function for comparing floating-points.
1628//
1629// Template parameter:
1630//
1631//   RawType: the raw floating-point type (either float or double)
1632//
1633// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1634template <typename RawType>
1635AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression,
1636                                         const char* actual_expression,
1637                                         RawType expected,
1638                                         RawType actual) {
1639  const FloatingPoint<RawType> lhs(expected), rhs(actual);
1640
1641  if (lhs.AlmostEquals(rhs)) {
1642    return AssertionSuccess();
1643  }
1644
1645  ::std::stringstream expected_ss;
1646  expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1647              << expected;
1648
1649  ::std::stringstream actual_ss;
1650  actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1651            << actual;
1652
1653  return EqFailure(expected_expression,
1654                   actual_expression,
1655                   StringStreamToString(&expected_ss),
1656                   StringStreamToString(&actual_ss),
1657                   false);
1658}
1659
1660// Helper function for implementing ASSERT_NEAR.
1661//
1662// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1663GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
1664                                                const char* expr2,
1665                                                const char* abs_error_expr,
1666                                                double val1,
1667                                                double val2,
1668                                                double abs_error);
1669
1670// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1671// A class that enables one to stream messages to assertion macros
1672class GTEST_API_ AssertHelper {
1673 public:
1674  // Constructor.
1675  AssertHelper(TestPartResult::Type type,
1676               const char* file,
1677               int line,
1678               const char* message);
1679  ~AssertHelper();
1680
1681  // Message assignment is a semantic trick to enable assertion
1682  // streaming; see the GTEST_MESSAGE_ macro below.
1683  void operator=(const Message& message) const;
1684
1685 private:
1686  // We put our data in a struct so that the size of the AssertHelper class can
1687  // be as small as possible.  This is important because gcc is incapable of
1688  // re-using stack space even for temporary variables, so every EXPECT_EQ
1689  // reserves stack space for another AssertHelper.
1690  struct AssertHelperData {
1691    AssertHelperData(TestPartResult::Type t,
1692                     const char* srcfile,
1693                     int line_num,
1694                     const char* msg)
1695        : type(t), file(srcfile), line(line_num), message(msg) { }
1696
1697    TestPartResult::Type const type;
1698    const char* const file;
1699    int const line;
1700    std::string const message;
1701
1702   private:
1703    GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
1704  };
1705
1706  AssertHelperData* const data_;
1707
1708  GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
1709};
1710
1711}  // namespace internal
1712
1713#if GTEST_HAS_PARAM_TEST
1714// The pure interface class that all value-parameterized tests inherit from.
1715// A value-parameterized class must inherit from both ::testing::Test and
1716// ::testing::WithParamInterface. In most cases that just means inheriting
1717// from ::testing::TestWithParam, but more complicated test hierarchies
1718// may need to inherit from Test and WithParamInterface at different levels.
1719//
1720// This interface has support for accessing the test parameter value via
1721// the GetParam() method.
1722//
1723// Use it with one of the parameter generator defining functions, like Range(),
1724// Values(), ValuesIn(), Bool(), and Combine().
1725//
1726// class FooTest : public ::testing::TestWithParam<int> {
1727//  protected:
1728//   FooTest() {
1729//     // Can use GetParam() here.
1730//   }
1731//   virtual ~FooTest() {
1732//     // Can use GetParam() here.
1733//   }
1734//   virtual void SetUp() {
1735//     // Can use GetParam() here.
1736//   }
1737//   virtual void TearDown {
1738//     // Can use GetParam() here.
1739//   }
1740// };
1741// TEST_P(FooTest, DoesBar) {
1742//   // Can use GetParam() method here.
1743//   Foo foo;
1744//   ASSERT_TRUE(foo.DoesBar(GetParam()));
1745// }
1746// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
1747
1748template <typename T>
1749class WithParamInterface {
1750 public:
1751  typedef T ParamType;
1752  virtual ~WithParamInterface() {}
1753
1754  // The current parameter value. Is also available in the test fixture's
1755  // constructor. This member function is non-static, even though it only
1756  // references static data, to reduce the opportunity for incorrect uses
1757  // like writing 'WithParamInterface<bool>::GetParam()' for a test that
1758  // uses a fixture whose parameter type is int.
1759  const ParamType& GetParam() const {
1760    GTEST_CHECK_(parameter_ != NULL)
1761        << "GetParam() can only be called inside a value-parameterized test "
1762        << "-- did you intend to write TEST_P instead of TEST_F?";
1763    return *parameter_;
1764  }
1765
1766 private:
1767  // Sets parameter value. The caller is responsible for making sure the value
1768  // remains alive and unchanged throughout the current test.
1769  static void SetParam(const ParamType* parameter) {
1770    parameter_ = parameter;
1771  }
1772
1773  // Static value used for accessing parameter during a test lifetime.
1774  static const ParamType* parameter_;
1775
1776  // TestClass must be a subclass of WithParamInterface<T> and Test.
1777  template <class TestClass> friend class internal::ParameterizedTestFactory;
1778};
1779
1780template <typename T>
1781const T* WithParamInterface<T>::parameter_ = NULL;
1782
1783// Most value-parameterized classes can ignore the existence of
1784// WithParamInterface, and can just inherit from ::testing::TestWithParam.
1785
1786template <typename T>
1787class TestWithParam : public Test, public WithParamInterface<T> {
1788};
1789
1790#endif  // GTEST_HAS_PARAM_TEST
1791
1792// Macros for indicating success/failure in test code.
1793
1794// ADD_FAILURE unconditionally adds a failure to the current test.
1795// SUCCEED generates a success - it doesn't automatically make the
1796// current test successful, as a test is only successful when it has
1797// no failure.
1798//
1799// EXPECT_* verifies that a certain condition is satisfied.  If not,
1800// it behaves like ADD_FAILURE.  In particular:
1801//
1802//   EXPECT_TRUE  verifies that a Boolean condition is true.
1803//   EXPECT_FALSE verifies that a Boolean condition is false.
1804//
1805// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
1806// that they will also abort the current function on failure.  People
1807// usually want the fail-fast behavior of FAIL and ASSERT_*, but those
1808// writing data-driven tests often find themselves using ADD_FAILURE
1809// and EXPECT_* more.
1810
1811// Generates a nonfatal failure with a generic message.
1812#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
1813
1814// Generates a nonfatal failure at the given source file location with
1815// a generic message.
1816#define ADD_FAILURE_AT(file, line) \
1817  GTEST_MESSAGE_AT_(file, line, "Failed", \
1818                    ::testing::TestPartResult::kNonFatalFailure)
1819
1820// Generates a fatal failure with a generic message.
1821#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
1822
1823// Define this macro to 1 to omit the definition of FAIL(), which is a
1824// generic name and clashes with some other libraries.
1825#if !GTEST_DONT_DEFINE_FAIL
1826# define FAIL() GTEST_FAIL()
1827#endif
1828
1829// Generates a success with a generic message.
1830#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
1831
1832// Define this macro to 1 to omit the definition of SUCCEED(), which
1833// is a generic name and clashes with some other libraries.
1834#if !GTEST_DONT_DEFINE_SUCCEED
1835# define SUCCEED() GTEST_SUCCEED()
1836#endif
1837
1838// Macros for testing exceptions.
1839//
1840//    * {ASSERT|EXPECT}_THROW(statement, expected_exception):
1841//         Tests that the statement throws the expected exception.
1842//    * {ASSERT|EXPECT}_NO_THROW(statement):
1843//         Tests that the statement doesn't throw any exception.
1844//    * {ASSERT|EXPECT}_ANY_THROW(statement):
1845//         Tests that the statement throws an exception.
1846
1847#define EXPECT_THROW(statement, expected_exception) \
1848  GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
1849#define EXPECT_NO_THROW(statement) \
1850  GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1851#define EXPECT_ANY_THROW(statement) \
1852  GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1853#define ASSERT_THROW(statement, expected_exception) \
1854  GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
1855#define ASSERT_NO_THROW(statement) \
1856  GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
1857#define ASSERT_ANY_THROW(statement) \
1858  GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
1859
1860// Boolean assertions. Condition can be either a Boolean expression or an
1861// AssertionResult. For more information on how to use AssertionResult with
1862// these macros see comments on that class.
1863#define EXPECT_TRUE(condition) \
1864  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1865                      GTEST_NONFATAL_FAILURE_)
1866#define EXPECT_FALSE(condition) \
1867  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1868                      GTEST_NONFATAL_FAILURE_)
1869#define ASSERT_TRUE(condition) \
1870  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1871                      GTEST_FATAL_FAILURE_)
1872#define ASSERT_FALSE(condition) \
1873  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1874                      GTEST_FATAL_FAILURE_)
1875
1876// Includes the auto-generated header that implements a family of
1877// generic predicate assertion macros.
1878#include "gtest/gtest_pred_impl.h"
1879
1880// Macros for testing equalities and inequalities.
1881//
1882//    * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual
1883//    * {ASSERT|EXPECT}_NE(v1, v2):           Tests that v1 != v2
1884//    * {ASSERT|EXPECT}_LT(v1, v2):           Tests that v1 < v2
1885//    * {ASSERT|EXPECT}_LE(v1, v2):           Tests that v1 <= v2
1886//    * {ASSERT|EXPECT}_GT(v1, v2):           Tests that v1 > v2
1887//    * {ASSERT|EXPECT}_GE(v1, v2):           Tests that v1 >= v2
1888//
1889// When they are not, Google Test prints both the tested expressions and
1890// their actual values.  The values must be compatible built-in types,
1891// or you will get a compiler error.  By "compatible" we mean that the
1892// values can be compared by the respective operator.
1893//
1894// Note:
1895//
1896//   1. It is possible to make a user-defined type work with
1897//   {ASSERT|EXPECT}_??(), but that requires overloading the
1898//   comparison operators and is thus discouraged by the Google C++
1899//   Usage Guide.  Therefore, you are advised to use the
1900//   {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
1901//   equal.
1902//
1903//   2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
1904//   pointers (in particular, C strings).  Therefore, if you use it
1905//   with two C strings, you are testing how their locations in memory
1906//   are related, not how their content is related.  To compare two C
1907//   strings by content, use {ASSERT|EXPECT}_STR*().
1908//
1909//   3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to
1910//   {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you
1911//   what the actual value is when it fails, and similarly for the
1912//   other comparisons.
1913//
1914//   4. Do not depend on the order in which {ASSERT|EXPECT}_??()
1915//   evaluate their arguments, which is undefined.
1916//
1917//   5. These macros evaluate their arguments exactly once.
1918//
1919// Examples:
1920//
1921//   EXPECT_NE(5, Foo());
1922//   EXPECT_EQ(NULL, a_pointer);
1923//   ASSERT_LT(i, array_size);
1924//   ASSERT_GT(records.size(), 0) << "There is no record left.";
1925
1926#define EXPECT_EQ(expected, actual) \
1927  EXPECT_PRED_FORMAT2(::testing::internal:: \
1928                      EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
1929                      expected, actual)
1930#define EXPECT_NE(expected, actual) \
1931  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual)
1932#define EXPECT_LE(val1, val2) \
1933  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1934#define EXPECT_LT(val1, val2) \
1935  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1936#define EXPECT_GE(val1, val2) \
1937  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1938#define EXPECT_GT(val1, val2) \
1939  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1940
1941#define GTEST_ASSERT_EQ(expected, actual) \
1942  ASSERT_PRED_FORMAT2(::testing::internal:: \
1943                      EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
1944                      expected, actual)
1945#define GTEST_ASSERT_NE(val1, val2) \
1946  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
1947#define GTEST_ASSERT_LE(val1, val2) \
1948  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1949#define GTEST_ASSERT_LT(val1, val2) \
1950  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1951#define GTEST_ASSERT_GE(val1, val2) \
1952  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1953#define GTEST_ASSERT_GT(val1, val2) \
1954  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1955
1956// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
1957// ASSERT_XY(), which clashes with some users' own code.
1958
1959#if !GTEST_DONT_DEFINE_ASSERT_EQ
1960# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
1961#endif
1962
1963#if !GTEST_DONT_DEFINE_ASSERT_NE
1964# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
1965#endif
1966
1967#if !GTEST_DONT_DEFINE_ASSERT_LE
1968# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
1969#endif
1970
1971#if !GTEST_DONT_DEFINE_ASSERT_LT
1972# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
1973#endif
1974
1975#if !GTEST_DONT_DEFINE_ASSERT_GE
1976# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
1977#endif
1978
1979#if !GTEST_DONT_DEFINE_ASSERT_GT
1980# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
1981#endif
1982
1983// C-string Comparisons.  All tests treat NULL and any non-NULL string
1984// as different.  Two NULLs are equal.
1985//
1986//    * {ASSERT|EXPECT}_STREQ(s1, s2):     Tests that s1 == s2
1987//    * {ASSERT|EXPECT}_STRNE(s1, s2):     Tests that s1 != s2
1988//    * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
1989//    * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
1990//
1991// For wide or narrow string objects, you can use the
1992// {ASSERT|EXPECT}_??() macros.
1993//
1994// Don't depend on the order in which the arguments are evaluated,
1995// which is undefined.
1996//
1997// These macros evaluate their arguments exactly once.
1998
1999#define EXPECT_STREQ(expected, actual) \
2000  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
2001#define EXPECT_STRNE(s1, s2) \
2002  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2003#define EXPECT_STRCASEEQ(expected, actual) \
2004  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
2005#define EXPECT_STRCASENE(s1, s2)\
2006  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2007
2008#define ASSERT_STREQ(expected, actual) \
2009  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
2010#define ASSERT_STRNE(s1, s2) \
2011  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2012#define ASSERT_STRCASEEQ(expected, actual) \
2013  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
2014#define ASSERT_STRCASENE(s1, s2)\
2015  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2016
2017// Macros for comparing floating-point numbers.
2018//
2019//    * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual):
2020//         Tests that two float values are almost equal.
2021//    * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual):
2022//         Tests that two double values are almost equal.
2023//    * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
2024//         Tests that v1 and v2 are within the given distance to each other.
2025//
2026// Google Test uses ULP-based comparison to automatically pick a default
2027// error bound that is appropriate for the operands.  See the
2028// FloatingPoint template class in gtest-internal.h if you are
2029// interested in the implementation details.
2030
2031#define EXPECT_FLOAT_EQ(expected, actual)\
2032  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2033                      expected, actual)
2034
2035#define EXPECT_DOUBLE_EQ(expected, actual)\
2036  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2037                      expected, actual)
2038
2039#define ASSERT_FLOAT_EQ(expected, actual)\
2040  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2041                      expected, actual)
2042
2043#define ASSERT_DOUBLE_EQ(expected, actual)\
2044  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2045                      expected, actual)
2046
2047#define EXPECT_NEAR(val1, val2, abs_error)\
2048  EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2049                      val1, val2, abs_error)
2050
2051#define ASSERT_NEAR(val1, val2, abs_error)\
2052  ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2053                      val1, val2, abs_error)
2054
2055// These predicate format functions work on floating-point values, and
2056// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
2057//
2058//   EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
2059
2060// Asserts that val1 is less than, or almost equal to, val2.  Fails
2061// otherwise.  In particular, it fails if either val1 or val2 is NaN.
2062GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
2063                                   float val1, float val2);
2064GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
2065                                    double val1, double val2);
2066
2067
2068#if GTEST_OS_WINDOWS
2069
2070// Macros that test for HRESULT failure and success, these are only useful
2071// on Windows, and rely on Windows SDK macros and APIs to compile.
2072//
2073//    * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
2074//
2075// When expr unexpectedly fails or succeeds, Google Test prints the
2076// expected result and the actual result with both a human-readable
2077// string representation of the error, if available, as well as the
2078// hex result code.
2079# define EXPECT_HRESULT_SUCCEEDED(expr) \
2080    EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2081
2082# define ASSERT_HRESULT_SUCCEEDED(expr) \
2083    ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2084
2085# define EXPECT_HRESULT_FAILED(expr) \
2086    EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2087
2088# define ASSERT_HRESULT_FAILED(expr) \
2089    ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2090
2091#endif  // GTEST_OS_WINDOWS
2092
2093// Macros that execute statement and check that it doesn't generate new fatal
2094// failures in the current thread.
2095//
2096//   * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
2097//
2098// Examples:
2099//
2100//   EXPECT_NO_FATAL_FAILURE(Process());
2101//   ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
2102//
2103#define ASSERT_NO_FATAL_FAILURE(statement) \
2104    GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
2105#define EXPECT_NO_FATAL_FAILURE(statement) \
2106    GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
2107
2108// Causes a trace (including the source file path, the current line
2109// number, and the given message) to be included in every test failure
2110// message generated by code in the current scope.  The effect is
2111// undone when the control leaves the current scope.
2112//
2113// The message argument can be anything streamable to std::ostream.
2114//
2115// In the implementation, we include the current line number as part
2116// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
2117// to appear in the same block - as long as they are on different
2118// lines.
2119#define SCOPED_TRACE(message) \
2120  ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
2121    __FILE__, __LINE__, ::testing::Message() << (message))
2122
2123// Compile-time assertion for type equality.
2124// StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are
2125// the same type.  The value it returns is not interesting.
2126//
2127// Instead of making StaticAssertTypeEq a class template, we make it a
2128// function template that invokes a helper class template.  This
2129// prevents a user from misusing StaticAssertTypeEq<T1, T2> by
2130// defining objects of that type.
2131//
2132// CAVEAT:
2133//
2134// When used inside a method of a class template,
2135// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
2136// instantiated.  For example, given:
2137//
2138//   template <typename T> class Foo {
2139//    public:
2140//     void Bar() { testing::StaticAssertTypeEq<int, T>(); }
2141//   };
2142//
2143// the code:
2144//
2145//   void Test1() { Foo<bool> foo; }
2146//
2147// will NOT generate a compiler error, as Foo<bool>::Bar() is never
2148// actually instantiated.  Instead, you need:
2149//
2150//   void Test2() { Foo<bool> foo; foo.Bar(); }
2151//
2152// to cause a compiler error.
2153template <typename T1, typename T2>
2154bool StaticAssertTypeEq() {
2155  (void)internal::StaticAssertTypeEqHelper<T1, T2>();
2156  return true;
2157}
2158
2159// Defines a test.
2160//
2161// The first parameter is the name of the test case, and the second
2162// parameter is the name of the test within the test case.
2163//
2164// The convention is to end the test case name with "Test".  For
2165// example, a test case for the Foo class can be named FooTest.
2166//
2167// Test code should appear between braces after an invocation of
2168// this macro.  Example:
2169//
2170//   TEST(FooTest, InitializesCorrectly) {
2171//     Foo foo;
2172//     EXPECT_TRUE(foo.StatusIsOK());
2173//   }
2174
2175// Note that we call GetTestTypeId() instead of GetTypeId<
2176// ::testing::Test>() here to get the type ID of testing::Test.  This
2177// is to work around a suspected linker bug when using Google Test as
2178// a framework on Mac OS X.  The bug causes GetTypeId<
2179// ::testing::Test>() to return different values depending on whether
2180// the call is from the Google Test framework itself or from user test
2181// code.  GetTestTypeId() is guaranteed to always return the same
2182// value, as it always calls GetTypeId<>() from the Google Test
2183// framework.
2184#define GTEST_TEST(test_case_name, test_name)\
2185  GTEST_TEST_(test_case_name, test_name, \
2186              ::testing::Test, ::testing::internal::GetTestTypeId())
2187
2188// Define this macro to 1 to omit the definition of TEST(), which
2189// is a generic name and clashes with some other libraries.
2190#if !GTEST_DONT_DEFINE_TEST
2191# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
2192#endif
2193
2194// Defines a test that uses a test fixture.
2195//
2196// The first parameter is the name of the test fixture class, which
2197// also doubles as the test case name.  The second parameter is the
2198// name of the test within the test case.
2199//
2200// A test fixture class must be declared earlier.  The user should put
2201// his test code between braces after using this macro.  Example:
2202//
2203//   class FooTest : public testing::Test {
2204//    protected:
2205//     virtual void SetUp() { b_.AddElement(3); }
2206//
2207//     Foo a_;
2208//     Foo b_;
2209//   };
2210//
2211//   TEST_F(FooTest, InitializesCorrectly) {
2212//     EXPECT_TRUE(a_.StatusIsOK());
2213//   }
2214//
2215//   TEST_F(FooTest, ReturnsElementCountCorrectly) {
2216//     EXPECT_EQ(0, a_.size());
2217//     EXPECT_EQ(1, b_.size());
2218//   }
2219
2220#define TEST_F(test_fixture, test_name)\
2221  GTEST_TEST_(test_fixture, test_name, test_fixture, \
2222              ::testing::internal::GetTypeId<test_fixture>())
2223
2224}  // namespace testing
2225
2226// Use this function in main() to run all tests.  It returns 0 if all
2227// tests are successful, or 1 otherwise.
2228//
2229// RUN_ALL_TESTS() should be invoked after the command line has been
2230// parsed by InitGoogleTest().
2231//
2232// This function was formerly a macro; thus, it is in the global
2233// namespace and has an all-caps name.
2234int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
2235
2236inline int RUN_ALL_TESTS() {
2237  return ::testing::UnitTest::GetInstance()->Run();
2238}
2239
2240#endif  // GTEST_INCLUDE_GTEST_GTEST_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest_pred_impl.h
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command
31// 'gen_gtest_pred_impl.py 5'.  DO NOT EDIT BY HAND!
32//
33// Implements a family of generic predicate assertion macros.
34
35#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
36#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
37
38// Makes sure this header is not included before gtest.h.
39#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
40# error Do not include gtest_pred_impl.h directly.  Include gtest.h instead.
41#endif  // GTEST_INCLUDE_GTEST_GTEST_H_
42
43// This header implements a family of generic predicate assertion
44// macros:
45//
46//   ASSERT_PRED_FORMAT1(pred_format, v1)
47//   ASSERT_PRED_FORMAT2(pred_format, v1, v2)
48//   ...
49//
50// where pred_format is a function or functor that takes n (in the
51// case of ASSERT_PRED_FORMATn) values and their source expression
52// text, and returns a testing::AssertionResult.  See the definition
53// of ASSERT_EQ in gtest.h for an example.
54//
55// If you don't care about formatting, you can use the more
56// restrictive version:
57//
58//   ASSERT_PRED1(pred, v1)
59//   ASSERT_PRED2(pred, v1, v2)
60//   ...
61//
62// where pred is an n-ary function or functor that returns bool,
63// and the values v1, v2, ..., must support the << operator for
64// streaming to std::ostream.
65//
66// We also define the EXPECT_* variations.
67//
68// For now we only support predicates whose arity is at most 5.
69// Please email googletestframework@googlegroups.com if you need
70// support for higher arities.
71
72// GTEST_ASSERT_ is the basic statement to which all of the assertions
73// in this file reduce.  Don't use this in your code.
74
75#define GTEST_ASSERT_(expression, on_failure) \
76  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
77  if (const ::testing::AssertionResult gtest_ar = (expression)) \
78    ; \
79  else \
80    on_failure(gtest_ar.failure_message())
81
82
83// Helper function for implementing {EXPECT|ASSERT}_PRED1.  Don't use
84// this in your code.
85template <typename Pred,
86          typename T1>
87AssertionResult AssertPred1Helper(const char* pred_text,
88                                  const char* e1,
89                                  Pred pred,
90                                  const T1& v1) {
91  if (pred(v1)) return AssertionSuccess();
92
93  return AssertionFailure() << pred_text << "("
94                            << e1 << ") evaluates to false, where"
95                            << "\n" << e1 << " evaluates to " << v1;
96}
97
98// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
99// Don't use this in your code.
100#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
101  GTEST_ASSERT_(pred_format(#v1, v1), \
102                on_failure)
103
104// Internal macro for implementing {EXPECT|ASSERT}_PRED1.  Don't use
105// this in your code.
106#define GTEST_PRED1_(pred, v1, on_failure)\
107  GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
108                                             #v1, \
109                                             pred, \
110                                             v1), on_failure)
111
112// Unary predicate assertion macros.
113#define EXPECT_PRED_FORMAT1(pred_format, v1) \
114  GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
115#define EXPECT_PRED1(pred, v1) \
116  GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
117#define ASSERT_PRED_FORMAT1(pred_format, v1) \
118  GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
119#define ASSERT_PRED1(pred, v1) \
120  GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
121
122
123
124// Helper function for implementing {EXPECT|ASSERT}_PRED2.  Don't use
125// this in your code.
126template <typename Pred,
127          typename T1,
128          typename T2>
129AssertionResult AssertPred2Helper(const char* pred_text,
130                                  const char* e1,
131                                  const char* e2,
132                                  Pred pred,
133                                  const T1& v1,
134                                  const T2& v2) {
135  if (pred(v1, v2)) return AssertionSuccess();
136
137  return AssertionFailure() << pred_text << "("
138                            << e1 << ", "
139                            << e2 << ") evaluates to false, where"
140                            << "\n" << e1 << " evaluates to " << v1
141                            << "\n" << e2 << " evaluates to " << v2;
142}
143
144// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
145// Don't use this in your code.
146#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
147  GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
148                on_failure)
149
150// Internal macro for implementing {EXPECT|ASSERT}_PRED2.  Don't use
151// this in your code.
152#define GTEST_PRED2_(pred, v1, v2, on_failure)\
153  GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
154                                             #v1, \
155                                             #v2, \
156                                             pred, \
157                                             v1, \
158                                             v2), on_failure)
159
160// Binary predicate assertion macros.
161#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
162  GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
163#define EXPECT_PRED2(pred, v1, v2) \
164  GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
165#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
166  GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
167#define ASSERT_PRED2(pred, v1, v2) \
168  GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
169
170
171
172// Helper function for implementing {EXPECT|ASSERT}_PRED3.  Don't use
173// this in your code.
174template <typename Pred,
175          typename T1,
176          typename T2,
177          typename T3>
178AssertionResult AssertPred3Helper(const char* pred_text,
179                                  const char* e1,
180                                  const char* e2,
181                                  const char* e3,
182                                  Pred pred,
183                                  const T1& v1,
184                                  const T2& v2,
185                                  const T3& v3) {
186  if (pred(v1, v2, v3)) return AssertionSuccess();
187
188  return AssertionFailure() << pred_text << "("
189                            << e1 << ", "
190                            << e2 << ", "
191                            << e3 << ") evaluates to false, where"
192                            << "\n" << e1 << " evaluates to " << v1
193                            << "\n" << e2 << " evaluates to " << v2
194                            << "\n" << e3 << " evaluates to " << v3;
195}
196
197// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
198// Don't use this in your code.
199#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
200  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
201                on_failure)
202
203// Internal macro for implementing {EXPECT|ASSERT}_PRED3.  Don't use
204// this in your code.
205#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
206  GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
207                                             #v1, \
208                                             #v2, \
209                                             #v3, \
210                                             pred, \
211                                             v1, \
212                                             v2, \
213                                             v3), on_failure)
214
215// Ternary predicate assertion macros.
216#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
217  GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
218#define EXPECT_PRED3(pred, v1, v2, v3) \
219  GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
220#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
221  GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
222#define ASSERT_PRED3(pred, v1, v2, v3) \
223  GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
224
225
226
227// Helper function for implementing {EXPECT|ASSERT}_PRED4.  Don't use
228// this in your code.
229template <typename Pred,
230          typename T1,
231          typename T2,
232          typename T3,
233          typename T4>
234AssertionResult AssertPred4Helper(const char* pred_text,
235                                  const char* e1,
236                                  const char* e2,
237                                  const char* e3,
238                                  const char* e4,
239                                  Pred pred,
240                                  const T1& v1,
241                                  const T2& v2,
242                                  const T3& v3,
243                                  const T4& v4) {
244  if (pred(v1, v2, v3, v4)) return AssertionSuccess();
245
246  return AssertionFailure() << pred_text << "("
247                            << e1 << ", "
248                            << e2 << ", "
249                            << e3 << ", "
250                            << e4 << ") evaluates to false, where"
251                            << "\n" << e1 << " evaluates to " << v1
252                            << "\n" << e2 << " evaluates to " << v2
253                            << "\n" << e3 << " evaluates to " << v3
254                            << "\n" << e4 << " evaluates to " << v4;
255}
256
257// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
258// Don't use this in your code.
259#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
260  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
261                on_failure)
262
263// Internal macro for implementing {EXPECT|ASSERT}_PRED4.  Don't use
264// this in your code.
265#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
266  GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
267                                             #v1, \
268                                             #v2, \
269                                             #v3, \
270                                             #v4, \
271                                             pred, \
272                                             v1, \
273                                             v2, \
274                                             v3, \
275                                             v4), on_failure)
276
277// 4-ary predicate assertion macros.
278#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
279  GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
280#define EXPECT_PRED4(pred, v1, v2, v3, v4) \
281  GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
282#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
283  GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
284#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
285  GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
286
287
288
289// Helper function for implementing {EXPECT|ASSERT}_PRED5.  Don't use
290// this in your code.
291template <typename Pred,
292          typename T1,
293          typename T2,
294          typename T3,
295          typename T4,
296          typename T5>
297AssertionResult AssertPred5Helper(const char* pred_text,
298                                  const char* e1,
299                                  const char* e2,
300                                  const char* e3,
301                                  const char* e4,
302                                  const char* e5,
303                                  Pred pred,
304                                  const T1& v1,
305                                  const T2& v2,
306                                  const T3& v3,
307                                  const T4& v4,
308                                  const T5& v5) {
309  if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
310
311  return AssertionFailure() << pred_text << "("
312                            << e1 << ", "
313                            << e2 << ", "
314                            << e3 << ", "
315                            << e4 << ", "
316                            << e5 << ") evaluates to false, where"
317                            << "\n" << e1 << " evaluates to " << v1
318                            << "\n" << e2 << " evaluates to " << v2
319                            << "\n" << e3 << " evaluates to " << v3
320                            << "\n" << e4 << " evaluates to " << v4
321                            << "\n" << e5 << " evaluates to " << v5;
322}
323
324// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
325// Don't use this in your code.
326#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
327  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
328                on_failure)
329
330// Internal macro for implementing {EXPECT|ASSERT}_PRED5.  Don't use
331// this in your code.
332#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
333  GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
334                                             #v1, \
335                                             #v2, \
336                                             #v3, \
337                                             #v4, \
338                                             #v5, \
339                                             pred, \
340                                             v1, \
341                                             v2, \
342                                             v3, \
343                                             v4, \
344                                             v5), on_failure)
345
346// 5-ary predicate assertion macros.
347#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
348  GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
349#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
350  GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
351#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
352  GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
353#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
354  GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
355
356
357
358#endif  // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
trunk/3rdparty/googletest/googletest/include/gtest/gtest_prod.h
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Google C++ Testing Framework definitions useful in production code.
33
34#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
35#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
36
37// When you need to test the private or protected members of a class,
38// use the FRIEND_TEST macro to declare your tests as friends of the
39// class.  For example:
40//
41// class MyClass {
42//  private:
43//   void MyMethod();
44//   FRIEND_TEST(MyClassTest, MyMethod);
45// };
46//
47// class MyClassTest : public testing::Test {
48//   // ...
49// };
50//
51// TEST_F(MyClassTest, MyMethod) {
52//   // Can call MyClass::MyMethod() here.
53// }
54
55#define FRIEND_TEST(test_case_name, test_name)\
56friend class test_case_name##_##test_name##_Test
57
58#endif  // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/custom/gtest-port.h
r0r249096
1// Copyright 2015, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Injection point for custom user configurations.
31// The following macros can be defined:
32//
33//   Flag related macros:
34//     GTEST_FLAG(flag_name)
35//     GTEST_USE_OWN_FLAGFILE_FLAG_  - Define to 0 when the system provides its
36//                                     own flagfile flag parsing.
37//     GTEST_DECLARE_bool_(name)
38//     GTEST_DECLARE_int32_(name)
39//     GTEST_DECLARE_string_(name)
40//     GTEST_DEFINE_bool_(name, default_val, doc)
41//     GTEST_DEFINE_int32_(name, default_val, doc)
42//     GTEST_DEFINE_string_(name, default_val, doc)
43//
44//   Test filtering:
45//     GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that
46//                                  will be used if --GTEST_FLAG(test_filter)
47//                                  is not provided.
48//
49//   Logging:
50//     GTEST_LOG_(severity)
51//     GTEST_CHECK_(condition)
52//     Functions LogToStderr() and FlushInfoLog() have to be provided too.
53//
54//   Threading:
55//     GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided.
56//     GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are
57//                                         already provided.
58//     Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and
59//     GTEST_DEFINE_STATIC_MUTEX_(mutex)
60//
61//     GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
62//     GTEST_LOCK_EXCLUDED_(locks)
63//
64// ** Custom implementation starts here **
65
66#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
67#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
68
69#endif  // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/custom/gtest-printers.h
r0r249096
1// Copyright 2015, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// This file provides an injection point for custom printers in a local
31// installation of gTest.
32// It will be included from gtest-printers.h and the overrides in this file
33// will be visible to everyone.
34// See documentation at gtest/gtest-printers.h for details on how to define a
35// custom printer.
36//
37// ** Custom implementation starts here **
38
39#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
40#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
41
42#endif  // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/custom/gtest.h
r0r249096
1// Copyright 2015, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Injection point for custom user configurations.
31// The following macros can be defined:
32//
33// GTEST_OS_STACK_TRACE_GETTER_  - The name of an implementation of
34//                                 OsStackTraceGetterInterface.
35//
36// ** Custom implementation starts here **
37
38#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
39#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
40
41#endif  // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-death-test-internal.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file defines internal utilities needed for implementing
35// death tests.  They are subject to change without notice.
36
37#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
38#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
39
40#include "gtest/internal/gtest-internal.h"
41
42#include <stdio.h>
43
44namespace testing {
45namespace internal {
46
47GTEST_DECLARE_string_(internal_run_death_test);
48
49// Names of the flags (needed for parsing Google Test flags).
50const char kDeathTestStyleFlag[] = "death_test_style";
51const char kDeathTestUseFork[] = "death_test_use_fork";
52const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
53
54#if GTEST_HAS_DEATH_TEST
55
56// DeathTest is a class that hides much of the complexity of the
57// GTEST_DEATH_TEST_ macro.  It is abstract; its static Create method
58// returns a concrete class that depends on the prevailing death test
59// style, as defined by the --gtest_death_test_style and/or
60// --gtest_internal_run_death_test flags.
61
62// In describing the results of death tests, these terms are used with
63// the corresponding definitions:
64//
65// exit status:  The integer exit information in the format specified
66//               by wait(2)
67// exit code:    The integer code passed to exit(3), _exit(2), or
68//               returned from main()
69class GTEST_API_ DeathTest {
70 public:
71  // Create returns false if there was an error determining the
72  // appropriate action to take for the current death test; for example,
73  // if the gtest_death_test_style flag is set to an invalid value.
74  // The LastMessage method will return a more detailed message in that
75  // case.  Otherwise, the DeathTest pointer pointed to by the "test"
76  // argument is set.  If the death test should be skipped, the pointer
77  // is set to NULL; otherwise, it is set to the address of a new concrete
78  // DeathTest object that controls the execution of the current test.
79  static bool Create(const char* statement, const RE* regex,
80                     const char* file, int line, DeathTest** test);
81  DeathTest();
82  virtual ~DeathTest() { }
83
84  // A helper class that aborts a death test when it's deleted.
85  class ReturnSentinel {
86   public:
87    explicit ReturnSentinel(DeathTest* test) : test_(test) { }
88    ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
89   private:
90    DeathTest* const test_;
91    GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
92  } GTEST_ATTRIBUTE_UNUSED_;
93
94  // An enumeration of possible roles that may be taken when a death
95  // test is encountered.  EXECUTE means that the death test logic should
96  // be executed immediately.  OVERSEE means that the program should prepare
97  // the appropriate environment for a child process to execute the death
98  // test, then wait for it to complete.
99  enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
100
101  // An enumeration of the three reasons that a test might be aborted.
102  enum AbortReason {
103    TEST_ENCOUNTERED_RETURN_STATEMENT,
104    TEST_THREW_EXCEPTION,
105    TEST_DID_NOT_DIE
106  };
107
108  // Assumes one of the above roles.
109  virtual TestRole AssumeRole() = 0;
110
111  // Waits for the death test to finish and returns its status.
112  virtual int Wait() = 0;
113
114  // Returns true if the death test passed; that is, the test process
115  // exited during the test, its exit status matches a user-supplied
116  // predicate, and its stderr output matches a user-supplied regular
117  // expression.
118  // The user-supplied predicate may be a macro expression rather
119  // than a function pointer or functor, or else Wait and Passed could
120  // be combined.
121  virtual bool Passed(bool exit_status_ok) = 0;
122
123  // Signals that the death test did not die as expected.
124  virtual void Abort(AbortReason reason) = 0;
125
126  // Returns a human-readable outcome message regarding the outcome of
127  // the last death test.
128  static const char* LastMessage();
129
130  static void set_last_death_test_message(const std::string& message);
131
132 private:
133  // A string containing a description of the outcome of the last death test.
134  static std::string last_death_test_message_;
135
136  GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
137};
138
139// Factory interface for death tests.  May be mocked out for testing.
140class DeathTestFactory {
141 public:
142  virtual ~DeathTestFactory() { }
143  virtual bool Create(const char* statement, const RE* regex,
144                      const char* file, int line, DeathTest** test) = 0;
145};
146
147// A concrete DeathTestFactory implementation for normal use.
148class DefaultDeathTestFactory : public DeathTestFactory {
149 public:
150  virtual bool Create(const char* statement, const RE* regex,
151                      const char* file, int line, DeathTest** test);
152};
153
154// Returns true if exit_status describes a process that was terminated
155// by a signal, or exited normally with a nonzero exit code.
156GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
157
158// Traps C++ exceptions escaping statement and reports them as test
159// failures. Note that trapping SEH exceptions is not implemented here.
160# if GTEST_HAS_EXCEPTIONS
161#  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
162  try { \
163    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
164  } catch (const ::std::exception& gtest_exception) { \
165    fprintf(\
166        stderr, \
167        "\n%s: Caught std::exception-derived exception escaping the " \
168        "death test statement. Exception message: %s\n", \
169        ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
170        gtest_exception.what()); \
171    fflush(stderr); \
172    death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
173  } catch (...) { \
174    death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
175  }
176
177# else
178#  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
179  GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
180
181# endif
182
183// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
184// ASSERT_EXIT*, and EXPECT_EXIT*.
185# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \
186  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
187  if (::testing::internal::AlwaysTrue()) { \
188    const ::testing::internal::RE& gtest_regex = (regex); \
189    ::testing::internal::DeathTest* gtest_dt; \
190    if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \
191        __FILE__, __LINE__, &gtest_dt)) { \
192      goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
193    } \
194    if (gtest_dt != NULL) { \
195      ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
196          gtest_dt_ptr(gtest_dt); \
197      switch (gtest_dt->AssumeRole()) { \
198        case ::testing::internal::DeathTest::OVERSEE_TEST: \
199          if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
200            goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
201          } \
202          break; \
203        case ::testing::internal::DeathTest::EXECUTE_TEST: { \
204          ::testing::internal::DeathTest::ReturnSentinel \
205              gtest_sentinel(gtest_dt); \
206          GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
207          gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
208          break; \
209        } \
210        default: \
211          break; \
212      } \
213    } \
214  } else \
215    GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \
216      fail(::testing::internal::DeathTest::LastMessage())
217// The symbol "fail" here expands to something into which a message
218// can be streamed.
219
220// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
221// NDEBUG mode. In this case we need the statements to be executed, the regex is
222// ignored, and the macro must accept a streamed message even though the message
223// is never printed.
224# define GTEST_EXECUTE_STATEMENT_(statement, regex) \
225  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
226  if (::testing::internal::AlwaysTrue()) { \
227     GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
228  } else \
229    ::testing::Message()
230
231// A class representing the parsed contents of the
232// --gtest_internal_run_death_test flag, as it existed when
233// RUN_ALL_TESTS was called.
234class InternalRunDeathTestFlag {
235 public:
236  InternalRunDeathTestFlag(const std::string& a_file,
237                           int a_line,
238                           int an_index,
239                           int a_write_fd)
240      : file_(a_file), line_(a_line), index_(an_index),
241        write_fd_(a_write_fd) {}
242
243  ~InternalRunDeathTestFlag() {
244    if (write_fd_ >= 0)
245      posix::Close(write_fd_);
246  }
247
248  const std::string& file() const { return file_; }
249  int line() const { return line_; }
250  int index() const { return index_; }
251  int write_fd() const { return write_fd_; }
252
253 private:
254  std::string file_;
255  int line_;
256  int index_;
257  int write_fd_;
258
259  GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
260};
261
262// Returns a newly created InternalRunDeathTestFlag object with fields
263// initialized from the GTEST_FLAG(internal_run_death_test) flag if
264// the flag is specified; otherwise returns NULL.
265InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
266
267#else  // GTEST_HAS_DEATH_TEST
268
269// This macro is used for implementing macros such as
270// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
271// death tests are not supported. Those macros must compile on such systems
272// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
273// systems that support death tests. This allows one to write such a macro
274// on a system that does not support death tests and be sure that it will
275// compile on a death-test supporting system.
276//
277// Parameters:
278//   statement -  A statement that a macro such as EXPECT_DEATH would test
279//                for program termination. This macro has to make sure this
280//                statement is compiled but not executed, to ensure that
281//                EXPECT_DEATH_IF_SUPPORTED compiles with a certain
282//                parameter iff EXPECT_DEATH compiles with it.
283//   regex     -  A regex that a macro such as EXPECT_DEATH would use to test
284//                the output of statement.  This parameter has to be
285//                compiled but not evaluated by this macro, to ensure that
286//                this macro only accepts expressions that a macro such as
287//                EXPECT_DEATH would accept.
288//   terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
289//                and a return statement for ASSERT_DEATH_IF_SUPPORTED.
290//                This ensures that ASSERT_DEATH_IF_SUPPORTED will not
291//                compile inside functions where ASSERT_DEATH doesn't
292//                compile.
293//
294//  The branch that has an always false condition is used to ensure that
295//  statement and regex are compiled (and thus syntactically correct) but
296//  never executed. The unreachable code macro protects the terminator
297//  statement from generating an 'unreachable code' warning in case
298//  statement unconditionally returns or throws. The Message constructor at
299//  the end allows the syntax of streaming additional messages into the
300//  macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
301# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
302    GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
303    if (::testing::internal::AlwaysTrue()) { \
304      GTEST_LOG_(WARNING) \
305          << "Death tests are not supported on this platform.\n" \
306          << "Statement '" #statement "' cannot be verified."; \
307    } else if (::testing::internal::AlwaysFalse()) { \
308      ::testing::internal::RE::PartialMatch(".*", (regex)); \
309      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
310      terminator; \
311    } else \
312      ::testing::Message()
313
314#endif  // GTEST_HAS_DEATH_TEST
315
316}  // namespace internal
317}  // namespace testing
318
319#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-filepath.h
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: keith.ray@gmail.com (Keith Ray)
31//
32// Google Test filepath utilities
33//
34// This header file declares classes and functions used internally by
35// Google Test.  They are subject to change without notice.
36//
37// This file is #included in <gtest/internal/gtest-internal.h>.
38// Do not include this header file separately!
39
40#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
41#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
42
43#include "gtest/internal/gtest-string.h"
44
45namespace testing {
46namespace internal {
47
48// FilePath - a class for file and directory pathname manipulation which
49// handles platform-specific conventions (like the pathname separator).
50// Used for helper functions for naming files in a directory for xml output.
51// Except for Set methods, all methods are const or static, which provides an
52// "immutable value object" -- useful for peace of mind.
53// A FilePath with a value ending in a path separator ("like/this/") represents
54// a directory, otherwise it is assumed to represent a file. In either case,
55// it may or may not represent an actual file or directory in the file system.
56// Names are NOT checked for syntax correctness -- no checking for illegal
57// characters, malformed paths, etc.
58
59class GTEST_API_ FilePath {
60 public:
61  FilePath() : pathname_("") { }
62  FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
63
64  explicit FilePath(const std::string& pathname) : pathname_(pathname) {
65    Normalize();
66  }
67
68  FilePath& operator=(const FilePath& rhs) {
69    Set(rhs);
70    return *this;
71  }
72
73  void Set(const FilePath& rhs) {
74    pathname_ = rhs.pathname_;
75  }
76
77  const std::string& string() const { return pathname_; }
78  const char* c_str() const { return pathname_.c_str(); }
79
80  // Returns the current working directory, or "" if unsuccessful.
81  static FilePath GetCurrentDir();
82
83  // Given directory = "dir", base_name = "test", number = 0,
84  // extension = "xml", returns "dir/test.xml". If number is greater
85  // than zero (e.g., 12), returns "dir/test_12.xml".
86  // On Windows platform, uses \ as the separator rather than /.
87  static FilePath MakeFileName(const FilePath& directory,
88                               const FilePath& base_name,
89                               int number,
90                               const char* extension);
91
92  // Given directory = "dir", relative_path = "test.xml",
93  // returns "dir/test.xml".
94  // On Windows, uses \ as the separator rather than /.
95  static FilePath ConcatPaths(const FilePath& directory,
96                              const FilePath& relative_path);
97
98  // Returns a pathname for a file that does not currently exist. The pathname
99  // will be directory/base_name.extension or
100  // directory/base_name_<number>.extension if directory/base_name.extension
101  // already exists. The number will be incremented until a pathname is found
102  // that does not already exist.
103  // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
104  // There could be a race condition if two or more processes are calling this
105  // function at the same time -- they could both pick the same filename.
106  static FilePath GenerateUniqueFileName(const FilePath& directory,
107                                         const FilePath& base_name,
108                                         const char* extension);
109
110  // Returns true iff the path is "".
111  bool IsEmpty() const { return pathname_.empty(); }
112
113  // If input name has a trailing separator character, removes it and returns
114  // the name, otherwise return the name string unmodified.
115  // On Windows platform, uses \ as the separator, other platforms use /.
116  FilePath RemoveTrailingPathSeparator() const;
117
118  // Returns a copy of the FilePath with the directory part removed.
119  // Example: FilePath("path/to/file").RemoveDirectoryName() returns
120  // FilePath("file"). If there is no directory part ("just_a_file"), it returns
121  // the FilePath unmodified. If there is no file part ("just_a_dir/") it
122  // returns an empty FilePath ("").
123  // On Windows platform, '\' is the path separator, otherwise it is '/'.
124  FilePath RemoveDirectoryName() const;
125
126  // RemoveFileName returns the directory path with the filename removed.
127  // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
128  // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
129  // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
130  // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
131  // On Windows platform, '\' is the path separator, otherwise it is '/'.
132  FilePath RemoveFileName() const;
133
134  // Returns a copy of the FilePath with the case-insensitive extension removed.
135  // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
136  // FilePath("dir/file"). If a case-insensitive extension is not
137  // found, returns a copy of the original FilePath.
138  FilePath RemoveExtension(const char* extension) const;
139
140  // Creates directories so that path exists. Returns true if successful or if
141  // the directories already exist; returns false if unable to create
142  // directories for any reason. Will also return false if the FilePath does
143  // not represent a directory (that is, it doesn't end with a path separator).
144  bool CreateDirectoriesRecursively() const;
145
146  // Create the directory so that path exists. Returns true if successful or
147  // if the directory already exists; returns false if unable to create the
148  // directory for any reason, including if the parent directory does not
149  // exist. Not named "CreateDirectory" because that's a macro on Windows.
150  bool CreateFolder() const;
151
152  // Returns true if FilePath describes something in the file-system,
153  // either a file, directory, or whatever, and that something exists.
154  bool FileOrDirectoryExists() const;
155
156  // Returns true if pathname describes a directory in the file-system
157  // that exists.
158  bool DirectoryExists() const;
159
160  // Returns true if FilePath ends with a path separator, which indicates that
161  // it is intended to represent a directory. Returns false otherwise.
162  // This does NOT check that a directory (or file) actually exists.
163  bool IsDirectory() const;
164
165  // Returns true if pathname describes a root directory. (Windows has one
166  // root directory per disk drive.)
167  bool IsRootDirectory() const;
168
169  // Returns true if pathname describes an absolute path.
170  bool IsAbsolutePath() const;
171
172 private:
173  // Replaces multiple consecutive separators with a single separator.
174  // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
175  // redundancies that might be in a pathname involving "." or "..".
176  //
177  // A pathname with multiple consecutive separators may occur either through
178  // user error or as a result of some scripts or APIs that generate a pathname
179  // with a trailing separator. On other platforms the same API or script
180  // may NOT generate a pathname with a trailing "/". Then elsewhere that
181  // pathname may have another "/" and pathname components added to it,
182  // without checking for the separator already being there.
183  // The script language and operating system may allow paths like "foo//bar"
184  // but some of the functions in FilePath will not handle that correctly. In
185  // particular, RemoveTrailingPathSeparator() only removes one separator, and
186  // it is called in CreateDirectoriesRecursively() assuming that it will change
187  // a pathname from directory syntax (trailing separator) to filename syntax.
188  //
189  // On Windows this method also replaces the alternate path separator '/' with
190  // the primary path separator '\\', so that for example "bar\\/\\foo" becomes
191  // "bar\\foo".
192
193  void Normalize();
194
195  // Returns a pointer to the last occurence of a valid path separator in
196  // the FilePath. On Windows, for example, both '/' and '\' are valid path
197  // separators. Returns NULL if no path separator was found.
198  const char* FindLastPathSeparator() const;
199
200  std::string pathname_;
201};  // class FilePath
202
203}  // namespace internal
204}  // namespace testing
205
206#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-internal.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file declares functions and macros used internally by
35// Google Test.  They are subject to change without notice.
36
37#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
38#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
39
40#include "gtest/internal/gtest-port.h"
41
42#if GTEST_OS_LINUX
43# include <stdlib.h>
44# include <sys/types.h>
45# include <sys/wait.h>
46# include <unistd.h>
47#endif  // GTEST_OS_LINUX
48
49#if GTEST_HAS_EXCEPTIONS
50# include <stdexcept>
51#endif
52
53#include <ctype.h>
54#include <float.h>
55#include <string.h>
56#include <iomanip>
57#include <limits>
58#include <map>
59#include <set>
60#include <string>
61#include <vector>
62
63#include "gtest/gtest-message.h"
64#include "gtest/internal/gtest-string.h"
65#include "gtest/internal/gtest-filepath.h"
66#include "gtest/internal/gtest-type-util.h"
67
68// Due to C++ preprocessor weirdness, we need double indirection to
69// concatenate two tokens when one of them is __LINE__.  Writing
70//
71//   foo ## __LINE__
72//
73// will result in the token foo__LINE__, instead of foo followed by
74// the current line number.  For more details, see
75// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
76#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
77#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
78
79class ProtocolMessage;
80namespace proto2 { class Message; }
81
82namespace testing {
83
84// Forward declarations.
85
86class AssertionResult;                 // Result of an assertion.
87class Message;                         // Represents a failure message.
88class Test;                            // Represents a test.
89class TestInfo;                        // Information about a test.
90class TestPartResult;                  // Result of a test part.
91class UnitTest;                        // A collection of test cases.
92
93template <typename T>
94::std::string PrintToString(const T& value);
95
96namespace internal {
97
98struct TraceInfo;                      // Information about a trace point.
99class ScopedTrace;                     // Implements scoped trace.
100class TestInfoImpl;                    // Opaque implementation of TestInfo
101class UnitTestImpl;                    // Opaque implementation of UnitTest
102
103// The text used in failure messages to indicate the start of the
104// stack trace.
105GTEST_API_ extern const char kStackTraceMarker[];
106
107// Two overloaded helpers for checking at compile time whether an
108// expression is a null pointer literal (i.e. NULL or any 0-valued
109// compile-time integral constant).  Their return values have
110// different sizes, so we can use sizeof() to test which version is
111// picked by the compiler.  These helpers have no implementations, as
112// we only need their signatures.
113//
114// Given IsNullLiteralHelper(x), the compiler will pick the first
115// version if x can be implicitly converted to Secret*, and pick the
116// second version otherwise.  Since Secret is a secret and incomplete
117// type, the only expression a user can write that has type Secret* is
118// a null pointer literal.  Therefore, we know that x is a null
119// pointer literal if and only if the first version is picked by the
120// compiler.
121char IsNullLiteralHelper(Secret* p);
122char (&IsNullLiteralHelper(...))[2];  // NOLINT
123
124// A compile-time bool constant that is true if and only if x is a
125// null pointer literal (i.e. NULL or any 0-valued compile-time
126// integral constant).
127#ifdef GTEST_ELLIPSIS_NEEDS_POD_
128// We lose support for NULL detection where the compiler doesn't like
129// passing non-POD classes through ellipsis (...).
130# define GTEST_IS_NULL_LITERAL_(x) false
131#else
132# define GTEST_IS_NULL_LITERAL_(x) \
133    (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
134#endif  // GTEST_ELLIPSIS_NEEDS_POD_
135
136// Appends the user-supplied message to the Google-Test-generated message.
137GTEST_API_ std::string AppendUserMessage(
138    const std::string& gtest_msg, const Message& user_msg);
139
140#if GTEST_HAS_EXCEPTIONS
141
142// This exception is thrown by (and only by) a failed Google Test
143// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
144// are enabled).  We derive it from std::runtime_error, which is for
145// errors presumably detectable only at run time.  Since
146// std::runtime_error inherits from std::exception, many testing
147// frameworks know how to extract and print the message inside it.
148class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
149 public:
150  explicit GoogleTestFailureException(const TestPartResult& failure);
151};
152
153#endif  // GTEST_HAS_EXCEPTIONS
154
155// A helper class for creating scoped traces in user programs.
156class GTEST_API_ ScopedTrace {
157 public:
158  // The c'tor pushes the given source file location and message onto
159  // a trace stack maintained by Google Test.
160  ScopedTrace(const char* file, int line, const Message& message);
161
162  // The d'tor pops the info pushed by the c'tor.
163  //
164  // Note that the d'tor is not virtual in order to be efficient.
165  // Don't inherit from ScopedTrace!
166  ~ScopedTrace();
167
168 private:
169  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
170} GTEST_ATTRIBUTE_UNUSED_;  // A ScopedTrace object does its job in its
171                            // c'tor and d'tor.  Therefore it doesn't
172                            // need to be used otherwise.
173
174namespace edit_distance {
175// Returns the optimal edits to go from 'left' to 'right'.
176// All edits cost the same, with replace having lower priority than
177// add/remove.
178// Simple implementation of the Wagner–Fischer algorithm.
179// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
180enum EditType { kMatch, kAdd, kRemove, kReplace };
181GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
182    const std::vector<size_t>& left, const std::vector<size_t>& right);
183
184// Same as above, but the input is represented as strings.
185GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
186    const std::vector<std::string>& left,
187    const std::vector<std::string>& right);
188
189// Create a diff of the input strings in Unified diff format.
190GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
191                                         const std::vector<std::string>& right,
192                                         size_t context = 2);
193
194}  // namespace edit_distance
195
196// Calculate the diff between 'left' and 'right' and return it in unified diff
197// format.
198// If not null, stores in 'total_line_count' the total number of lines found
199// in left + right.
200GTEST_API_ std::string DiffStrings(const std::string& left,
201                                   const std::string& right,
202                                   size_t* total_line_count);
203
204// Constructs and returns the message for an equality assertion
205// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
206//
207// The first four parameters are the expressions used in the assertion
208// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
209// where foo is 5 and bar is 6, we have:
210//
211//   expected_expression: "foo"
212//   actual_expression:   "bar"
213//   expected_value:      "5"
214//   actual_value:        "6"
215//
216// The ignoring_case parameter is true iff the assertion is a
217// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
218// be inserted into the message.
219GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
220                                     const char* actual_expression,
221                                     const std::string& expected_value,
222                                     const std::string& actual_value,
223                                     bool ignoring_case);
224
225// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
226GTEST_API_ std::string GetBoolAssertionFailureMessage(
227    const AssertionResult& assertion_result,
228    const char* expression_text,
229    const char* actual_predicate_value,
230    const char* expected_predicate_value);
231
232// This template class represents an IEEE floating-point number
233// (either single-precision or double-precision, depending on the
234// template parameters).
235//
236// The purpose of this class is to do more sophisticated number
237// comparison.  (Due to round-off error, etc, it's very unlikely that
238// two floating-points will be equal exactly.  Hence a naive
239// comparison by the == operation often doesn't work.)
240//
241// Format of IEEE floating-point:
242//
243//   The most-significant bit being the leftmost, an IEEE
244//   floating-point looks like
245//
246//     sign_bit exponent_bits fraction_bits
247//
248//   Here, sign_bit is a single bit that designates the sign of the
249//   number.
250//
251//   For float, there are 8 exponent bits and 23 fraction bits.
252//
253//   For double, there are 11 exponent bits and 52 fraction bits.
254//
255//   More details can be found at
256//   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
257//
258// Template parameter:
259//
260//   RawType: the raw floating-point type (either float or double)
261template <typename RawType>
262class FloatingPoint {
263 public:
264  // Defines the unsigned integer type that has the same size as the
265  // floating point number.
266  typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
267
268  // Constants.
269
270  // # of bits in a number.
271  static const size_t kBitCount = 8*sizeof(RawType);
272
273  // # of fraction bits in a number.
274  static const size_t kFractionBitCount =
275    std::numeric_limits<RawType>::digits - 1;
276
277  // # of exponent bits in a number.
278  static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
279
280  // The mask for the sign bit.
281  static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
282
283  // The mask for the fraction bits.
284  static const Bits kFractionBitMask =
285    ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
286
287  // The mask for the exponent bits.
288  static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
289
290  // How many ULP's (Units in the Last Place) we want to tolerate when
291  // comparing two numbers.  The larger the value, the more error we
292  // allow.  A 0 value means that two numbers must be exactly the same
293  // to be considered equal.
294  //
295  // The maximum error of a single floating-point operation is 0.5
296  // units in the last place.  On Intel CPU's, all floating-point
297  // calculations are done with 80-bit precision, while double has 64
298  // bits.  Therefore, 4 should be enough for ordinary use.
299  //
300  // See the following article for more details on ULP:
301  // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
302  static const size_t kMaxUlps = 4;
303
304  // Constructs a FloatingPoint from a raw floating-point number.
305  //
306  // On an Intel CPU, passing a non-normalized NAN (Not a Number)
307  // around may change its bits, although the new value is guaranteed
308  // to be also a NAN.  Therefore, don't expect this constructor to
309  // preserve the bits in x when x is a NAN.
310  explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
311
312  // Static methods
313
314  // Reinterprets a bit pattern as a floating-point number.
315  //
316  // This function is needed to test the AlmostEquals() method.
317  static RawType ReinterpretBits(const Bits bits) {
318    FloatingPoint fp(0);
319    fp.u_.bits_ = bits;
320    return fp.u_.value_;
321  }
322
323  // Returns the floating-point number that represent positive infinity.
324  static RawType Infinity() {
325    return ReinterpretBits(kExponentBitMask);
326  }
327
328  // Returns the maximum representable finite floating-point number.
329  static RawType Max();
330
331  // Non-static methods
332
333  // Returns the bits that represents this number.
334  const Bits &bits() const { return u_.bits_; }
335
336  // Returns the exponent bits of this number.
337  Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
338
339  // Returns the fraction bits of this number.
340  Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
341
342  // Returns the sign bit of this number.
343  Bits sign_bit() const { return kSignBitMask & u_.bits_; }
344
345  // Returns true iff this is NAN (not a number).
346  bool is_nan() const {
347    // It's a NAN if the exponent bits are all ones and the fraction
348    // bits are not entirely zeros.
349    return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
350  }
351
352  // Returns true iff this number is at most kMaxUlps ULP's away from
353  // rhs.  In particular, this function:
354  //
355  //   - returns false if either number is (or both are) NAN.
356  //   - treats really large numbers as almost equal to infinity.
357  //   - thinks +0.0 and -0.0 are 0 DLP's apart.
358  bool AlmostEquals(const FloatingPoint& rhs) const {
359    // The IEEE standard says that any comparison operation involving
360    // a NAN must return false.
361    if (is_nan() || rhs.is_nan()) return false;
362
363    return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
364        <= kMaxUlps;
365  }
366
367 private:
368  // The data type used to store the actual floating-point number.
369  union FloatingPointUnion {
370    RawType value_;  // The raw floating-point number.
371    Bits bits_;      // The bits that represent the number.
372  };
373
374  // Converts an integer from the sign-and-magnitude representation to
375  // the biased representation.  More precisely, let N be 2 to the
376  // power of (kBitCount - 1), an integer x is represented by the
377  // unsigned number x + N.
378  //
379  // For instance,
380  //
381  //   -N + 1 (the most negative number representable using
382  //          sign-and-magnitude) is represented by 1;
383  //   0      is represented by N; and
384  //   N - 1  (the biggest number representable using
385  //          sign-and-magnitude) is represented by 2N - 1.
386  //
387  // Read http://en.wikipedia.org/wiki/Signed_number_representations
388  // for more details on signed number representations.
389  static Bits SignAndMagnitudeToBiased(const Bits &sam) {
390    if (kSignBitMask & sam) {
391      // sam represents a negative number.
392      return ~sam + 1;
393    } else {
394      // sam represents a positive number.
395      return kSignBitMask | sam;
396    }
397  }
398
399  // Given two numbers in the sign-and-magnitude representation,
400  // returns the distance between them as an unsigned number.
401  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
402                                                     const Bits &sam2) {
403    const Bits biased1 = SignAndMagnitudeToBiased(sam1);
404    const Bits biased2 = SignAndMagnitudeToBiased(sam2);
405    return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
406  }
407
408  FloatingPointUnion u_;
409};
410
411// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
412// macro defined by <windows.h>.
413template <>
414inline float FloatingPoint<float>::Max() { return FLT_MAX; }
415template <>
416inline double FloatingPoint<double>::Max() { return DBL_MAX; }
417
418// Typedefs the instances of the FloatingPoint template class that we
419// care to use.
420typedef FloatingPoint<float> Float;
421typedef FloatingPoint<double> Double;
422
423// In order to catch the mistake of putting tests that use different
424// test fixture classes in the same test case, we need to assign
425// unique IDs to fixture classes and compare them.  The TypeId type is
426// used to hold such IDs.  The user should treat TypeId as an opaque
427// type: the only operation allowed on TypeId values is to compare
428// them for equality using the == operator.
429typedef const void* TypeId;
430
431template <typename T>
432class TypeIdHelper {
433 public:
434  // dummy_ must not have a const type.  Otherwise an overly eager
435  // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
436  // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
437  static bool dummy_;
438};
439
440template <typename T>
441bool TypeIdHelper<T>::dummy_ = false;
442
443// GetTypeId<T>() returns the ID of type T.  Different values will be
444// returned for different types.  Calling the function twice with the
445// same type argument is guaranteed to return the same ID.
446template <typename T>
447TypeId GetTypeId() {
448  // The compiler is required to allocate a different
449  // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
450  // the template.  Therefore, the address of dummy_ is guaranteed to
451  // be unique.
452  return &(TypeIdHelper<T>::dummy_);
453}
454
455// Returns the type ID of ::testing::Test.  Always call this instead
456// of GetTypeId< ::testing::Test>() to get the type ID of
457// ::testing::Test, as the latter may give the wrong result due to a
458// suspected linker bug when compiling Google Test as a Mac OS X
459// framework.
460GTEST_API_ TypeId GetTestTypeId();
461
462// Defines the abstract factory interface that creates instances
463// of a Test object.
464class TestFactoryBase {
465 public:
466  virtual ~TestFactoryBase() {}
467
468  // Creates a test instance to run. The instance is both created and destroyed
469  // within TestInfoImpl::Run()
470  virtual Test* CreateTest() = 0;
471
472 protected:
473  TestFactoryBase() {}
474
475 private:
476  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
477};
478
479// This class provides implementation of TeastFactoryBase interface.
480// It is used in TEST and TEST_F macros.
481template <class TestClass>
482class TestFactoryImpl : public TestFactoryBase {
483 public:
484  virtual Test* CreateTest() { return new TestClass; }
485};
486
487#if GTEST_OS_WINDOWS
488
489// Predicate-formatters for implementing the HRESULT checking macros
490// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
491// We pass a long instead of HRESULT to avoid causing an
492// include dependency for the HRESULT type.
493GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
494                                            long hr);  // NOLINT
495GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
496                                            long hr);  // NOLINT
497
498#endif  // GTEST_OS_WINDOWS
499
500// Types of SetUpTestCase() and TearDownTestCase() functions.
501typedef void (*SetUpTestCaseFunc)();
502typedef void (*TearDownTestCaseFunc)();
503
504struct CodeLocation {
505  CodeLocation(const string& a_file, int a_line) : file(a_file), line(a_line) {}
506
507  string file;
508  int line;
509};
510
511// Creates a new TestInfo object and registers it with Google Test;
512// returns the created object.
513//
514// Arguments:
515//
516//   test_case_name:   name of the test case
517//   name:             name of the test
518//   type_param        the name of the test's type parameter, or NULL if
519//                     this is not a typed or a type-parameterized test.
520//   value_param       text representation of the test's value parameter,
521//                     or NULL if this is not a type-parameterized test.
522//   code_location:    code location where the test is defined
523//   fixture_class_id: ID of the test fixture class
524//   set_up_tc:        pointer to the function that sets up the test case
525//   tear_down_tc:     pointer to the function that tears down the test case
526//   factory:          pointer to the factory that creates a test object.
527//                     The newly created TestInfo instance will assume
528//                     ownership of the factory object.
529GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
530    const char* test_case_name,
531    const char* name,
532    const char* type_param,
533    const char* value_param,
534    CodeLocation code_location,
535    TypeId fixture_class_id,
536    SetUpTestCaseFunc set_up_tc,
537    TearDownTestCaseFunc tear_down_tc,
538    TestFactoryBase* factory);
539
540// If *pstr starts with the given prefix, modifies *pstr to be right
541// past the prefix and returns true; otherwise leaves *pstr unchanged
542// and returns false.  None of pstr, *pstr, and prefix can be NULL.
543GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
544
545#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
546
547// State of the definition of a type-parameterized test case.
548class GTEST_API_ TypedTestCasePState {
549 public:
550  TypedTestCasePState() : registered_(false) {}
551
552  // Adds the given test name to defined_test_names_ and return true
553  // if the test case hasn't been registered; otherwise aborts the
554  // program.
555  bool AddTestName(const char* file, int line, const char* case_name,
556                   const char* test_name) {
557    if (registered_) {
558      fprintf(stderr, "%s Test %s must be defined before "
559              "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n",
560              FormatFileLocation(file, line).c_str(), test_name, case_name);
561      fflush(stderr);
562      posix::Abort();
563    }
564    registered_tests_.insert(
565        ::std::make_pair(test_name, CodeLocation(file, line)));
566    return true;
567  }
568
569  bool TestExists(const std::string& test_name) const {
570    return registered_tests_.count(test_name) > 0;
571  }
572
573  const CodeLocation& GetCodeLocation(const std::string& test_name) const {
574    RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
575    GTEST_CHECK_(it != registered_tests_.end());
576    return it->second;
577  }
578
579  // Verifies that registered_tests match the test names in
580  // defined_test_names_; returns registered_tests if successful, or
581  // aborts the program otherwise.
582  const char* VerifyRegisteredTestNames(
583      const char* file, int line, const char* registered_tests);
584
585 private:
586  typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
587
588  bool registered_;
589  RegisteredTestsMap registered_tests_;
590};
591
592// Skips to the first non-space char after the first comma in 'str';
593// returns NULL if no comma is found in 'str'.
594inline const char* SkipComma(const char* str) {
595  const char* comma = strchr(str, ',');
596  if (comma == NULL) {
597    return NULL;
598  }
599  while (IsSpace(*(++comma))) {}
600  return comma;
601}
602
603// Returns the prefix of 'str' before the first comma in it; returns
604// the entire string if it contains no comma.
605inline std::string GetPrefixUntilComma(const char* str) {
606  const char* comma = strchr(str, ',');
607  return comma == NULL ? str : std::string(str, comma);
608}
609
610// Splits a given string on a given delimiter, populating a given
611// vector with the fields.
612void SplitString(const ::std::string& str, char delimiter,
613                 ::std::vector< ::std::string>* dest);
614
615// TypeParameterizedTest<Fixture, TestSel, Types>::Register()
616// registers a list of type-parameterized tests with Google Test.  The
617// return value is insignificant - we just need to return something
618// such that we can call this function in a namespace scope.
619//
620// Implementation note: The GTEST_TEMPLATE_ macro declares a template
621// template parameter.  It's defined in gtest-type-util.h.
622template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
623class TypeParameterizedTest {
624 public:
625  // 'index' is the index of the test in the type list 'Types'
626  // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase,
627  // Types).  Valid values for 'index' are [0, N - 1] where N is the
628  // length of Types.
629  static bool Register(const char* prefix,
630                       CodeLocation code_location,
631                       const char* case_name, const char* test_names,
632                       int index) {
633    typedef typename Types::Head Type;
634    typedef Fixture<Type> FixtureClass;
635    typedef typename GTEST_BIND_(TestSel, Type) TestClass;
636
637    // First, registers the first type-parameterized test in the type
638    // list.
639    MakeAndRegisterTestInfo(
640        (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/"
641         + StreamableToString(index)).c_str(),
642        StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
643        GetTypeName<Type>().c_str(),
644        NULL,  // No value parameter.
645        code_location,
646        GetTypeId<FixtureClass>(),
647        TestClass::SetUpTestCase,
648        TestClass::TearDownTestCase,
649        new TestFactoryImpl<TestClass>);
650
651    // Next, recurses (at compile time) with the tail of the type list.
652    return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail>
653        ::Register(prefix, code_location, case_name, test_names, index + 1);
654  }
655};
656
657// The base case for the compile time recursion.
658template <GTEST_TEMPLATE_ Fixture, class TestSel>
659class TypeParameterizedTest<Fixture, TestSel, Types0> {
660 public:
661  static bool Register(const char* /*prefix*/, CodeLocation,
662                       const char* /*case_name*/, const char* /*test_names*/,
663                       int /*index*/) {
664    return true;
665  }
666};
667
668// TypeParameterizedTestCase<Fixture, Tests, Types>::Register()
669// registers *all combinations* of 'Tests' and 'Types' with Google
670// Test.  The return value is insignificant - we just need to return
671// something such that we can call this function in a namespace scope.
672template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
673class TypeParameterizedTestCase {
674 public:
675  static bool Register(const char* prefix, CodeLocation code_location,
676                       const TypedTestCasePState* state,
677                       const char* case_name, const char* test_names) {
678    std::string test_name = StripTrailingSpaces(
679        GetPrefixUntilComma(test_names));
680    if (!state->TestExists(test_name)) {
681      fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
682              case_name, test_name.c_str(),
683              FormatFileLocation(code_location.file.c_str(),
684                                 code_location.line).c_str());
685      fflush(stderr);
686      posix::Abort();
687    }
688    const CodeLocation& test_location = state->GetCodeLocation(test_name);
689
690    typedef typename Tests::Head Head;
691
692    // First, register the first test in 'Test' for each type in 'Types'.
693    TypeParameterizedTest<Fixture, Head, Types>::Register(
694        prefix, test_location, case_name, test_names, 0);
695
696    // Next, recurses (at compile time) with the tail of the test list.
697    return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types>
698        ::Register(prefix, code_location, state,
699                   case_name, SkipComma(test_names));
700  }
701};
702
703// The base case for the compile time recursion.
704template <GTEST_TEMPLATE_ Fixture, typename Types>
705class TypeParameterizedTestCase<Fixture, Templates0, Types> {
706 public:
707  static bool Register(const char* /*prefix*/, CodeLocation,
708                       const TypedTestCasePState* /*state*/,
709                       const char* /*case_name*/, const char* /*test_names*/) {
710    return true;
711  }
712};
713
714#endif  // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
715
716// Returns the current OS stack trace as an std::string.
717//
718// The maximum number of stack frames to be included is specified by
719// the gtest_stack_trace_depth flag.  The skip_count parameter
720// specifies the number of top frames to be skipped, which doesn't
721// count against the number of frames to be included.
722//
723// For example, if Foo() calls Bar(), which in turn calls
724// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
725// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
726GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
727    UnitTest* unit_test, int skip_count);
728
729// Helpers for suppressing warnings on unreachable code or constant
730// condition.
731
732// Always returns true.
733GTEST_API_ bool AlwaysTrue();
734
735// Always returns false.
736inline bool AlwaysFalse() { return !AlwaysTrue(); }
737
738// Helper for suppressing false warning from Clang on a const char*
739// variable declared in a conditional expression always being NULL in
740// the else branch.
741struct GTEST_API_ ConstCharPtr {
742  ConstCharPtr(const char* str) : value(str) {}
743  operator bool() const { return true; }
744  const char* value;
745};
746
747// A simple Linear Congruential Generator for generating random
748// numbers with a uniform distribution.  Unlike rand() and srand(), it
749// doesn't use global state (and therefore can't interfere with user
750// code).  Unlike rand_r(), it's portable.  An LCG isn't very random,
751// but it's good enough for our purposes.
752class GTEST_API_ Random {
753 public:
754  static const UInt32 kMaxRange = 1u << 31;
755
756  explicit Random(UInt32 seed) : state_(seed) {}
757
758  void Reseed(UInt32 seed) { state_ = seed; }
759
760  // Generates a random number from [0, range).  Crashes if 'range' is
761  // 0 or greater than kMaxRange.
762  UInt32 Generate(UInt32 range);
763
764 private:
765  UInt32 state_;
766  GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
767};
768
769// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
770// compiler error iff T1 and T2 are different types.
771template <typename T1, typename T2>
772struct CompileAssertTypesEqual;
773
774template <typename T>
775struct CompileAssertTypesEqual<T, T> {
776};
777
778// Removes the reference from a type if it is a reference type,
779// otherwise leaves it unchanged.  This is the same as
780// tr1::remove_reference, which is not widely available yet.
781template <typename T>
782struct RemoveReference { typedef T type; };  // NOLINT
783template <typename T>
784struct RemoveReference<T&> { typedef T type; };  // NOLINT
785
786// A handy wrapper around RemoveReference that works when the argument
787// T depends on template parameters.
788#define GTEST_REMOVE_REFERENCE_(T) \
789    typename ::testing::internal::RemoveReference<T>::type
790
791// Removes const from a type if it is a const type, otherwise leaves
792// it unchanged.  This is the same as tr1::remove_const, which is not
793// widely available yet.
794template <typename T>
795struct RemoveConst { typedef T type; };  // NOLINT
796template <typename T>
797struct RemoveConst<const T> { typedef T type; };  // NOLINT
798
799// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above
800// definition to fail to remove the const in 'const int[3]' and 'const
801// char[3][4]'.  The following specialization works around the bug.
802template <typename T, size_t N>
803struct RemoveConst<const T[N]> {
804  typedef typename RemoveConst<T>::type type[N];
805};
806
807#if defined(_MSC_VER) && _MSC_VER < 1400
808// This is the only specialization that allows VC++ 7.1 to remove const in
809// 'const int[3] and 'const int[3][4]'.  However, it causes trouble with GCC
810// and thus needs to be conditionally compiled.
811template <typename T, size_t N>
812struct RemoveConst<T[N]> {
813  typedef typename RemoveConst<T>::type type[N];
814};
815#endif
816
817// A handy wrapper around RemoveConst that works when the argument
818// T depends on template parameters.
819#define GTEST_REMOVE_CONST_(T) \
820    typename ::testing::internal::RemoveConst<T>::type
821
822// Turns const U&, U&, const U, and U all into U.
823#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
824    GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T))
825
826// Adds reference to a type if it is not a reference type,
827// otherwise leaves it unchanged.  This is the same as
828// tr1::add_reference, which is not widely available yet.
829template <typename T>
830struct AddReference { typedef T& type; };  // NOLINT
831template <typename T>
832struct AddReference<T&> { typedef T& type; };  // NOLINT
833
834// A handy wrapper around AddReference that works when the argument T
835// depends on template parameters.
836#define GTEST_ADD_REFERENCE_(T) \
837    typename ::testing::internal::AddReference<T>::type
838
839// Adds a reference to const on top of T as necessary.  For example,
840// it transforms
841//
842//   char         ==> const char&
843//   const char   ==> const char&
844//   char&        ==> const char&
845//   const char&  ==> const char&
846//
847// The argument T must depend on some template parameters.
848#define GTEST_REFERENCE_TO_CONST_(T) \
849    GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T))
850
851// ImplicitlyConvertible<From, To>::value is a compile-time bool
852// constant that's true iff type From can be implicitly converted to
853// type To.
854template <typename From, typename To>
855class ImplicitlyConvertible {
856 private:
857  // We need the following helper functions only for their types.
858  // They have no implementations.
859
860  // MakeFrom() is an expression whose type is From.  We cannot simply
861  // use From(), as the type From may not have a public default
862  // constructor.
863  static typename AddReference<From>::type MakeFrom();
864
865  // These two functions are overloaded.  Given an expression
866  // Helper(x), the compiler will pick the first version if x can be
867  // implicitly converted to type To; otherwise it will pick the
868  // second version.
869  //
870  // The first version returns a value of size 1, and the second
871  // version returns a value of size 2.  Therefore, by checking the
872  // size of Helper(x), which can be done at compile time, we can tell
873  // which version of Helper() is used, and hence whether x can be
874  // implicitly converted to type To.
875  static char Helper(To);
876  static char (&Helper(...))[2];  // NOLINT
877
878  // We have to put the 'public' section after the 'private' section,
879  // or MSVC refuses to compile the code.
880 public:
881#if defined(__BORLANDC__)
882  // C++Builder cannot use member overload resolution during template
883  // instantiation.  The simplest workaround is to use its C++0x type traits
884  // functions (C++Builder 2009 and above only).
885  static const bool value = __is_convertible(From, To);
886#else
887  // MSVC warns about implicitly converting from double to int for
888  // possible loss of data, so we need to temporarily disable the
889  // warning.
890  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244)
891  static const bool value =
892      sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
893  GTEST_DISABLE_MSC_WARNINGS_POP_()
894#endif  // __BORLANDC__
895};
896template <typename From, typename To>
897const bool ImplicitlyConvertible<From, To>::value;
898
899// IsAProtocolMessage<T>::value is a compile-time bool constant that's
900// true iff T is type ProtocolMessage, proto2::Message, or a subclass
901// of those.
902template <typename T>
903struct IsAProtocolMessage
904    : public bool_constant<
905  ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value ||
906  ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> {
907};
908
909// When the compiler sees expression IsContainerTest<C>(0), if C is an
910// STL-style container class, the first overload of IsContainerTest
911// will be viable (since both C::iterator* and C::const_iterator* are
912// valid types and NULL can be implicitly converted to them).  It will
913// be picked over the second overload as 'int' is a perfect match for
914// the type of argument 0.  If C::iterator or C::const_iterator is not
915// a valid type, the first overload is not viable, and the second
916// overload will be picked.  Therefore, we can determine whether C is
917// a container class by checking the type of IsContainerTest<C>(0).
918// The value of the expression is insignificant.
919//
920// Note that we look for both C::iterator and C::const_iterator.  The
921// reason is that C++ injects the name of a class as a member of the
922// class itself (e.g. you can refer to class iterator as either
923// 'iterator' or 'iterator::iterator').  If we look for C::iterator
924// only, for example, we would mistakenly think that a class named
925// iterator is an STL container.
926//
927// Also note that the simpler approach of overloading
928// IsContainerTest(typename C::const_iterator*) and
929// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
930typedef int IsContainer;
931template <class C>
932IsContainer IsContainerTest(int /* dummy */,
933                            typename C::iterator* /* it */ = NULL,
934                            typename C::const_iterator* /* const_it */ = NULL) {
935  return 0;
936}
937
938typedef char IsNotContainer;
939template <class C>
940IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
941
942// EnableIf<condition>::type is void when 'Cond' is true, and
943// undefined when 'Cond' is false.  To use SFINAE to make a function
944// overload only apply when a particular expression is true, add
945// "typename EnableIf<expression>::type* = 0" as the last parameter.
946template<bool> struct EnableIf;
947template<> struct EnableIf<true> { typedef void type; };  // NOLINT
948
949// Utilities for native arrays.
950
951// ArrayEq() compares two k-dimensional native arrays using the
952// elements' operator==, where k can be any integer >= 0.  When k is
953// 0, ArrayEq() degenerates into comparing a single pair of values.
954
955template <typename T, typename U>
956bool ArrayEq(const T* lhs, size_t size, const U* rhs);
957
958// This generic version is used when k is 0.
959template <typename T, typename U>
960inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
961
962// This overload is used when k >= 1.
963template <typename T, typename U, size_t N>
964inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
965  return internal::ArrayEq(lhs, N, rhs);
966}
967
968// This helper reduces code bloat.  If we instead put its logic inside
969// the previous ArrayEq() function, arrays with different sizes would
970// lead to different copies of the template code.
971template <typename T, typename U>
972bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
973  for (size_t i = 0; i != size; i++) {
974    if (!internal::ArrayEq(lhs[i], rhs[i]))
975      return false;
976  }
977  return true;
978}
979
980// Finds the first element in the iterator range [begin, end) that
981// equals elem.  Element may be a native array type itself.
982template <typename Iter, typename Element>
983Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
984  for (Iter it = begin; it != end; ++it) {
985    if (internal::ArrayEq(*it, elem))
986      return it;
987  }
988  return end;
989}
990
991// CopyArray() copies a k-dimensional native array using the elements'
992// operator=, where k can be any integer >= 0.  When k is 0,
993// CopyArray() degenerates into copying a single value.
994
995template <typename T, typename U>
996void CopyArray(const T* from, size_t size, U* to);
997
998// This generic version is used when k is 0.
999template <typename T, typename U>
1000inline void CopyArray(const T& from, U* to) { *to = from; }
1001
1002// This overload is used when k >= 1.
1003template <typename T, typename U, size_t N>
1004inline void CopyArray(const T(&from)[N], U(*to)[N]) {
1005  internal::CopyArray(from, N, *to);
1006}
1007
1008// This helper reduces code bloat.  If we instead put its logic inside
1009// the previous CopyArray() function, arrays with different sizes
1010// would lead to different copies of the template code.
1011template <typename T, typename U>
1012void CopyArray(const T* from, size_t size, U* to) {
1013  for (size_t i = 0; i != size; i++) {
1014    internal::CopyArray(from[i], to + i);
1015  }
1016}
1017
1018// The relation between an NativeArray object (see below) and the
1019// native array it represents.
1020// We use 2 different structs to allow non-copyable types to be used, as long
1021// as RelationToSourceReference() is passed.
1022struct RelationToSourceReference {};
1023struct RelationToSourceCopy {};
1024
1025// Adapts a native array to a read-only STL-style container.  Instead
1026// of the complete STL container concept, this adaptor only implements
1027// members useful for Google Mock's container matchers.  New members
1028// should be added as needed.  To simplify the implementation, we only
1029// support Element being a raw type (i.e. having no top-level const or
1030// reference modifier).  It's the client's responsibility to satisfy
1031// this requirement.  Element can be an array type itself (hence
1032// multi-dimensional arrays are supported).
1033template <typename Element>
1034class NativeArray {
1035 public:
1036  // STL-style container typedefs.
1037  typedef Element value_type;
1038  typedef Element* iterator;
1039  typedef const Element* const_iterator;
1040
1041  // Constructs from a native array. References the source.
1042  NativeArray(const Element* array, size_t count, RelationToSourceReference) {
1043    InitRef(array, count);
1044  }
1045
1046  // Constructs from a native array. Copies the source.
1047  NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
1048    InitCopy(array, count);
1049  }
1050
1051  // Copy constructor.
1052  NativeArray(const NativeArray& rhs) {
1053    (this->*rhs.clone_)(rhs.array_, rhs.size_);
1054  }
1055
1056  ~NativeArray() {
1057    if (clone_ != &NativeArray::InitRef)
1058      delete[] array_;
1059  }
1060
1061  // STL-style container methods.
1062  size_t size() const { return size_; }
1063  const_iterator begin() const { return array_; }
1064  const_iterator end() const { return array_ + size_; }
1065  bool operator==(const NativeArray& rhs) const {
1066    return size() == rhs.size() &&
1067        ArrayEq(begin(), size(), rhs.begin());
1068  }
1069
1070 private:
1071  enum {
1072    kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper<
1073        Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value,
1074  };
1075
1076  // Initializes this object with a copy of the input.
1077  void InitCopy(const Element* array, size_t a_size) {
1078    Element* const copy = new Element[a_size];
1079    CopyArray(array, a_size, copy);
1080    array_ = copy;
1081    size_ = a_size;
1082    clone_ = &NativeArray::InitCopy;
1083  }
1084
1085  // Initializes this object with a reference of the input.
1086  void InitRef(const Element* array, size_t a_size) {
1087    array_ = array;
1088    size_ = a_size;
1089    clone_ = &NativeArray::InitRef;
1090  }
1091
1092  const Element* array_;
1093  size_t size_;
1094  void (NativeArray::*clone_)(const Element*, size_t);
1095
1096  GTEST_DISALLOW_ASSIGN_(NativeArray);
1097};
1098
1099}  // namespace internal
1100}  // namespace testing
1101
1102#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1103  ::testing::internal::AssertHelper(result_type, file, line, message) \
1104    = ::testing::Message()
1105
1106#define GTEST_MESSAGE_(message, result_type) \
1107  GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1108
1109#define GTEST_FATAL_FAILURE_(message) \
1110  return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1111
1112#define GTEST_NONFATAL_FAILURE_(message) \
1113  GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1114
1115#define GTEST_SUCCESS_(message) \
1116  GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1117
1118// Suppresses MSVC warnings 4072 (unreachable code) for the code following
1119// statement if it returns or throws (or doesn't return or throw in some
1120// situations).
1121#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1122  if (::testing::internal::AlwaysTrue()) { statement; }
1123
1124#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1125  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1126  if (::testing::internal::ConstCharPtr gtest_msg = "") { \
1127    bool gtest_caught_expected = false; \
1128    try { \
1129      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1130    } \
1131    catch (expected_exception const&) { \
1132      gtest_caught_expected = true; \
1133    } \
1134    catch (...) { \
1135      gtest_msg.value = \
1136          "Expected: " #statement " throws an exception of type " \
1137          #expected_exception ".\n  Actual: it throws a different type."; \
1138      goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1139    } \
1140    if (!gtest_caught_expected) { \
1141      gtest_msg.value = \
1142          "Expected: " #statement " throws an exception of type " \
1143          #expected_exception ".\n  Actual: it throws nothing."; \
1144      goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1145    } \
1146  } else \
1147    GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
1148      fail(gtest_msg.value)
1149
1150#define GTEST_TEST_NO_THROW_(statement, fail) \
1151  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1152  if (::testing::internal::AlwaysTrue()) { \
1153    try { \
1154      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1155    } \
1156    catch (...) { \
1157      goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1158    } \
1159  } else \
1160    GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
1161      fail("Expected: " #statement " doesn't throw an exception.\n" \
1162           "  Actual: it throws.")
1163
1164#define GTEST_TEST_ANY_THROW_(statement, fail) \
1165  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1166  if (::testing::internal::AlwaysTrue()) { \
1167    bool gtest_caught_any = false; \
1168    try { \
1169      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1170    } \
1171    catch (...) { \
1172      gtest_caught_any = true; \
1173    } \
1174    if (!gtest_caught_any) { \
1175      goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1176    } \
1177  } else \
1178    GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1179      fail("Expected: " #statement " throws an exception.\n" \
1180           "  Actual: it doesn't.")
1181
1182
1183// Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1184// either a boolean expression or an AssertionResult. text is a textual
1185// represenation of expression as it was passed into the EXPECT_TRUE.
1186#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1187  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1188  if (const ::testing::AssertionResult gtest_ar_ = \
1189      ::testing::AssertionResult(expression)) \
1190    ; \
1191  else \
1192    fail(::testing::internal::GetBoolAssertionFailureMessage(\
1193        gtest_ar_, text, #actual, #expected).c_str())
1194
1195#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1196  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1197  if (::testing::internal::AlwaysTrue()) { \
1198    ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1199    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1200    if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1201      goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1202    } \
1203  } else \
1204    GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1205      fail("Expected: " #statement " doesn't generate new fatal " \
1206           "failures in the current thread.\n" \
1207           "  Actual: it does.")
1208
1209// Expands to the name of the class that implements the given test.
1210#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
1211  test_case_name##_##test_name##_Test
1212
1213// Helper macro for defining tests.
1214#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
1215class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
1216 public:\
1217  GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
1218 private:\
1219  virtual void TestBody();\
1220  static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
1221  GTEST_DISALLOW_COPY_AND_ASSIGN_(\
1222      GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
1223};\
1224\
1225::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
1226  ::test_info_ =\
1227    ::testing::internal::MakeAndRegisterTestInfo(\
1228        #test_case_name, #test_name, NULL, NULL, \
1229        ::testing::internal::CodeLocation(__FILE__, __LINE__), \
1230        (parent_id), \
1231        parent_class::SetUpTestCase, \
1232        parent_class::TearDownTestCase, \
1233        new ::testing::internal::TestFactoryImpl<\
1234            GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
1235void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
1236
1237#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
1238
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-linked_ptr.h
r0r249096
1// Copyright 2003 Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: Dan Egnor (egnor@google.com)
31//
32// A "smart" pointer type with reference tracking.  Every pointer to a
33// particular object is kept on a circular linked list.  When the last pointer
34// to an object is destroyed or reassigned, the object is deleted.
35//
36// Used properly, this deletes the object when the last reference goes away.
37// There are several caveats:
38// - Like all reference counting schemes, cycles lead to leaks.
39// - Each smart pointer is actually two pointers (8 bytes instead of 4).
40// - Every time a pointer is assigned, the entire list of pointers to that
41//   object is traversed.  This class is therefore NOT SUITABLE when there
42//   will often be more than two or three pointers to a particular object.
43// - References are only tracked as long as linked_ptr<> objects are copied.
44//   If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS
45//   will happen (double deletion).
46//
47// A good use of this class is storing object references in STL containers.
48// You can safely put linked_ptr<> in a vector<>.
49// Other uses may not be as good.
50//
51// Note: If you use an incomplete type with linked_ptr<>, the class
52// *containing* linked_ptr<> must have a constructor and destructor (even
53// if they do nothing!).
54//
55// Bill Gibbons suggested we use something like this.
56//
57// Thread Safety:
58//   Unlike other linked_ptr implementations, in this implementation
59//   a linked_ptr object is thread-safe in the sense that:
60//     - it's safe to copy linked_ptr objects concurrently,
61//     - it's safe to copy *from* a linked_ptr and read its underlying
62//       raw pointer (e.g. via get()) concurrently, and
63//     - it's safe to write to two linked_ptrs that point to the same
64//       shared object concurrently.
65// TODO(wan@google.com): rename this to safe_linked_ptr to avoid
66// confusion with normal linked_ptr.
67
68#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
69#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
70
71#include <stdlib.h>
72#include <assert.h>
73
74#include "gtest/internal/gtest-port.h"
75
76namespace testing {
77namespace internal {
78
79// Protects copying of all linked_ptr objects.
80GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex);
81
82// This is used internally by all instances of linked_ptr<>.  It needs to be
83// a non-template class because different types of linked_ptr<> can refer to
84// the same object (linked_ptr<Superclass>(obj) vs linked_ptr<Subclass>(obj)).
85// So, it needs to be possible for different types of linked_ptr to participate
86// in the same circular linked list, so we need a single class type here.
87//
88// DO NOT USE THIS CLASS DIRECTLY YOURSELF.  Use linked_ptr<T>.
89class linked_ptr_internal {
90 public:
91  // Create a new circle that includes only this instance.
92  void join_new() {
93    next_ = this;
94  }
95
96  // Many linked_ptr operations may change p.link_ for some linked_ptr
97  // variable p in the same circle as this object.  Therefore we need
98  // to prevent two such operations from occurring concurrently.
99  //
100  // Note that different types of linked_ptr objects can coexist in a
101  // circle (e.g. linked_ptr<Base>, linked_ptr<Derived1>, and
102  // linked_ptr<Derived2>).  Therefore we must use a single mutex to
103  // protect all linked_ptr objects.  This can create serious
104  // contention in production code, but is acceptable in a testing
105  // framework.
106
107  // Join an existing circle.
108  void join(linked_ptr_internal const* ptr)
109      GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) {
110    MutexLock lock(&g_linked_ptr_mutex);
111
112    linked_ptr_internal const* p = ptr;
113    while (p->next_ != ptr) {
114      assert(p->next_ != this &&
115             "Trying to join() a linked ring we are already in. "
116             "Is GMock thread safety enabled?");
117      p = p->next_;
118    }
119    p->next_ = this;
120    next_ = ptr;
121  }
122
123  // Leave whatever circle we're part of.  Returns true if we were the
124  // last member of the circle.  Once this is done, you can join() another.
125  bool depart()
126      GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) {
127    MutexLock lock(&g_linked_ptr_mutex);
128
129    if (next_ == this) return true;
130    linked_ptr_internal const* p = next_;
131    while (p->next_ != this) {
132      assert(p->next_ != next_ &&
133             "Trying to depart() a linked ring we are not in. "
134             "Is GMock thread safety enabled?");
135      p = p->next_;
136    }
137    p->next_ = next_;
138    return false;
139  }
140
141 private:
142  mutable linked_ptr_internal const* next_;
143};
144
145template <typename T>
146class linked_ptr {
147 public:
148  typedef T element_type;
149
150  // Take over ownership of a raw pointer.  This should happen as soon as
151  // possible after the object is created.
152  explicit linked_ptr(T* ptr = NULL) { capture(ptr); }
153  ~linked_ptr() { depart(); }
154
155  // Copy an existing linked_ptr<>, adding ourselves to the list of references.
156  template <typename U> linked_ptr(linked_ptr<U> const& ptr) { copy(&ptr); }
157  linked_ptr(linked_ptr const& ptr) {  // NOLINT
158    assert(&ptr != this);
159    copy(&ptr);
160  }
161
162  // Assignment releases the old value and acquires the new.
163  template <typename U> linked_ptr& operator=(linked_ptr<U> const& ptr) {
164    depart();
165    copy(&ptr);
166    return *this;
167  }
168
169  linked_ptr& operator=(linked_ptr const& ptr) {
170    if (&ptr != this) {
171      depart();
172      copy(&ptr);
173    }
174    return *this;
175  }
176
177  // Smart pointer members.
178  void reset(T* ptr = NULL) {
179    depart();
180    capture(ptr);
181  }
182  T* get() const { return value_; }
183  T* operator->() const { return value_; }
184  T& operator*() const { return *value_; }
185
186  bool operator==(T* p) const { return value_ == p; }
187  bool operator!=(T* p) const { return value_ != p; }
188  template <typename U>
189  bool operator==(linked_ptr<U> const& ptr) const {
190    return value_ == ptr.get();
191  }
192  template <typename U>
193  bool operator!=(linked_ptr<U> const& ptr) const {
194    return value_ != ptr.get();
195  }
196
197 private:
198  template <typename U>
199  friend class linked_ptr;
200
201  T* value_;
202  linked_ptr_internal link_;
203
204  void depart() {
205    if (link_.depart()) delete value_;
206  }
207
208  void capture(T* ptr) {
209    value_ = ptr;
210    link_.join_new();
211  }
212
213  template <typename U> void copy(linked_ptr<U> const* ptr) {
214    value_ = ptr->get();
215    if (value_)
216      link_.join(&ptr->link_);
217    else
218      link_.join_new();
219  }
220};
221
222template<typename T> inline
223bool operator==(T* ptr, const linked_ptr<T>& x) {
224  return ptr == x.get();
225}
226
227template<typename T> inline
228bool operator!=(T* ptr, const linked_ptr<T>& x) {
229  return ptr != x.get();
230}
231
232// A function to convert T* into linked_ptr<T>
233// Doing e.g. make_linked_ptr(new FooBarBaz<type>(arg)) is a shorter notation
234// for linked_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
235template <typename T>
236linked_ptr<T> make_linked_ptr(T* ptr) {
237  return linked_ptr<T>(ptr);
238}
239
240}  // namespace internal
241}  // namespace testing
242
243#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-param-util-generated.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gtest-param-util-generated.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2008 Google Inc.
6// All Rights Reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33//
34// Author: vladl@google.com (Vlad Losev)
35
36// Type and function utilities for implementing parameterized tests.
37// This file is generated by a SCRIPT.  DO NOT EDIT BY HAND!
38//
39// Currently Google Test supports at most 50 arguments in Values,
40// and at most 10 arguments in Combine. Please contact
41// googletestframework@googlegroups.com if you need more.
42// Please note that the number of arguments to Combine is limited
43// by the maximum arity of the implementation of tuple which is
44// currently set at 10.
45
46#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
47#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
48
49// scripts/fuse_gtest.py depends on gtest's own header being #included
50// *unconditionally*.  Therefore these #includes cannot be moved
51// inside #if GTEST_HAS_PARAM_TEST.
52#include "gtest/internal/gtest-param-util.h"
53#include "gtest/internal/gtest-port.h"
54
55#if GTEST_HAS_PARAM_TEST
56
57namespace testing {
58
59// Forward declarations of ValuesIn(), which is implemented in
60// include/gtest/gtest-param-test.h.
61template <typename ForwardIterator>
62internal::ParamGenerator<
63  typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type>
64ValuesIn(ForwardIterator begin, ForwardIterator end);
65
66template <typename T, size_t N>
67internal::ParamGenerator<T> ValuesIn(const T (&array)[N]);
68
69template <class Container>
70internal::ParamGenerator<typename Container::value_type> ValuesIn(
71    const Container& container);
72
73namespace internal {
74
75// Used in the Values() function to provide polymorphic capabilities.
76template <typename T1>
77class ValueArray1 {
78 public:
79  explicit ValueArray1(T1 v1) : v1_(v1) {}
80
81  template <typename T>
82  operator ParamGenerator<T>() const {
83    const T array[] = {static_cast<T>(v1_)};
84    return ValuesIn(array);
85  }
86
87 private:
88  // No implementation - assignment is unsupported.
89  void operator=(const ValueArray1& other);
90
91  const T1 v1_;
92};
93
94template <typename T1, typename T2>
95class ValueArray2 {
96 public:
97  ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {}
98
99  template <typename T>
100  operator ParamGenerator<T>() const {
101    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_)};
102    return ValuesIn(array);
103  }
104
105 private:
106  // No implementation - assignment is unsupported.
107  void operator=(const ValueArray2& other);
108
109  const T1 v1_;
110  const T2 v2_;
111};
112
113template <typename T1, typename T2, typename T3>
114class ValueArray3 {
115 public:
116  ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {}
117
118  template <typename T>
119  operator ParamGenerator<T>() const {
120    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
121        static_cast<T>(v3_)};
122    return ValuesIn(array);
123  }
124
125 private:
126  // No implementation - assignment is unsupported.
127  void operator=(const ValueArray3& other);
128
129  const T1 v1_;
130  const T2 v2_;
131  const T3 v3_;
132};
133
134template <typename T1, typename T2, typename T3, typename T4>
135class ValueArray4 {
136 public:
137  ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3),
138      v4_(v4) {}
139
140  template <typename T>
141  operator ParamGenerator<T>() const {
142    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
143        static_cast<T>(v3_), static_cast<T>(v4_)};
144    return ValuesIn(array);
145  }
146
147 private:
148  // No implementation - assignment is unsupported.
149  void operator=(const ValueArray4& other);
150
151  const T1 v1_;
152  const T2 v2_;
153  const T3 v3_;
154  const T4 v4_;
155};
156
157template <typename T1, typename T2, typename T3, typename T4, typename T5>
158class ValueArray5 {
159 public:
160  ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3),
161      v4_(v4), v5_(v5) {}
162
163  template <typename T>
164  operator ParamGenerator<T>() const {
165    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
166        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_)};
167    return ValuesIn(array);
168  }
169
170 private:
171  // No implementation - assignment is unsupported.
172  void operator=(const ValueArray5& other);
173
174  const T1 v1_;
175  const T2 v2_;
176  const T3 v3_;
177  const T4 v4_;
178  const T5 v5_;
179};
180
181template <typename T1, typename T2, typename T3, typename T4, typename T5,
182    typename T6>
183class ValueArray6 {
184 public:
185  ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2),
186      v3_(v3), v4_(v4), v5_(v5), v6_(v6) {}
187
188  template <typename T>
189  operator ParamGenerator<T>() const {
190    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
191        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
192        static_cast<T>(v6_)};
193    return ValuesIn(array);
194  }
195
196 private:
197  // No implementation - assignment is unsupported.
198  void operator=(const ValueArray6& other);
199
200  const T1 v1_;
201  const T2 v2_;
202  const T3 v3_;
203  const T4 v4_;
204  const T5 v5_;
205  const T6 v6_;
206};
207
208template <typename T1, typename T2, typename T3, typename T4, typename T5,
209    typename T6, typename T7>
210class ValueArray7 {
211 public:
212  ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1),
213      v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {}
214
215  template <typename T>
216  operator ParamGenerator<T>() const {
217    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
218        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
219        static_cast<T>(v6_), static_cast<T>(v7_)};
220    return ValuesIn(array);
221  }
222
223 private:
224  // No implementation - assignment is unsupported.
225  void operator=(const ValueArray7& other);
226
227  const T1 v1_;
228  const T2 v2_;
229  const T3 v3_;
230  const T4 v4_;
231  const T5 v5_;
232  const T6 v6_;
233  const T7 v7_;
234};
235
236template <typename T1, typename T2, typename T3, typename T4, typename T5,
237    typename T6, typename T7, typename T8>
238class ValueArray8 {
239 public:
240  ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7,
241      T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
242      v8_(v8) {}
243
244  template <typename T>
245  operator ParamGenerator<T>() const {
246    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
247        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
248        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_)};
249    return ValuesIn(array);
250  }
251
252 private:
253  // No implementation - assignment is unsupported.
254  void operator=(const ValueArray8& other);
255
256  const T1 v1_;
257  const T2 v2_;
258  const T3 v3_;
259  const T4 v4_;
260  const T5 v5_;
261  const T6 v6_;
262  const T7 v7_;
263  const T8 v8_;
264};
265
266template <typename T1, typename T2, typename T3, typename T4, typename T5,
267    typename T6, typename T7, typename T8, typename T9>
268class ValueArray9 {
269 public:
270  ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8,
271      T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
272      v8_(v8), v9_(v9) {}
273
274  template <typename T>
275  operator ParamGenerator<T>() const {
276    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
277        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
278        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
279        static_cast<T>(v9_)};
280    return ValuesIn(array);
281  }
282
283 private:
284  // No implementation - assignment is unsupported.
285  void operator=(const ValueArray9& other);
286
287  const T1 v1_;
288  const T2 v2_;
289  const T3 v3_;
290  const T4 v4_;
291  const T5 v5_;
292  const T6 v6_;
293  const T7 v7_;
294  const T8 v8_;
295  const T9 v9_;
296};
297
298template <typename T1, typename T2, typename T3, typename T4, typename T5,
299    typename T6, typename T7, typename T8, typename T9, typename T10>
300class ValueArray10 {
301 public:
302  ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
303      T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
304      v8_(v8), v9_(v9), v10_(v10) {}
305
306  template <typename T>
307  operator ParamGenerator<T>() const {
308    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
309        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
310        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
311        static_cast<T>(v9_), static_cast<T>(v10_)};
312    return ValuesIn(array);
313  }
314
315 private:
316  // No implementation - assignment is unsupported.
317  void operator=(const ValueArray10& other);
318
319  const T1 v1_;
320  const T2 v2_;
321  const T3 v3_;
322  const T4 v4_;
323  const T5 v5_;
324  const T6 v6_;
325  const T7 v7_;
326  const T8 v8_;
327  const T9 v9_;
328  const T10 v10_;
329};
330
331template <typename T1, typename T2, typename T3, typename T4, typename T5,
332    typename T6, typename T7, typename T8, typename T9, typename T10,
333    typename T11>
334class ValueArray11 {
335 public:
336  ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
337      T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6),
338      v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {}
339
340  template <typename T>
341  operator ParamGenerator<T>() const {
342    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
343        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
344        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
345        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_)};
346    return ValuesIn(array);
347  }
348
349 private:
350  // No implementation - assignment is unsupported.
351  void operator=(const ValueArray11& other);
352
353  const T1 v1_;
354  const T2 v2_;
355  const T3 v3_;
356  const T4 v4_;
357  const T5 v5_;
358  const T6 v6_;
359  const T7 v7_;
360  const T8 v8_;
361  const T9 v9_;
362  const T10 v10_;
363  const T11 v11_;
364};
365
366template <typename T1, typename T2, typename T3, typename T4, typename T5,
367    typename T6, typename T7, typename T8, typename T9, typename T10,
368    typename T11, typename T12>
369class ValueArray12 {
370 public:
371  ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
372      T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5),
373      v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {}
374
375  template <typename T>
376  operator ParamGenerator<T>() const {
377    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
378        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
379        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
380        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
381        static_cast<T>(v12_)};
382    return ValuesIn(array);
383  }
384
385 private:
386  // No implementation - assignment is unsupported.
387  void operator=(const ValueArray12& other);
388
389  const T1 v1_;
390  const T2 v2_;
391  const T3 v3_;
392  const T4 v4_;
393  const T5 v5_;
394  const T6 v6_;
395  const T7 v7_;
396  const T8 v8_;
397  const T9 v9_;
398  const T10 v10_;
399  const T11 v11_;
400  const T12 v12_;
401};
402
403template <typename T1, typename T2, typename T3, typename T4, typename T5,
404    typename T6, typename T7, typename T8, typename T9, typename T10,
405    typename T11, typename T12, typename T13>
406class ValueArray13 {
407 public:
408  ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
409      T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4),
410      v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11),
411      v12_(v12), v13_(v13) {}
412
413  template <typename T>
414  operator ParamGenerator<T>() const {
415    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
416        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
417        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
418        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
419        static_cast<T>(v12_), static_cast<T>(v13_)};
420    return ValuesIn(array);
421  }
422
423 private:
424  // No implementation - assignment is unsupported.
425  void operator=(const ValueArray13& other);
426
427  const T1 v1_;
428  const T2 v2_;
429  const T3 v3_;
430  const T4 v4_;
431  const T5 v5_;
432  const T6 v6_;
433  const T7 v7_;
434  const T8 v8_;
435  const T9 v9_;
436  const T10 v10_;
437  const T11 v11_;
438  const T12 v12_;
439  const T13 v13_;
440};
441
442template <typename T1, typename T2, typename T3, typename T4, typename T5,
443    typename T6, typename T7, typename T8, typename T9, typename T10,
444    typename T11, typename T12, typename T13, typename T14>
445class ValueArray14 {
446 public:
447  ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
448      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3),
449      v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
450      v11_(v11), v12_(v12), v13_(v13), v14_(v14) {}
451
452  template <typename T>
453  operator ParamGenerator<T>() const {
454    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
455        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
456        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
457        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
458        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_)};
459    return ValuesIn(array);
460  }
461
462 private:
463  // No implementation - assignment is unsupported.
464  void operator=(const ValueArray14& other);
465
466  const T1 v1_;
467  const T2 v2_;
468  const T3 v3_;
469  const T4 v4_;
470  const T5 v5_;
471  const T6 v6_;
472  const T7 v7_;
473  const T8 v8_;
474  const T9 v9_;
475  const T10 v10_;
476  const T11 v11_;
477  const T12 v12_;
478  const T13 v13_;
479  const T14 v14_;
480};
481
482template <typename T1, typename T2, typename T3, typename T4, typename T5,
483    typename T6, typename T7, typename T8, typename T9, typename T10,
484    typename T11, typename T12, typename T13, typename T14, typename T15>
485class ValueArray15 {
486 public:
487  ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
488      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2),
489      v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
490      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {}
491
492  template <typename T>
493  operator ParamGenerator<T>() const {
494    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
495        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
496        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
497        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
498        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
499        static_cast<T>(v15_)};
500    return ValuesIn(array);
501  }
502
503 private:
504  // No implementation - assignment is unsupported.
505  void operator=(const ValueArray15& other);
506
507  const T1 v1_;
508  const T2 v2_;
509  const T3 v3_;
510  const T4 v4_;
511  const T5 v5_;
512  const T6 v6_;
513  const T7 v7_;
514  const T8 v8_;
515  const T9 v9_;
516  const T10 v10_;
517  const T11 v11_;
518  const T12 v12_;
519  const T13 v13_;
520  const T14 v14_;
521  const T15 v15_;
522};
523
524template <typename T1, typename T2, typename T3, typename T4, typename T5,
525    typename T6, typename T7, typename T8, typename T9, typename T10,
526    typename T11, typename T12, typename T13, typename T14, typename T15,
527    typename T16>
528class ValueArray16 {
529 public:
530  ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
531      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1),
532      v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9),
533      v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15),
534      v16_(v16) {}
535
536  template <typename T>
537  operator ParamGenerator<T>() const {
538    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
539        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
540        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
541        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
542        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
543        static_cast<T>(v15_), static_cast<T>(v16_)};
544    return ValuesIn(array);
545  }
546
547 private:
548  // No implementation - assignment is unsupported.
549  void operator=(const ValueArray16& other);
550
551  const T1 v1_;
552  const T2 v2_;
553  const T3 v3_;
554  const T4 v4_;
555  const T5 v5_;
556  const T6 v6_;
557  const T7 v7_;
558  const T8 v8_;
559  const T9 v9_;
560  const T10 v10_;
561  const T11 v11_;
562  const T12 v12_;
563  const T13 v13_;
564  const T14 v14_;
565  const T15 v15_;
566  const T16 v16_;
567};
568
569template <typename T1, typename T2, typename T3, typename T4, typename T5,
570    typename T6, typename T7, typename T8, typename T9, typename T10,
571    typename T11, typename T12, typename T13, typename T14, typename T15,
572    typename T16, typename T17>
573class ValueArray17 {
574 public:
575  ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
576      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16,
577      T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
578      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
579      v15_(v15), v16_(v16), v17_(v17) {}
580
581  template <typename T>
582  operator ParamGenerator<T>() const {
583    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
584        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
585        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
586        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
587        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
588        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_)};
589    return ValuesIn(array);
590  }
591
592 private:
593  // No implementation - assignment is unsupported.
594  void operator=(const ValueArray17& other);
595
596  const T1 v1_;
597  const T2 v2_;
598  const T3 v3_;
599  const T4 v4_;
600  const T5 v5_;
601  const T6 v6_;
602  const T7 v7_;
603  const T8 v8_;
604  const T9 v9_;
605  const T10 v10_;
606  const T11 v11_;
607  const T12 v12_;
608  const T13 v13_;
609  const T14 v14_;
610  const T15 v15_;
611  const T16 v16_;
612  const T17 v17_;
613};
614
615template <typename T1, typename T2, typename T3, typename T4, typename T5,
616    typename T6, typename T7, typename T8, typename T9, typename T10,
617    typename T11, typename T12, typename T13, typename T14, typename T15,
618    typename T16, typename T17, typename T18>
619class ValueArray18 {
620 public:
621  ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
622      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
623      T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
624      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
625      v15_(v15), v16_(v16), v17_(v17), v18_(v18) {}
626
627  template <typename T>
628  operator ParamGenerator<T>() const {
629    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
630        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
631        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
632        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
633        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
634        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
635        static_cast<T>(v18_)};
636    return ValuesIn(array);
637  }
638
639 private:
640  // No implementation - assignment is unsupported.
641  void operator=(const ValueArray18& other);
642
643  const T1 v1_;
644  const T2 v2_;
645  const T3 v3_;
646  const T4 v4_;
647  const T5 v5_;
648  const T6 v6_;
649  const T7 v7_;
650  const T8 v8_;
651  const T9 v9_;
652  const T10 v10_;
653  const T11 v11_;
654  const T12 v12_;
655  const T13 v13_;
656  const T14 v14_;
657  const T15 v15_;
658  const T16 v16_;
659  const T17 v17_;
660  const T18 v18_;
661};
662
663template <typename T1, typename T2, typename T3, typename T4, typename T5,
664    typename T6, typename T7, typename T8, typename T9, typename T10,
665    typename T11, typename T12, typename T13, typename T14, typename T15,
666    typename T16, typename T17, typename T18, typename T19>
667class ValueArray19 {
668 public:
669  ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
670      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
671      T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6),
672      v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13),
673      v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {}
674
675  template <typename T>
676  operator ParamGenerator<T>() const {
677    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
678        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
679        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
680        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
681        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
682        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
683        static_cast<T>(v18_), static_cast<T>(v19_)};
684    return ValuesIn(array);
685  }
686
687 private:
688  // No implementation - assignment is unsupported.
689  void operator=(const ValueArray19& other);
690
691  const T1 v1_;
692  const T2 v2_;
693  const T3 v3_;
694  const T4 v4_;
695  const T5 v5_;
696  const T6 v6_;
697  const T7 v7_;
698  const T8 v8_;
699  const T9 v9_;
700  const T10 v10_;
701  const T11 v11_;
702  const T12 v12_;
703  const T13 v13_;
704  const T14 v14_;
705  const T15 v15_;
706  const T16 v16_;
707  const T17 v17_;
708  const T18 v18_;
709  const T19 v19_;
710};
711
712template <typename T1, typename T2, typename T3, typename T4, typename T5,
713    typename T6, typename T7, typename T8, typename T9, typename T10,
714    typename T11, typename T12, typename T13, typename T14, typename T15,
715    typename T16, typename T17, typename T18, typename T19, typename T20>
716class ValueArray20 {
717 public:
718  ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
719      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
720      T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5),
721      v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12),
722      v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18),
723      v19_(v19), v20_(v20) {}
724
725  template <typename T>
726  operator ParamGenerator<T>() const {
727    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
728        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
729        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
730        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
731        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
732        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
733        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_)};
734    return ValuesIn(array);
735  }
736
737 private:
738  // No implementation - assignment is unsupported.
739  void operator=(const ValueArray20& other);
740
741  const T1 v1_;
742  const T2 v2_;
743  const T3 v3_;
744  const T4 v4_;
745  const T5 v5_;
746  const T6 v6_;
747  const T7 v7_;
748  const T8 v8_;
749  const T9 v9_;
750  const T10 v10_;
751  const T11 v11_;
752  const T12 v12_;
753  const T13 v13_;
754  const T14 v14_;
755  const T15 v15_;
756  const T16 v16_;
757  const T17 v17_;
758  const T18 v18_;
759  const T19 v19_;
760  const T20 v20_;
761};
762
763template <typename T1, typename T2, typename T3, typename T4, typename T5,
764    typename T6, typename T7, typename T8, typename T9, typename T10,
765    typename T11, typename T12, typename T13, typename T14, typename T15,
766    typename T16, typename T17, typename T18, typename T19, typename T20,
767    typename T21>
768class ValueArray21 {
769 public:
770  ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
771      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
772      T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4),
773      v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11),
774      v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17),
775      v18_(v18), v19_(v19), v20_(v20), v21_(v21) {}
776
777  template <typename T>
778  operator ParamGenerator<T>() const {
779    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
780        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
781        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
782        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
783        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
784        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
785        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
786        static_cast<T>(v21_)};
787    return ValuesIn(array);
788  }
789
790 private:
791  // No implementation - assignment is unsupported.
792  void operator=(const ValueArray21& other);
793
794  const T1 v1_;
795  const T2 v2_;
796  const T3 v3_;
797  const T4 v4_;
798  const T5 v5_;
799  const T6 v6_;
800  const T7 v7_;
801  const T8 v8_;
802  const T9 v9_;
803  const T10 v10_;
804  const T11 v11_;
805  const T12 v12_;
806  const T13 v13_;
807  const T14 v14_;
808  const T15 v15_;
809  const T16 v16_;
810  const T17 v17_;
811  const T18 v18_;
812  const T19 v19_;
813  const T20 v20_;
814  const T21 v21_;
815};
816
817template <typename T1, typename T2, typename T3, typename T4, typename T5,
818    typename T6, typename T7, typename T8, typename T9, typename T10,
819    typename T11, typename T12, typename T13, typename T14, typename T15,
820    typename T16, typename T17, typename T18, typename T19, typename T20,
821    typename T21, typename T22>
822class ValueArray22 {
823 public:
824  ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
825      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
826      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3),
827      v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
828      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
829      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {}
830
831  template <typename T>
832  operator ParamGenerator<T>() const {
833    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
834        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
835        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
836        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
837        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
838        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
839        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
840        static_cast<T>(v21_), static_cast<T>(v22_)};
841    return ValuesIn(array);
842  }
843
844 private:
845  // No implementation - assignment is unsupported.
846  void operator=(const ValueArray22& other);
847
848  const T1 v1_;
849  const T2 v2_;
850  const T3 v3_;
851  const T4 v4_;
852  const T5 v5_;
853  const T6 v6_;
854  const T7 v7_;
855  const T8 v8_;
856  const T9 v9_;
857  const T10 v10_;
858  const T11 v11_;
859  const T12 v12_;
860  const T13 v13_;
861  const T14 v14_;
862  const T15 v15_;
863  const T16 v16_;
864  const T17 v17_;
865  const T18 v18_;
866  const T19 v19_;
867  const T20 v20_;
868  const T21 v21_;
869  const T22 v22_;
870};
871
872template <typename T1, typename T2, typename T3, typename T4, typename T5,
873    typename T6, typename T7, typename T8, typename T9, typename T10,
874    typename T11, typename T12, typename T13, typename T14, typename T15,
875    typename T16, typename T17, typename T18, typename T19, typename T20,
876    typename T21, typename T22, typename T23>
877class ValueArray23 {
878 public:
879  ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
880      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
881      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2),
882      v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
883      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
884      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22),
885      v23_(v23) {}
886
887  template <typename T>
888  operator ParamGenerator<T>() const {
889    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
890        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
891        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
892        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
893        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
894        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
895        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
896        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_)};
897    return ValuesIn(array);
898  }
899
900 private:
901  // No implementation - assignment is unsupported.
902  void operator=(const ValueArray23& other);
903
904  const T1 v1_;
905  const T2 v2_;
906  const T3 v3_;
907  const T4 v4_;
908  const T5 v5_;
909  const T6 v6_;
910  const T7 v7_;
911  const T8 v8_;
912  const T9 v9_;
913  const T10 v10_;
914  const T11 v11_;
915  const T12 v12_;
916  const T13 v13_;
917  const T14 v14_;
918  const T15 v15_;
919  const T16 v16_;
920  const T17 v17_;
921  const T18 v18_;
922  const T19 v19_;
923  const T20 v20_;
924  const T21 v21_;
925  const T22 v22_;
926  const T23 v23_;
927};
928
929template <typename T1, typename T2, typename T3, typename T4, typename T5,
930    typename T6, typename T7, typename T8, typename T9, typename T10,
931    typename T11, typename T12, typename T13, typename T14, typename T15,
932    typename T16, typename T17, typename T18, typename T19, typename T20,
933    typename T21, typename T22, typename T23, typename T24>
934class ValueArray24 {
935 public:
936  ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
937      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
938      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1),
939      v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9),
940      v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15),
941      v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21),
942      v22_(v22), v23_(v23), v24_(v24) {}
943
944  template <typename T>
945  operator ParamGenerator<T>() const {
946    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
947        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
948        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
949        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
950        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
951        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
952        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
953        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
954        static_cast<T>(v24_)};
955    return ValuesIn(array);
956  }
957
958 private:
959  // No implementation - assignment is unsupported.
960  void operator=(const ValueArray24& other);
961
962  const T1 v1_;
963  const T2 v2_;
964  const T3 v3_;
965  const T4 v4_;
966  const T5 v5_;
967  const T6 v6_;
968  const T7 v7_;
969  const T8 v8_;
970  const T9 v9_;
971  const T10 v10_;
972  const T11 v11_;
973  const T12 v12_;
974  const T13 v13_;
975  const T14 v14_;
976  const T15 v15_;
977  const T16 v16_;
978  const T17 v17_;
979  const T18 v18_;
980  const T19 v19_;
981  const T20 v20_;
982  const T21 v21_;
983  const T22 v22_;
984  const T23 v23_;
985  const T24 v24_;
986};
987
988template <typename T1, typename T2, typename T3, typename T4, typename T5,
989    typename T6, typename T7, typename T8, typename T9, typename T10,
990    typename T11, typename T12, typename T13, typename T14, typename T15,
991    typename T16, typename T17, typename T18, typename T19, typename T20,
992    typename T21, typename T22, typename T23, typename T24, typename T25>
993class ValueArray25 {
994 public:
995  ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
996      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
997      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24,
998      T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
999      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
1000      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
1001      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {}
1002
1003  template <typename T>
1004  operator ParamGenerator<T>() const {
1005    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1006        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1007        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1008        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1009        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1010        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1011        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1012        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1013        static_cast<T>(v24_), static_cast<T>(v25_)};
1014    return ValuesIn(array);
1015  }
1016
1017 private:
1018  // No implementation - assignment is unsupported.
1019  void operator=(const ValueArray25& other);
1020
1021  const T1 v1_;
1022  const T2 v2_;
1023  const T3 v3_;
1024  const T4 v4_;
1025  const T5 v5_;
1026  const T6 v6_;
1027  const T7 v7_;
1028  const T8 v8_;
1029  const T9 v9_;
1030  const T10 v10_;
1031  const T11 v11_;
1032  const T12 v12_;
1033  const T13 v13_;
1034  const T14 v14_;
1035  const T15 v15_;
1036  const T16 v16_;
1037  const T17 v17_;
1038  const T18 v18_;
1039  const T19 v19_;
1040  const T20 v20_;
1041  const T21 v21_;
1042  const T22 v22_;
1043  const T23 v23_;
1044  const T24 v24_;
1045  const T25 v25_;
1046};
1047
1048template <typename T1, typename T2, typename T3, typename T4, typename T5,
1049    typename T6, typename T7, typename T8, typename T9, typename T10,
1050    typename T11, typename T12, typename T13, typename T14, typename T15,
1051    typename T16, typename T17, typename T18, typename T19, typename T20,
1052    typename T21, typename T22, typename T23, typename T24, typename T25,
1053    typename T26>
1054class ValueArray26 {
1055 public:
1056  ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1057      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1058      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1059      T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
1060      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
1061      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
1062      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {}
1063
1064  template <typename T>
1065  operator ParamGenerator<T>() const {
1066    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1067        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1068        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1069        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1070        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1071        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1072        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1073        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1074        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_)};
1075    return ValuesIn(array);
1076  }
1077
1078 private:
1079  // No implementation - assignment is unsupported.
1080  void operator=(const ValueArray26& other);
1081
1082  const T1 v1_;
1083  const T2 v2_;
1084  const T3 v3_;
1085  const T4 v4_;
1086  const T5 v5_;
1087  const T6 v6_;
1088  const T7 v7_;
1089  const T8 v8_;
1090  const T9 v9_;
1091  const T10 v10_;
1092  const T11 v11_;
1093  const T12 v12_;
1094  const T13 v13_;
1095  const T14 v14_;
1096  const T15 v15_;
1097  const T16 v16_;
1098  const T17 v17_;
1099  const T18 v18_;
1100  const T19 v19_;
1101  const T20 v20_;
1102  const T21 v21_;
1103  const T22 v22_;
1104  const T23 v23_;
1105  const T24 v24_;
1106  const T25 v25_;
1107  const T26 v26_;
1108};
1109
1110template <typename T1, typename T2, typename T3, typename T4, typename T5,
1111    typename T6, typename T7, typename T8, typename T9, typename T10,
1112    typename T11, typename T12, typename T13, typename T14, typename T15,
1113    typename T16, typename T17, typename T18, typename T19, typename T20,
1114    typename T21, typename T22, typename T23, typename T24, typename T25,
1115    typename T26, typename T27>
1116class ValueArray27 {
1117 public:
1118  ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1119      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1120      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1121      T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6),
1122      v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13),
1123      v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19),
1124      v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25),
1125      v26_(v26), v27_(v27) {}
1126
1127  template <typename T>
1128  operator ParamGenerator<T>() const {
1129    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1130        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1131        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1132        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1133        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1134        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1135        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1136        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1137        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1138        static_cast<T>(v27_)};
1139    return ValuesIn(array);
1140  }
1141
1142 private:
1143  // No implementation - assignment is unsupported.
1144  void operator=(const ValueArray27& other);
1145
1146  const T1 v1_;
1147  const T2 v2_;
1148  const T3 v3_;
1149  const T4 v4_;
1150  const T5 v5_;
1151  const T6 v6_;
1152  const T7 v7_;
1153  const T8 v8_;
1154  const T9 v9_;
1155  const T10 v10_;
1156  const T11 v11_;
1157  const T12 v12_;
1158  const T13 v13_;
1159  const T14 v14_;
1160  const T15 v15_;
1161  const T16 v16_;
1162  const T17 v17_;
1163  const T18 v18_;
1164  const T19 v19_;
1165  const T20 v20_;
1166  const T21 v21_;
1167  const T22 v22_;
1168  const T23 v23_;
1169  const T24 v24_;
1170  const T25 v25_;
1171  const T26 v26_;
1172  const T27 v27_;
1173};
1174
1175template <typename T1, typename T2, typename T3, typename T4, typename T5,
1176    typename T6, typename T7, typename T8, typename T9, typename T10,
1177    typename T11, typename T12, typename T13, typename T14, typename T15,
1178    typename T16, typename T17, typename T18, typename T19, typename T20,
1179    typename T21, typename T22, typename T23, typename T24, typename T25,
1180    typename T26, typename T27, typename T28>
1181class ValueArray28 {
1182 public:
1183  ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1184      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1185      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1186      T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5),
1187      v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12),
1188      v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18),
1189      v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24),
1190      v25_(v25), v26_(v26), v27_(v27), v28_(v28) {}
1191
1192  template <typename T>
1193  operator ParamGenerator<T>() const {
1194    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1195        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1196        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1197        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1198        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1199        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1200        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1201        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1202        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1203        static_cast<T>(v27_), static_cast<T>(v28_)};
1204    return ValuesIn(array);
1205  }
1206
1207 private:
1208  // No implementation - assignment is unsupported.
1209  void operator=(const ValueArray28& other);
1210
1211  const T1 v1_;
1212  const T2 v2_;
1213  const T3 v3_;
1214  const T4 v4_;
1215  const T5 v5_;
1216  const T6 v6_;
1217  const T7 v7_;
1218  const T8 v8_;
1219  const T9 v9_;
1220  const T10 v10_;
1221  const T11 v11_;
1222  const T12 v12_;
1223  const T13 v13_;
1224  const T14 v14_;
1225  const T15 v15_;
1226  const T16 v16_;
1227  const T17 v17_;
1228  const T18 v18_;
1229  const T19 v19_;
1230  const T20 v20_;
1231  const T21 v21_;
1232  const T22 v22_;
1233  const T23 v23_;
1234  const T24 v24_;
1235  const T25 v25_;
1236  const T26 v26_;
1237  const T27 v27_;
1238  const T28 v28_;
1239};
1240
1241template <typename T1, typename T2, typename T3, typename T4, typename T5,
1242    typename T6, typename T7, typename T8, typename T9, typename T10,
1243    typename T11, typename T12, typename T13, typename T14, typename T15,
1244    typename T16, typename T17, typename T18, typename T19, typename T20,
1245    typename T21, typename T22, typename T23, typename T24, typename T25,
1246    typename T26, typename T27, typename T28, typename T29>
1247class ValueArray29 {
1248 public:
1249  ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1250      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1251      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1252      T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4),
1253      v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11),
1254      v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17),
1255      v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23),
1256      v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {}
1257
1258  template <typename T>
1259  operator ParamGenerator<T>() const {
1260    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1261        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1262        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1263        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1264        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1265        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1266        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1267        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1268        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1269        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_)};
1270    return ValuesIn(array);
1271  }
1272
1273 private:
1274  // No implementation - assignment is unsupported.
1275  void operator=(const ValueArray29& other);
1276
1277  const T1 v1_;
1278  const T2 v2_;
1279  const T3 v3_;
1280  const T4 v4_;
1281  const T5 v5_;
1282  const T6 v6_;
1283  const T7 v7_;
1284  const T8 v8_;
1285  const T9 v9_;
1286  const T10 v10_;
1287  const T11 v11_;
1288  const T12 v12_;
1289  const T13 v13_;
1290  const T14 v14_;
1291  const T15 v15_;
1292  const T16 v16_;
1293  const T17 v17_;
1294  const T18 v18_;
1295  const T19 v19_;
1296  const T20 v20_;
1297  const T21 v21_;
1298  const T22 v22_;
1299  const T23 v23_;
1300  const T24 v24_;
1301  const T25 v25_;
1302  const T26 v26_;
1303  const T27 v27_;
1304  const T28 v28_;
1305  const T29 v29_;
1306};
1307
1308template <typename T1, typename T2, typename T3, typename T4, typename T5,
1309    typename T6, typename T7, typename T8, typename T9, typename T10,
1310    typename T11, typename T12, typename T13, typename T14, typename T15,
1311    typename T16, typename T17, typename T18, typename T19, typename T20,
1312    typename T21, typename T22, typename T23, typename T24, typename T25,
1313    typename T26, typename T27, typename T28, typename T29, typename T30>
1314class ValueArray30 {
1315 public:
1316  ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1317      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1318      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1319      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3),
1320      v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
1321      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
1322      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22),
1323      v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28),
1324      v29_(v29), v30_(v30) {}
1325
1326  template <typename T>
1327  operator ParamGenerator<T>() const {
1328    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1329        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1330        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1331        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1332        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1333        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1334        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1335        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1336        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1337        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1338        static_cast<T>(v30_)};
1339    return ValuesIn(array);
1340  }
1341
1342 private:
1343  // No implementation - assignment is unsupported.
1344  void operator=(const ValueArray30& other);
1345
1346  const T1 v1_;
1347  const T2 v2_;
1348  const T3 v3_;
1349  const T4 v4_;
1350  const T5 v5_;
1351  const T6 v6_;
1352  const T7 v7_;
1353  const T8 v8_;
1354  const T9 v9_;
1355  const T10 v10_;
1356  const T11 v11_;
1357  const T12 v12_;
1358  const T13 v13_;
1359  const T14 v14_;
1360  const T15 v15_;
1361  const T16 v16_;
1362  const T17 v17_;
1363  const T18 v18_;
1364  const T19 v19_;
1365  const T20 v20_;
1366  const T21 v21_;
1367  const T22 v22_;
1368  const T23 v23_;
1369  const T24 v24_;
1370  const T25 v25_;
1371  const T26 v26_;
1372  const T27 v27_;
1373  const T28 v28_;
1374  const T29 v29_;
1375  const T30 v30_;
1376};
1377
1378template <typename T1, typename T2, typename T3, typename T4, typename T5,
1379    typename T6, typename T7, typename T8, typename T9, typename T10,
1380    typename T11, typename T12, typename T13, typename T14, typename T15,
1381    typename T16, typename T17, typename T18, typename T19, typename T20,
1382    typename T21, typename T22, typename T23, typename T24, typename T25,
1383    typename T26, typename T27, typename T28, typename T29, typename T30,
1384    typename T31>
1385class ValueArray31 {
1386 public:
1387  ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1388      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1389      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1390      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2),
1391      v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
1392      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
1393      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22),
1394      v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28),
1395      v29_(v29), v30_(v30), v31_(v31) {}
1396
1397  template <typename T>
1398  operator ParamGenerator<T>() const {
1399    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1400        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1401        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1402        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1403        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1404        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1405        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1406        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1407        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1408        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1409        static_cast<T>(v30_), static_cast<T>(v31_)};
1410    return ValuesIn(array);
1411  }
1412
1413 private:
1414  // No implementation - assignment is unsupported.
1415  void operator=(const ValueArray31& other);
1416
1417  const T1 v1_;
1418  const T2 v2_;
1419  const T3 v3_;
1420  const T4 v4_;
1421  const T5 v5_;
1422  const T6 v6_;
1423  const T7 v7_;
1424  const T8 v8_;
1425  const T9 v9_;
1426  const T10 v10_;
1427  const T11 v11_;
1428  const T12 v12_;
1429  const T13 v13_;
1430  const T14 v14_;
1431  const T15 v15_;
1432  const T16 v16_;
1433  const T17 v17_;
1434  const T18 v18_;
1435  const T19 v19_;
1436  const T20 v20_;
1437  const T21 v21_;
1438  const T22 v22_;
1439  const T23 v23_;
1440  const T24 v24_;
1441  const T25 v25_;
1442  const T26 v26_;
1443  const T27 v27_;
1444  const T28 v28_;
1445  const T29 v29_;
1446  const T30 v30_;
1447  const T31 v31_;
1448};
1449
1450template <typename T1, typename T2, typename T3, typename T4, typename T5,
1451    typename T6, typename T7, typename T8, typename T9, typename T10,
1452    typename T11, typename T12, typename T13, typename T14, typename T15,
1453    typename T16, typename T17, typename T18, typename T19, typename T20,
1454    typename T21, typename T22, typename T23, typename T24, typename T25,
1455    typename T26, typename T27, typename T28, typename T29, typename T30,
1456    typename T31, typename T32>
1457class ValueArray32 {
1458 public:
1459  ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1460      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1461      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1462      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1),
1463      v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9),
1464      v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15),
1465      v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21),
1466      v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27),
1467      v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {}
1468
1469  template <typename T>
1470  operator ParamGenerator<T>() const {
1471    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1472        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1473        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1474        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1475        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1476        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1477        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1478        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1479        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1480        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1481        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_)};
1482    return ValuesIn(array);
1483  }
1484
1485 private:
1486  // No implementation - assignment is unsupported.
1487  void operator=(const ValueArray32& other);
1488
1489  const T1 v1_;
1490  const T2 v2_;
1491  const T3 v3_;
1492  const T4 v4_;
1493  const T5 v5_;
1494  const T6 v6_;
1495  const T7 v7_;
1496  const T8 v8_;
1497  const T9 v9_;
1498  const T10 v10_;
1499  const T11 v11_;
1500  const T12 v12_;
1501  const T13 v13_;
1502  const T14 v14_;
1503  const T15 v15_;
1504  const T16 v16_;
1505  const T17 v17_;
1506  const T18 v18_;
1507  const T19 v19_;
1508  const T20 v20_;
1509  const T21 v21_;
1510  const T22 v22_;
1511  const T23 v23_;
1512  const T24 v24_;
1513  const T25 v25_;
1514  const T26 v26_;
1515  const T27 v27_;
1516  const T28 v28_;
1517  const T29 v29_;
1518  const T30 v30_;
1519  const T31 v31_;
1520  const T32 v32_;
1521};
1522
1523template <typename T1, typename T2, typename T3, typename T4, typename T5,
1524    typename T6, typename T7, typename T8, typename T9, typename T10,
1525    typename T11, typename T12, typename T13, typename T14, typename T15,
1526    typename T16, typename T17, typename T18, typename T19, typename T20,
1527    typename T21, typename T22, typename T23, typename T24, typename T25,
1528    typename T26, typename T27, typename T28, typename T29, typename T30,
1529    typename T31, typename T32, typename T33>
1530class ValueArray33 {
1531 public:
1532  ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1533      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1534      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1535      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32,
1536      T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
1537      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
1538      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
1539      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26),
1540      v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32),
1541      v33_(v33) {}
1542
1543  template <typename T>
1544  operator ParamGenerator<T>() const {
1545    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1546        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1547        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1548        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1549        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1550        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1551        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1552        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1553        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1554        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1555        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
1556        static_cast<T>(v33_)};
1557    return ValuesIn(array);
1558  }
1559
1560 private:
1561  // No implementation - assignment is unsupported.
1562  void operator=(const ValueArray33& other);
1563
1564  const T1 v1_;
1565  const T2 v2_;
1566  const T3 v3_;
1567  const T4 v4_;
1568  const T5 v5_;
1569  const T6 v6_;
1570  const T7 v7_;
1571  const T8 v8_;
1572  const T9 v9_;
1573  const T10 v10_;
1574  const T11 v11_;
1575  const T12 v12_;
1576  const T13 v13_;
1577  const T14 v14_;
1578  const T15 v15_;
1579  const T16 v16_;
1580  const T17 v17_;
1581  const T18 v18_;
1582  const T19 v19_;
1583  const T20 v20_;
1584  const T21 v21_;
1585  const T22 v22_;
1586  const T23 v23_;
1587  const T24 v24_;
1588  const T25 v25_;
1589  const T26 v26_;
1590  const T27 v27_;
1591  const T28 v28_;
1592  const T29 v29_;
1593  const T30 v30_;
1594  const T31 v31_;
1595  const T32 v32_;
1596  const T33 v33_;
1597};
1598
1599template <typename T1, typename T2, typename T3, typename T4, typename T5,
1600    typename T6, typename T7, typename T8, typename T9, typename T10,
1601    typename T11, typename T12, typename T13, typename T14, typename T15,
1602    typename T16, typename T17, typename T18, typename T19, typename T20,
1603    typename T21, typename T22, typename T23, typename T24, typename T25,
1604    typename T26, typename T27, typename T28, typename T29, typename T30,
1605    typename T31, typename T32, typename T33, typename T34>
1606class ValueArray34 {
1607 public:
1608  ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1609      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1610      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1611      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
1612      T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
1613      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
1614      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
1615      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26),
1616      v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32),
1617      v33_(v33), v34_(v34) {}
1618
1619  template <typename T>
1620  operator ParamGenerator<T>() const {
1621    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1622        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1623        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1624        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1625        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1626        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1627        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1628        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1629        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1630        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1631        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
1632        static_cast<T>(v33_), static_cast<T>(v34_)};
1633    return ValuesIn(array);
1634  }
1635
1636 private:
1637  // No implementation - assignment is unsupported.
1638  void operator=(const ValueArray34& other);
1639
1640  const T1 v1_;
1641  const T2 v2_;
1642  const T3 v3_;
1643  const T4 v4_;
1644  const T5 v5_;
1645  const T6 v6_;
1646  const T7 v7_;
1647  const T8 v8_;
1648  const T9 v9_;
1649  const T10 v10_;
1650  const T11 v11_;
1651  const T12 v12_;
1652  const T13 v13_;
1653  const T14 v14_;
1654  const T15 v15_;
1655  const T16 v16_;
1656  const T17 v17_;
1657  const T18 v18_;
1658  const T19 v19_;
1659  const T20 v20_;
1660  const T21 v21_;
1661  const T22 v22_;
1662  const T23 v23_;
1663  const T24 v24_;
1664  const T25 v25_;
1665  const T26 v26_;
1666  const T27 v27_;
1667  const T28 v28_;
1668  const T29 v29_;
1669  const T30 v30_;
1670  const T31 v31_;
1671  const T32 v32_;
1672  const T33 v33_;
1673  const T34 v34_;
1674};
1675
1676template <typename T1, typename T2, typename T3, typename T4, typename T5,
1677    typename T6, typename T7, typename T8, typename T9, typename T10,
1678    typename T11, typename T12, typename T13, typename T14, typename T15,
1679    typename T16, typename T17, typename T18, typename T19, typename T20,
1680    typename T21, typename T22, typename T23, typename T24, typename T25,
1681    typename T26, typename T27, typename T28, typename T29, typename T30,
1682    typename T31, typename T32, typename T33, typename T34, typename T35>
1683class ValueArray35 {
1684 public:
1685  ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1686      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1687      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1688      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
1689      T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6),
1690      v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13),
1691      v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19),
1692      v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25),
1693      v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31),
1694      v32_(v32), v33_(v33), v34_(v34), v35_(v35) {}
1695
1696  template <typename T>
1697  operator ParamGenerator<T>() const {
1698    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1699        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1700        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1701        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1702        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1703        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1704        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1705        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1706        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1707        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1708        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
1709        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_)};
1710    return ValuesIn(array);
1711  }
1712
1713 private:
1714  // No implementation - assignment is unsupported.
1715  void operator=(const ValueArray35& other);
1716
1717  const T1 v1_;
1718  const T2 v2_;
1719  const T3 v3_;
1720  const T4 v4_;
1721  const T5 v5_;
1722  const T6 v6_;
1723  const T7 v7_;
1724  const T8 v8_;
1725  const T9 v9_;
1726  const T10 v10_;
1727  const T11 v11_;
1728  const T12 v12_;
1729  const T13 v13_;
1730  const T14 v14_;
1731  const T15 v15_;
1732  const T16 v16_;
1733  const T17 v17_;
1734  const T18 v18_;
1735  const T19 v19_;
1736  const T20 v20_;
1737  const T21 v21_;
1738  const T22 v22_;
1739  const T23 v23_;
1740  const T24 v24_;
1741  const T25 v25_;
1742  const T26 v26_;
1743  const T27 v27_;
1744  const T28 v28_;
1745  const T29 v29_;
1746  const T30 v30_;
1747  const T31 v31_;
1748  const T32 v32_;
1749  const T33 v33_;
1750  const T34 v34_;
1751  const T35 v35_;
1752};
1753
1754template <typename T1, typename T2, typename T3, typename T4, typename T5,
1755    typename T6, typename T7, typename T8, typename T9, typename T10,
1756    typename T11, typename T12, typename T13, typename T14, typename T15,
1757    typename T16, typename T17, typename T18, typename T19, typename T20,
1758    typename T21, typename T22, typename T23, typename T24, typename T25,
1759    typename T26, typename T27, typename T28, typename T29, typename T30,
1760    typename T31, typename T32, typename T33, typename T34, typename T35,
1761    typename T36>
1762class ValueArray36 {
1763 public:
1764  ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1765      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1766      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1767      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
1768      T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5),
1769      v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12),
1770      v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18),
1771      v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24),
1772      v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30),
1773      v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {}
1774
1775  template <typename T>
1776  operator ParamGenerator<T>() const {
1777    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1778        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1779        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1780        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1781        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1782        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1783        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1784        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1785        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1786        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1787        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
1788        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
1789        static_cast<T>(v36_)};
1790    return ValuesIn(array);
1791  }
1792
1793 private:
1794  // No implementation - assignment is unsupported.
1795  void operator=(const ValueArray36& other);
1796
1797  const T1 v1_;
1798  const T2 v2_;
1799  const T3 v3_;
1800  const T4 v4_;
1801  const T5 v5_;
1802  const T6 v6_;
1803  const T7 v7_;
1804  const T8 v8_;
1805  const T9 v9_;
1806  const T10 v10_;
1807  const T11 v11_;
1808  const T12 v12_;
1809  const T13 v13_;
1810  const T14 v14_;
1811  const T15 v15_;
1812  const T16 v16_;
1813  const T17 v17_;
1814  const T18 v18_;
1815  const T19 v19_;
1816  const T20 v20_;
1817  const T21 v21_;
1818  const T22 v22_;
1819  const T23 v23_;
1820  const T24 v24_;
1821  const T25 v25_;
1822  const T26 v26_;
1823  const T27 v27_;
1824  const T28 v28_;
1825  const T29 v29_;
1826  const T30 v30_;
1827  const T31 v31_;
1828  const T32 v32_;
1829  const T33 v33_;
1830  const T34 v34_;
1831  const T35 v35_;
1832  const T36 v36_;
1833};
1834
1835template <typename T1, typename T2, typename T3, typename T4, typename T5,
1836    typename T6, typename T7, typename T8, typename T9, typename T10,
1837    typename T11, typename T12, typename T13, typename T14, typename T15,
1838    typename T16, typename T17, typename T18, typename T19, typename T20,
1839    typename T21, typename T22, typename T23, typename T24, typename T25,
1840    typename T26, typename T27, typename T28, typename T29, typename T30,
1841    typename T31, typename T32, typename T33, typename T34, typename T35,
1842    typename T36, typename T37>
1843class ValueArray37 {
1844 public:
1845  ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1846      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1847      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1848      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
1849      T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4),
1850      v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11),
1851      v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17),
1852      v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23),
1853      v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29),
1854      v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35),
1855      v36_(v36), v37_(v37) {}
1856
1857  template <typename T>
1858  operator ParamGenerator<T>() const {
1859    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1860        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1861        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1862        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1863        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1864        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1865        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1866        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1867        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1868        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1869        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
1870        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
1871        static_cast<T>(v36_), static_cast<T>(v37_)};
1872    return ValuesIn(array);
1873  }
1874
1875 private:
1876  // No implementation - assignment is unsupported.
1877  void operator=(const ValueArray37& other);
1878
1879  const T1 v1_;
1880  const T2 v2_;
1881  const T3 v3_;
1882  const T4 v4_;
1883  const T5 v5_;
1884  const T6 v6_;
1885  const T7 v7_;
1886  const T8 v8_;
1887  const T9 v9_;
1888  const T10 v10_;
1889  const T11 v11_;
1890  const T12 v12_;
1891  const T13 v13_;
1892  const T14 v14_;
1893  const T15 v15_;
1894  const T16 v16_;
1895  const T17 v17_;
1896  const T18 v18_;
1897  const T19 v19_;
1898  const T20 v20_;
1899  const T21 v21_;
1900  const T22 v22_;
1901  const T23 v23_;
1902  const T24 v24_;
1903  const T25 v25_;
1904  const T26 v26_;
1905  const T27 v27_;
1906  const T28 v28_;
1907  const T29 v29_;
1908  const T30 v30_;
1909  const T31 v31_;
1910  const T32 v32_;
1911  const T33 v33_;
1912  const T34 v34_;
1913  const T35 v35_;
1914  const T36 v36_;
1915  const T37 v37_;
1916};
1917
1918template <typename T1, typename T2, typename T3, typename T4, typename T5,
1919    typename T6, typename T7, typename T8, typename T9, typename T10,
1920    typename T11, typename T12, typename T13, typename T14, typename T15,
1921    typename T16, typename T17, typename T18, typename T19, typename T20,
1922    typename T21, typename T22, typename T23, typename T24, typename T25,
1923    typename T26, typename T27, typename T28, typename T29, typename T30,
1924    typename T31, typename T32, typename T33, typename T34, typename T35,
1925    typename T36, typename T37, typename T38>
1926class ValueArray38 {
1927 public:
1928  ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
1929      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
1930      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
1931      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
1932      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3),
1933      v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
1934      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
1935      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22),
1936      v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28),
1937      v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34),
1938      v35_(v35), v36_(v36), v37_(v37), v38_(v38) {}
1939
1940  template <typename T>
1941  operator ParamGenerator<T>() const {
1942    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
1943        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
1944        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
1945        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
1946        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
1947        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
1948        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
1949        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
1950        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
1951        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
1952        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
1953        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
1954        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_)};
1955    return ValuesIn(array);
1956  }
1957
1958 private:
1959  // No implementation - assignment is unsupported.
1960  void operator=(const ValueArray38& other);
1961
1962  const T1 v1_;
1963  const T2 v2_;
1964  const T3 v3_;
1965  const T4 v4_;
1966  const T5 v5_;
1967  const T6 v6_;
1968  const T7 v7_;
1969  const T8 v8_;
1970  const T9 v9_;
1971  const T10 v10_;
1972  const T11 v11_;
1973  const T12 v12_;
1974  const T13 v13_;
1975  const T14 v14_;
1976  const T15 v15_;
1977  const T16 v16_;
1978  const T17 v17_;
1979  const T18 v18_;
1980  const T19 v19_;
1981  const T20 v20_;
1982  const T21 v21_;
1983  const T22 v22_;
1984  const T23 v23_;
1985  const T24 v24_;
1986  const T25 v25_;
1987  const T26 v26_;
1988  const T27 v27_;
1989  const T28 v28_;
1990  const T29 v29_;
1991  const T30 v30_;
1992  const T31 v31_;
1993  const T32 v32_;
1994  const T33 v33_;
1995  const T34 v34_;
1996  const T35 v35_;
1997  const T36 v36_;
1998  const T37 v37_;
1999  const T38 v38_;
2000};
2001
2002template <typename T1, typename T2, typename T3, typename T4, typename T5,
2003    typename T6, typename T7, typename T8, typename T9, typename T10,
2004    typename T11, typename T12, typename T13, typename T14, typename T15,
2005    typename T16, typename T17, typename T18, typename T19, typename T20,
2006    typename T21, typename T22, typename T23, typename T24, typename T25,
2007    typename T26, typename T27, typename T28, typename T29, typename T30,
2008    typename T31, typename T32, typename T33, typename T34, typename T35,
2009    typename T36, typename T37, typename T38, typename T39>
2010class ValueArray39 {
2011 public:
2012  ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2013      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2014      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2015      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2016      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2),
2017      v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
2018      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
2019      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22),
2020      v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28),
2021      v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34),
2022      v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {}
2023
2024  template <typename T>
2025  operator ParamGenerator<T>() const {
2026    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2027        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2028        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2029        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2030        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2031        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2032        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2033        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2034        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2035        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2036        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2037        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2038        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2039        static_cast<T>(v39_)};
2040    return ValuesIn(array);
2041  }
2042
2043 private:
2044  // No implementation - assignment is unsupported.
2045  void operator=(const ValueArray39& other);
2046
2047  const T1 v1_;
2048  const T2 v2_;
2049  const T3 v3_;
2050  const T4 v4_;
2051  const T5 v5_;
2052  const T6 v6_;
2053  const T7 v7_;
2054  const T8 v8_;
2055  const T9 v9_;
2056  const T10 v10_;
2057  const T11 v11_;
2058  const T12 v12_;
2059  const T13 v13_;
2060  const T14 v14_;
2061  const T15 v15_;
2062  const T16 v16_;
2063  const T17 v17_;
2064  const T18 v18_;
2065  const T19 v19_;
2066  const T20 v20_;
2067  const T21 v21_;
2068  const T22 v22_;
2069  const T23 v23_;
2070  const T24 v24_;
2071  const T25 v25_;
2072  const T26 v26_;
2073  const T27 v27_;
2074  const T28 v28_;
2075  const T29 v29_;
2076  const T30 v30_;
2077  const T31 v31_;
2078  const T32 v32_;
2079  const T33 v33_;
2080  const T34 v34_;
2081  const T35 v35_;
2082  const T36 v36_;
2083  const T37 v37_;
2084  const T38 v38_;
2085  const T39 v39_;
2086};
2087
2088template <typename T1, typename T2, typename T3, typename T4, typename T5,
2089    typename T6, typename T7, typename T8, typename T9, typename T10,
2090    typename T11, typename T12, typename T13, typename T14, typename T15,
2091    typename T16, typename T17, typename T18, typename T19, typename T20,
2092    typename T21, typename T22, typename T23, typename T24, typename T25,
2093    typename T26, typename T27, typename T28, typename T29, typename T30,
2094    typename T31, typename T32, typename T33, typename T34, typename T35,
2095    typename T36, typename T37, typename T38, typename T39, typename T40>
2096class ValueArray40 {
2097 public:
2098  ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2099      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2100      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2101      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2102      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1),
2103      v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9),
2104      v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15),
2105      v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21),
2106      v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27),
2107      v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33),
2108      v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39),
2109      v40_(v40) {}
2110
2111  template <typename T>
2112  operator ParamGenerator<T>() const {
2113    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2114        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2115        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2116        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2117        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2118        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2119        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2120        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2121        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2122        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2123        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2124        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2125        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2126        static_cast<T>(v39_), static_cast<T>(v40_)};
2127    return ValuesIn(array);
2128  }
2129
2130 private:
2131  // No implementation - assignment is unsupported.
2132  void operator=(const ValueArray40& other);
2133
2134  const T1 v1_;
2135  const T2 v2_;
2136  const T3 v3_;
2137  const T4 v4_;
2138  const T5 v5_;
2139  const T6 v6_;
2140  const T7 v7_;
2141  const T8 v8_;
2142  const T9 v9_;
2143  const T10 v10_;
2144  const T11 v11_;
2145  const T12 v12_;
2146  const T13 v13_;
2147  const T14 v14_;
2148  const T15 v15_;
2149  const T16 v16_;
2150  const T17 v17_;
2151  const T18 v18_;
2152  const T19 v19_;
2153  const T20 v20_;
2154  const T21 v21_;
2155  const T22 v22_;
2156  const T23 v23_;
2157  const T24 v24_;
2158  const T25 v25_;
2159  const T26 v26_;
2160  const T27 v27_;
2161  const T28 v28_;
2162  const T29 v29_;
2163  const T30 v30_;
2164  const T31 v31_;
2165  const T32 v32_;
2166  const T33 v33_;
2167  const T34 v34_;
2168  const T35 v35_;
2169  const T36 v36_;
2170  const T37 v37_;
2171  const T38 v38_;
2172  const T39 v39_;
2173  const T40 v40_;
2174};
2175
2176template <typename T1, typename T2, typename T3, typename T4, typename T5,
2177    typename T6, typename T7, typename T8, typename T9, typename T10,
2178    typename T11, typename T12, typename T13, typename T14, typename T15,
2179    typename T16, typename T17, typename T18, typename T19, typename T20,
2180    typename T21, typename T22, typename T23, typename T24, typename T25,
2181    typename T26, typename T27, typename T28, typename T29, typename T30,
2182    typename T31, typename T32, typename T33, typename T34, typename T35,
2183    typename T36, typename T37, typename T38, typename T39, typename T40,
2184    typename T41>
2185class ValueArray41 {
2186 public:
2187  ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2188      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2189      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2190      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2191      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40,
2192      T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
2193      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
2194      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
2195      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26),
2196      v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32),
2197      v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38),
2198      v39_(v39), v40_(v40), v41_(v41) {}
2199
2200  template <typename T>
2201  operator ParamGenerator<T>() const {
2202    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2203        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2204        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2205        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2206        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2207        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2208        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2209        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2210        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2211        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2212        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2213        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2214        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2215        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_)};
2216    return ValuesIn(array);
2217  }
2218
2219 private:
2220  // No implementation - assignment is unsupported.
2221  void operator=(const ValueArray41& other);
2222
2223  const T1 v1_;
2224  const T2 v2_;
2225  const T3 v3_;
2226  const T4 v4_;
2227  const T5 v5_;
2228  const T6 v6_;
2229  const T7 v7_;
2230  const T8 v8_;
2231  const T9 v9_;
2232  const T10 v10_;
2233  const T11 v11_;
2234  const T12 v12_;
2235  const T13 v13_;
2236  const T14 v14_;
2237  const T15 v15_;
2238  const T16 v16_;
2239  const T17 v17_;
2240  const T18 v18_;
2241  const T19 v19_;
2242  const T20 v20_;
2243  const T21 v21_;
2244  const T22 v22_;
2245  const T23 v23_;
2246  const T24 v24_;
2247  const T25 v25_;
2248  const T26 v26_;
2249  const T27 v27_;
2250  const T28 v28_;
2251  const T29 v29_;
2252  const T30 v30_;
2253  const T31 v31_;
2254  const T32 v32_;
2255  const T33 v33_;
2256  const T34 v34_;
2257  const T35 v35_;
2258  const T36 v36_;
2259  const T37 v37_;
2260  const T38 v38_;
2261  const T39 v39_;
2262  const T40 v40_;
2263  const T41 v41_;
2264};
2265
2266template <typename T1, typename T2, typename T3, typename T4, typename T5,
2267    typename T6, typename T7, typename T8, typename T9, typename T10,
2268    typename T11, typename T12, typename T13, typename T14, typename T15,
2269    typename T16, typename T17, typename T18, typename T19, typename T20,
2270    typename T21, typename T22, typename T23, typename T24, typename T25,
2271    typename T26, typename T27, typename T28, typename T29, typename T30,
2272    typename T31, typename T32, typename T33, typename T34, typename T35,
2273    typename T36, typename T37, typename T38, typename T39, typename T40,
2274    typename T41, typename T42>
2275class ValueArray42 {
2276 public:
2277  ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2278      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2279      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2280      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2281      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2282      T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
2283      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
2284      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
2285      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26),
2286      v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32),
2287      v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38),
2288      v39_(v39), v40_(v40), v41_(v41), v42_(v42) {}
2289
2290  template <typename T>
2291  operator ParamGenerator<T>() const {
2292    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2293        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2294        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2295        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2296        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2297        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2298        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2299        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2300        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2301        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2302        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2303        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2304        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2305        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2306        static_cast<T>(v42_)};
2307    return ValuesIn(array);
2308  }
2309
2310 private:
2311  // No implementation - assignment is unsupported.
2312  void operator=(const ValueArray42& other);
2313
2314  const T1 v1_;
2315  const T2 v2_;
2316  const T3 v3_;
2317  const T4 v4_;
2318  const T5 v5_;
2319  const T6 v6_;
2320  const T7 v7_;
2321  const T8 v8_;
2322  const T9 v9_;
2323  const T10 v10_;
2324  const T11 v11_;
2325  const T12 v12_;
2326  const T13 v13_;
2327  const T14 v14_;
2328  const T15 v15_;
2329  const T16 v16_;
2330  const T17 v17_;
2331  const T18 v18_;
2332  const T19 v19_;
2333  const T20 v20_;
2334  const T21 v21_;
2335  const T22 v22_;
2336  const T23 v23_;
2337  const T24 v24_;
2338  const T25 v25_;
2339  const T26 v26_;
2340  const T27 v27_;
2341  const T28 v28_;
2342  const T29 v29_;
2343  const T30 v30_;
2344  const T31 v31_;
2345  const T32 v32_;
2346  const T33 v33_;
2347  const T34 v34_;
2348  const T35 v35_;
2349  const T36 v36_;
2350  const T37 v37_;
2351  const T38 v38_;
2352  const T39 v39_;
2353  const T40 v40_;
2354  const T41 v41_;
2355  const T42 v42_;
2356};
2357
2358template <typename T1, typename T2, typename T3, typename T4, typename T5,
2359    typename T6, typename T7, typename T8, typename T9, typename T10,
2360    typename T11, typename T12, typename T13, typename T14, typename T15,
2361    typename T16, typename T17, typename T18, typename T19, typename T20,
2362    typename T21, typename T22, typename T23, typename T24, typename T25,
2363    typename T26, typename T27, typename T28, typename T29, typename T30,
2364    typename T31, typename T32, typename T33, typename T34, typename T35,
2365    typename T36, typename T37, typename T38, typename T39, typename T40,
2366    typename T41, typename T42, typename T43>
2367class ValueArray43 {
2368 public:
2369  ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2370      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2371      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2372      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2373      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2374      T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6),
2375      v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13),
2376      v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19),
2377      v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25),
2378      v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31),
2379      v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37),
2380      v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {}
2381
2382  template <typename T>
2383  operator ParamGenerator<T>() const {
2384    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2385        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2386        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2387        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2388        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2389        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2390        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2391        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2392        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2393        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2394        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2395        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2396        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2397        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2398        static_cast<T>(v42_), static_cast<T>(v43_)};
2399    return ValuesIn(array);
2400  }
2401
2402 private:
2403  // No implementation - assignment is unsupported.
2404  void operator=(const ValueArray43& other);
2405
2406  const T1 v1_;
2407  const T2 v2_;
2408  const T3 v3_;
2409  const T4 v4_;
2410  const T5 v5_;
2411  const T6 v6_;
2412  const T7 v7_;
2413  const T8 v8_;
2414  const T9 v9_;
2415  const T10 v10_;
2416  const T11 v11_;
2417  const T12 v12_;
2418  const T13 v13_;
2419  const T14 v14_;
2420  const T15 v15_;
2421  const T16 v16_;
2422  const T17 v17_;
2423  const T18 v18_;
2424  const T19 v19_;
2425  const T20 v20_;
2426  const T21 v21_;
2427  const T22 v22_;
2428  const T23 v23_;
2429  const T24 v24_;
2430  const T25 v25_;
2431  const T26 v26_;
2432  const T27 v27_;
2433  const T28 v28_;
2434  const T29 v29_;
2435  const T30 v30_;
2436  const T31 v31_;
2437  const T32 v32_;
2438  const T33 v33_;
2439  const T34 v34_;
2440  const T35 v35_;
2441  const T36 v36_;
2442  const T37 v37_;
2443  const T38 v38_;
2444  const T39 v39_;
2445  const T40 v40_;
2446  const T41 v41_;
2447  const T42 v42_;
2448  const T43 v43_;
2449};
2450
2451template <typename T1, typename T2, typename T3, typename T4, typename T5,
2452    typename T6, typename T7, typename T8, typename T9, typename T10,
2453    typename T11, typename T12, typename T13, typename T14, typename T15,
2454    typename T16, typename T17, typename T18, typename T19, typename T20,
2455    typename T21, typename T22, typename T23, typename T24, typename T25,
2456    typename T26, typename T27, typename T28, typename T29, typename T30,
2457    typename T31, typename T32, typename T33, typename T34, typename T35,
2458    typename T36, typename T37, typename T38, typename T39, typename T40,
2459    typename T41, typename T42, typename T43, typename T44>
2460class ValueArray44 {
2461 public:
2462  ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2463      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2464      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2465      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2466      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2467      T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5),
2468      v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12),
2469      v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18),
2470      v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24),
2471      v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30),
2472      v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36),
2473      v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42),
2474      v43_(v43), v44_(v44) {}
2475
2476  template <typename T>
2477  operator ParamGenerator<T>() const {
2478    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2479        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2480        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2481        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2482        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2483        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2484        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2485        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2486        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2487        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2488        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2489        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2490        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2491        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2492        static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_)};
2493    return ValuesIn(array);
2494  }
2495
2496 private:
2497  // No implementation - assignment is unsupported.
2498  void operator=(const ValueArray44& other);
2499
2500  const T1 v1_;
2501  const T2 v2_;
2502  const T3 v3_;
2503  const T4 v4_;
2504  const T5 v5_;
2505  const T6 v6_;
2506  const T7 v7_;
2507  const T8 v8_;
2508  const T9 v9_;
2509  const T10 v10_;
2510  const T11 v11_;
2511  const T12 v12_;
2512  const T13 v13_;
2513  const T14 v14_;
2514  const T15 v15_;
2515  const T16 v16_;
2516  const T17 v17_;
2517  const T18 v18_;
2518  const T19 v19_;
2519  const T20 v20_;
2520  const T21 v21_;
2521  const T22 v22_;
2522  const T23 v23_;
2523  const T24 v24_;
2524  const T25 v25_;
2525  const T26 v26_;
2526  const T27 v27_;
2527  const T28 v28_;
2528  const T29 v29_;
2529  const T30 v30_;
2530  const T31 v31_;
2531  const T32 v32_;
2532  const T33 v33_;
2533  const T34 v34_;
2534  const T35 v35_;
2535  const T36 v36_;
2536  const T37 v37_;
2537  const T38 v38_;
2538  const T39 v39_;
2539  const T40 v40_;
2540  const T41 v41_;
2541  const T42 v42_;
2542  const T43 v43_;
2543  const T44 v44_;
2544};
2545
2546template <typename T1, typename T2, typename T3, typename T4, typename T5,
2547    typename T6, typename T7, typename T8, typename T9, typename T10,
2548    typename T11, typename T12, typename T13, typename T14, typename T15,
2549    typename T16, typename T17, typename T18, typename T19, typename T20,
2550    typename T21, typename T22, typename T23, typename T24, typename T25,
2551    typename T26, typename T27, typename T28, typename T29, typename T30,
2552    typename T31, typename T32, typename T33, typename T34, typename T35,
2553    typename T36, typename T37, typename T38, typename T39, typename T40,
2554    typename T41, typename T42, typename T43, typename T44, typename T45>
2555class ValueArray45 {
2556 public:
2557  ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2558      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2559      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2560      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2561      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2562      T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4),
2563      v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11),
2564      v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17),
2565      v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23),
2566      v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29),
2567      v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35),
2568      v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41),
2569      v42_(v42), v43_(v43), v44_(v44), v45_(v45) {}
2570
2571  template <typename T>
2572  operator ParamGenerator<T>() const {
2573    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2574        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2575        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2576        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2577        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2578        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2579        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2580        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2581        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2582        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2583        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2584        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2585        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2586        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2587        static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_),
2588        static_cast<T>(v45_)};
2589    return ValuesIn(array);
2590  }
2591
2592 private:
2593  // No implementation - assignment is unsupported.
2594  void operator=(const ValueArray45& other);
2595
2596  const T1 v1_;
2597  const T2 v2_;
2598  const T3 v3_;
2599  const T4 v4_;
2600  const T5 v5_;
2601  const T6 v6_;
2602  const T7 v7_;
2603  const T8 v8_;
2604  const T9 v9_;
2605  const T10 v10_;
2606  const T11 v11_;
2607  const T12 v12_;
2608  const T13 v13_;
2609  const T14 v14_;
2610  const T15 v15_;
2611  const T16 v16_;
2612  const T17 v17_;
2613  const T18 v18_;
2614  const T19 v19_;
2615  const T20 v20_;
2616  const T21 v21_;
2617  const T22 v22_;
2618  const T23 v23_;
2619  const T24 v24_;
2620  const T25 v25_;
2621  const T26 v26_;
2622  const T27 v27_;
2623  const T28 v28_;
2624  const T29 v29_;
2625  const T30 v30_;
2626  const T31 v31_;
2627  const T32 v32_;
2628  const T33 v33_;
2629  const T34 v34_;
2630  const T35 v35_;
2631  const T36 v36_;
2632  const T37 v37_;
2633  const T38 v38_;
2634  const T39 v39_;
2635  const T40 v40_;
2636  const T41 v41_;
2637  const T42 v42_;
2638  const T43 v43_;
2639  const T44 v44_;
2640  const T45 v45_;
2641};
2642
2643template <typename T1, typename T2, typename T3, typename T4, typename T5,
2644    typename T6, typename T7, typename T8, typename T9, typename T10,
2645    typename T11, typename T12, typename T13, typename T14, typename T15,
2646    typename T16, typename T17, typename T18, typename T19, typename T20,
2647    typename T21, typename T22, typename T23, typename T24, typename T25,
2648    typename T26, typename T27, typename T28, typename T29, typename T30,
2649    typename T31, typename T32, typename T33, typename T34, typename T35,
2650    typename T36, typename T37, typename T38, typename T39, typename T40,
2651    typename T41, typename T42, typename T43, typename T44, typename T45,
2652    typename T46>
2653class ValueArray46 {
2654 public:
2655  ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2656      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2657      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2658      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2659      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2660      T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3),
2661      v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
2662      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
2663      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22),
2664      v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28),
2665      v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34),
2666      v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40),
2667      v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {}
2668
2669  template <typename T>
2670  operator ParamGenerator<T>() const {
2671    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2672        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2673        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2674        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2675        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2676        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2677        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2678        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2679        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2680        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2681        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2682        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2683        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2684        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2685        static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_),
2686        static_cast<T>(v45_), static_cast<T>(v46_)};
2687    return ValuesIn(array);
2688  }
2689
2690 private:
2691  // No implementation - assignment is unsupported.
2692  void operator=(const ValueArray46& other);
2693
2694  const T1 v1_;
2695  const T2 v2_;
2696  const T3 v3_;
2697  const T4 v4_;
2698  const T5 v5_;
2699  const T6 v6_;
2700  const T7 v7_;
2701  const T8 v8_;
2702  const T9 v9_;
2703  const T10 v10_;
2704  const T11 v11_;
2705  const T12 v12_;
2706  const T13 v13_;
2707  const T14 v14_;
2708  const T15 v15_;
2709  const T16 v16_;
2710  const T17 v17_;
2711  const T18 v18_;
2712  const T19 v19_;
2713  const T20 v20_;
2714  const T21 v21_;
2715  const T22 v22_;
2716  const T23 v23_;
2717  const T24 v24_;
2718  const T25 v25_;
2719  const T26 v26_;
2720  const T27 v27_;
2721  const T28 v28_;
2722  const T29 v29_;
2723  const T30 v30_;
2724  const T31 v31_;
2725  const T32 v32_;
2726  const T33 v33_;
2727  const T34 v34_;
2728  const T35 v35_;
2729  const T36 v36_;
2730  const T37 v37_;
2731  const T38 v38_;
2732  const T39 v39_;
2733  const T40 v40_;
2734  const T41 v41_;
2735  const T42 v42_;
2736  const T43 v43_;
2737  const T44 v44_;
2738  const T45 v45_;
2739  const T46 v46_;
2740};
2741
2742template <typename T1, typename T2, typename T3, typename T4, typename T5,
2743    typename T6, typename T7, typename T8, typename T9, typename T10,
2744    typename T11, typename T12, typename T13, typename T14, typename T15,
2745    typename T16, typename T17, typename T18, typename T19, typename T20,
2746    typename T21, typename T22, typename T23, typename T24, typename T25,
2747    typename T26, typename T27, typename T28, typename T29, typename T30,
2748    typename T31, typename T32, typename T33, typename T34, typename T35,
2749    typename T36, typename T37, typename T38, typename T39, typename T40,
2750    typename T41, typename T42, typename T43, typename T44, typename T45,
2751    typename T46, typename T47>
2752class ValueArray47 {
2753 public:
2754  ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2755      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2756      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2757      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2758      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2759      T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2),
2760      v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10),
2761      v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16),
2762      v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22),
2763      v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28),
2764      v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34),
2765      v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40),
2766      v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46),
2767      v47_(v47) {}
2768
2769  template <typename T>
2770  operator ParamGenerator<T>() const {
2771    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2772        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2773        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2774        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2775        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2776        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2777        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2778        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2779        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2780        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2781        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2782        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2783        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2784        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2785        static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_),
2786        static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_)};
2787    return ValuesIn(array);
2788  }
2789
2790 private:
2791  // No implementation - assignment is unsupported.
2792  void operator=(const ValueArray47& other);
2793
2794  const T1 v1_;
2795  const T2 v2_;
2796  const T3 v3_;
2797  const T4 v4_;
2798  const T5 v5_;
2799  const T6 v6_;
2800  const T7 v7_;
2801  const T8 v8_;
2802  const T9 v9_;
2803  const T10 v10_;
2804  const T11 v11_;
2805  const T12 v12_;
2806  const T13 v13_;
2807  const T14 v14_;
2808  const T15 v15_;
2809  const T16 v16_;
2810  const T17 v17_;
2811  const T18 v18_;
2812  const T19 v19_;
2813  const T20 v20_;
2814  const T21 v21_;
2815  const T22 v22_;
2816  const T23 v23_;
2817  const T24 v24_;
2818  const T25 v25_;
2819  const T26 v26_;
2820  const T27 v27_;
2821  const T28 v28_;
2822  const T29 v29_;
2823  const T30 v30_;
2824  const T31 v31_;
2825  const T32 v32_;
2826  const T33 v33_;
2827  const T34 v34_;
2828  const T35 v35_;
2829  const T36 v36_;
2830  const T37 v37_;
2831  const T38 v38_;
2832  const T39 v39_;
2833  const T40 v40_;
2834  const T41 v41_;
2835  const T42 v42_;
2836  const T43 v43_;
2837  const T44 v44_;
2838  const T45 v45_;
2839  const T46 v46_;
2840  const T47 v47_;
2841};
2842
2843template <typename T1, typename T2, typename T3, typename T4, typename T5,
2844    typename T6, typename T7, typename T8, typename T9, typename T10,
2845    typename T11, typename T12, typename T13, typename T14, typename T15,
2846    typename T16, typename T17, typename T18, typename T19, typename T20,
2847    typename T21, typename T22, typename T23, typename T24, typename T25,
2848    typename T26, typename T27, typename T28, typename T29, typename T30,
2849    typename T31, typename T32, typename T33, typename T34, typename T35,
2850    typename T36, typename T37, typename T38, typename T39, typename T40,
2851    typename T41, typename T42, typename T43, typename T44, typename T45,
2852    typename T46, typename T47, typename T48>
2853class ValueArray48 {
2854 public:
2855  ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2856      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2857      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2858      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2859      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2860      T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1),
2861      v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9),
2862      v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15),
2863      v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21),
2864      v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27),
2865      v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33),
2866      v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39),
2867      v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45),
2868      v46_(v46), v47_(v47), v48_(v48) {}
2869
2870  template <typename T>
2871  operator ParamGenerator<T>() const {
2872    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2873        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2874        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2875        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2876        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2877        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2878        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2879        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2880        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2881        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2882        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2883        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2884        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2885        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2886        static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_),
2887        static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_),
2888        static_cast<T>(v48_)};
2889    return ValuesIn(array);
2890  }
2891
2892 private:
2893  // No implementation - assignment is unsupported.
2894  void operator=(const ValueArray48& other);
2895
2896  const T1 v1_;
2897  const T2 v2_;
2898  const T3 v3_;
2899  const T4 v4_;
2900  const T5 v5_;
2901  const T6 v6_;
2902  const T7 v7_;
2903  const T8 v8_;
2904  const T9 v9_;
2905  const T10 v10_;
2906  const T11 v11_;
2907  const T12 v12_;
2908  const T13 v13_;
2909  const T14 v14_;
2910  const T15 v15_;
2911  const T16 v16_;
2912  const T17 v17_;
2913  const T18 v18_;
2914  const T19 v19_;
2915  const T20 v20_;
2916  const T21 v21_;
2917  const T22 v22_;
2918  const T23 v23_;
2919  const T24 v24_;
2920  const T25 v25_;
2921  const T26 v26_;
2922  const T27 v27_;
2923  const T28 v28_;
2924  const T29 v29_;
2925  const T30 v30_;
2926  const T31 v31_;
2927  const T32 v32_;
2928  const T33 v33_;
2929  const T34 v34_;
2930  const T35 v35_;
2931  const T36 v36_;
2932  const T37 v37_;
2933  const T38 v38_;
2934  const T39 v39_;
2935  const T40 v40_;
2936  const T41 v41_;
2937  const T42 v42_;
2938  const T43 v43_;
2939  const T44 v44_;
2940  const T45 v45_;
2941  const T46 v46_;
2942  const T47 v47_;
2943  const T48 v48_;
2944};
2945
2946template <typename T1, typename T2, typename T3, typename T4, typename T5,
2947    typename T6, typename T7, typename T8, typename T9, typename T10,
2948    typename T11, typename T12, typename T13, typename T14, typename T15,
2949    typename T16, typename T17, typename T18, typename T19, typename T20,
2950    typename T21, typename T22, typename T23, typename T24, typename T25,
2951    typename T26, typename T27, typename T28, typename T29, typename T30,
2952    typename T31, typename T32, typename T33, typename T34, typename T35,
2953    typename T36, typename T37, typename T38, typename T39, typename T40,
2954    typename T41, typename T42, typename T43, typename T44, typename T45,
2955    typename T46, typename T47, typename T48, typename T49>
2956class ValueArray49 {
2957 public:
2958  ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
2959      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
2960      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
2961      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
2962      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
2963      T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48,
2964      T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
2965      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
2966      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
2967      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26),
2968      v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32),
2969      v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38),
2970      v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44),
2971      v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {}
2972
2973  template <typename T>
2974  operator ParamGenerator<T>() const {
2975    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
2976        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
2977        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
2978        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
2979        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
2980        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
2981        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
2982        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
2983        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
2984        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
2985        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
2986        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
2987        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
2988        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
2989        static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_),
2990        static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_),
2991        static_cast<T>(v48_), static_cast<T>(v49_)};
2992    return ValuesIn(array);
2993  }
2994
2995 private:
2996  // No implementation - assignment is unsupported.
2997  void operator=(const ValueArray49& other);
2998
2999  const T1 v1_;
3000  const T2 v2_;
3001  const T3 v3_;
3002  const T4 v4_;
3003  const T5 v5_;
3004  const T6 v6_;
3005  const T7 v7_;
3006  const T8 v8_;
3007  const T9 v9_;
3008  const T10 v10_;
3009  const T11 v11_;
3010  const T12 v12_;
3011  const T13 v13_;
3012  const T14 v14_;
3013  const T15 v15_;
3014  const T16 v16_;
3015  const T17 v17_;
3016  const T18 v18_;
3017  const T19 v19_;
3018  const T20 v20_;
3019  const T21 v21_;
3020  const T22 v22_;
3021  const T23 v23_;
3022  const T24 v24_;
3023  const T25 v25_;
3024  const T26 v26_;
3025  const T27 v27_;
3026  const T28 v28_;
3027  const T29 v29_;
3028  const T30 v30_;
3029  const T31 v31_;
3030  const T32 v32_;
3031  const T33 v33_;
3032  const T34 v34_;
3033  const T35 v35_;
3034  const T36 v36_;
3035  const T37 v37_;
3036  const T38 v38_;
3037  const T39 v39_;
3038  const T40 v40_;
3039  const T41 v41_;
3040  const T42 v42_;
3041  const T43 v43_;
3042  const T44 v44_;
3043  const T45 v45_;
3044  const T46 v46_;
3045  const T47 v47_;
3046  const T48 v48_;
3047  const T49 v49_;
3048};
3049
3050template <typename T1, typename T2, typename T3, typename T4, typename T5,
3051    typename T6, typename T7, typename T8, typename T9, typename T10,
3052    typename T11, typename T12, typename T13, typename T14, typename T15,
3053    typename T16, typename T17, typename T18, typename T19, typename T20,
3054    typename T21, typename T22, typename T23, typename T24, typename T25,
3055    typename T26, typename T27, typename T28, typename T29, typename T30,
3056    typename T31, typename T32, typename T33, typename T34, typename T35,
3057    typename T36, typename T37, typename T38, typename T39, typename T40,
3058    typename T41, typename T42, typename T43, typename T44, typename T45,
3059    typename T46, typename T47, typename T48, typename T49, typename T50>
3060class ValueArray50 {
3061 public:
3062  ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9,
3063      T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17,
3064      T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25,
3065      T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33,
3066      T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41,
3067      T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49,
3068      T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7),
3069      v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14),
3070      v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20),
3071      v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26),
3072      v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32),
3073      v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38),
3074      v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44),
3075      v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {}
3076
3077  template <typename T>
3078  operator ParamGenerator<T>() const {
3079    const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_),
3080        static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_),
3081        static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_),
3082        static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_),
3083        static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_),
3084        static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_),
3085        static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_),
3086        static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_),
3087        static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_),
3088        static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_),
3089        static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_),
3090        static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_),
3091        static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_),
3092        static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_),
3093        static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_),
3094        static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_),
3095        static_cast<T>(v48_), static_cast<T>(v49_), static_cast<T>(v50_)};
3096    return ValuesIn(array);
3097  }
3098
3099 private:
3100  // No implementation - assignment is unsupported.
3101  void operator=(const ValueArray50& other);
3102
3103  const T1 v1_;
3104  const T2 v2_;
3105  const T3 v3_;
3106  const T4 v4_;
3107  const T5 v5_;
3108  const T6 v6_;
3109  const T7 v7_;
3110  const T8 v8_;
3111  const T9 v9_;
3112  const T10 v10_;
3113  const T11 v11_;
3114  const T12 v12_;
3115  const T13 v13_;
3116  const T14 v14_;
3117  const T15 v15_;
3118  const T16 v16_;
3119  const T17 v17_;
3120  const T18 v18_;
3121  const T19 v19_;
3122  const T20 v20_;
3123  const T21 v21_;
3124  const T22 v22_;
3125  const T23 v23_;
3126  const T24 v24_;
3127  const T25 v25_;
3128  const T26 v26_;
3129  const T27 v27_;
3130  const T28 v28_;
3131  const T29 v29_;
3132  const T30 v30_;
3133  const T31 v31_;
3134  const T32 v32_;
3135  const T33 v33_;
3136  const T34 v34_;
3137  const T35 v35_;
3138  const T36 v36_;
3139  const T37 v37_;
3140  const T38 v38_;
3141  const T39 v39_;
3142  const T40 v40_;
3143  const T41 v41_;
3144  const T42 v42_;
3145  const T43 v43_;
3146  const T44 v44_;
3147  const T45 v45_;
3148  const T46 v46_;
3149  const T47 v47_;
3150  const T48 v48_;
3151  const T49 v49_;
3152  const T50 v50_;
3153};
3154
3155# if GTEST_HAS_COMBINE
3156// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
3157//
3158// Generates values from the Cartesian product of values produced
3159// by the argument generators.
3160//
3161template <typename T1, typename T2>
3162class CartesianProductGenerator2
3163    : public ParamGeneratorInterface< ::testing::tuple<T1, T2> > {
3164 public:
3165  typedef ::testing::tuple<T1, T2> ParamType;
3166
3167  CartesianProductGenerator2(const ParamGenerator<T1>& g1,
3168      const ParamGenerator<T2>& g2)
3169      : g1_(g1), g2_(g2) {}
3170  virtual ~CartesianProductGenerator2() {}
3171
3172  virtual ParamIteratorInterface<ParamType>* Begin() const {
3173    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin());
3174  }
3175  virtual ParamIteratorInterface<ParamType>* End() const {
3176    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end());
3177  }
3178
3179 private:
3180  class Iterator : public ParamIteratorInterface<ParamType> {
3181   public:
3182    Iterator(const ParamGeneratorInterface<ParamType>* base,
3183      const ParamGenerator<T1>& g1,
3184      const typename ParamGenerator<T1>::iterator& current1,
3185      const ParamGenerator<T2>& g2,
3186      const typename ParamGenerator<T2>::iterator& current2)
3187        : base_(base),
3188          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
3189          begin2_(g2.begin()), end2_(g2.end()), current2_(current2)    {
3190      ComputeCurrentValue();
3191    }
3192    virtual ~Iterator() {}
3193
3194    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
3195      return base_;
3196    }
3197    // Advance should not be called on beyond-of-range iterators
3198    // so no component iterators must be beyond end of range, either.
3199    virtual void Advance() {
3200      assert(!AtEnd());
3201      ++current2_;
3202      if (current2_ == end2_) {
3203        current2_ = begin2_;
3204        ++current1_;
3205      }
3206      ComputeCurrentValue();
3207    }
3208    virtual ParamIteratorInterface<ParamType>* Clone() const {
3209      return new Iterator(*this);
3210    }
3211    virtual const ParamType* Current() const { return &current_value_; }
3212    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
3213      // Having the same base generator guarantees that the other
3214      // iterator is of the same type and we can downcast.
3215      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
3216          << "The program attempted to compare iterators "
3217          << "from different generators." << std::endl;
3218      const Iterator* typed_other =
3219          CheckedDowncastToActualType<const Iterator>(&other);
3220      // We must report iterators equal if they both point beyond their
3221      // respective ranges. That can happen in a variety of fashions,
3222      // so we have to consult AtEnd().
3223      return (AtEnd() && typed_other->AtEnd()) ||
3224         (
3225          current1_ == typed_other->current1_ &&
3226          current2_ == typed_other->current2_);
3227    }
3228
3229   private:
3230    Iterator(const Iterator& other)
3231        : base_(other.base_),
3232        begin1_(other.begin1_),
3233        end1_(other.end1_),
3234        current1_(other.current1_),
3235        begin2_(other.begin2_),
3236        end2_(other.end2_),
3237        current2_(other.current2_) {
3238      ComputeCurrentValue();
3239    }
3240
3241    void ComputeCurrentValue() {
3242      if (!AtEnd())
3243        current_value_ = ParamType(*current1_, *current2_);
3244    }
3245    bool AtEnd() const {
3246      // We must report iterator past the end of the range when either of the
3247      // component iterators has reached the end of its range.
3248      return
3249          current1_ == end1_ ||
3250          current2_ == end2_;
3251    }
3252
3253    // No implementation - assignment is unsupported.
3254    void operator=(const Iterator& other);
3255
3256    const ParamGeneratorInterface<ParamType>* const base_;
3257    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
3258    // current[i]_ is the actual traversing iterator.
3259    const typename ParamGenerator<T1>::iterator begin1_;
3260    const typename ParamGenerator<T1>::iterator end1_;
3261    typename ParamGenerator<T1>::iterator current1_;
3262    const typename ParamGenerator<T2>::iterator begin2_;
3263    const typename ParamGenerator<T2>::iterator end2_;
3264    typename ParamGenerator<T2>::iterator current2_;
3265    ParamType current_value_;
3266  };  // class CartesianProductGenerator2::Iterator
3267
3268  // No implementation - assignment is unsupported.
3269  void operator=(const CartesianProductGenerator2& other);
3270
3271  const ParamGenerator<T1> g1_;
3272  const ParamGenerator<T2> g2_;
3273};  // class CartesianProductGenerator2
3274
3275
3276template <typename T1, typename T2, typename T3>
3277class CartesianProductGenerator3
3278    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3> > {
3279 public:
3280  typedef ::testing::tuple<T1, T2, T3> ParamType;
3281
3282  CartesianProductGenerator3(const ParamGenerator<T1>& g1,
3283      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3)
3284      : g1_(g1), g2_(g2), g3_(g3) {}
3285  virtual ~CartesianProductGenerator3() {}
3286
3287  virtual ParamIteratorInterface<ParamType>* Begin() const {
3288    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
3289        g3_.begin());
3290  }
3291  virtual ParamIteratorInterface<ParamType>* End() const {
3292    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end());
3293  }
3294
3295 private:
3296  class Iterator : public ParamIteratorInterface<ParamType> {
3297   public:
3298    Iterator(const ParamGeneratorInterface<ParamType>* base,
3299      const ParamGenerator<T1>& g1,
3300      const typename ParamGenerator<T1>::iterator& current1,
3301      const ParamGenerator<T2>& g2,
3302      const typename ParamGenerator<T2>::iterator& current2,
3303      const ParamGenerator<T3>& g3,
3304      const typename ParamGenerator<T3>::iterator& current3)
3305        : base_(base),
3306          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
3307          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
3308          begin3_(g3.begin()), end3_(g3.end()), current3_(current3)    {
3309      ComputeCurrentValue();
3310    }
3311    virtual ~Iterator() {}
3312
3313    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
3314      return base_;
3315    }
3316    // Advance should not be called on beyond-of-range iterators
3317    // so no component iterators must be beyond end of range, either.
3318    virtual void Advance() {
3319      assert(!AtEnd());
3320      ++current3_;
3321      if (current3_ == end3_) {
3322        current3_ = begin3_;
3323        ++current2_;
3324      }
3325      if (current2_ == end2_) {
3326        current2_ = begin2_;
3327        ++current1_;
3328      }
3329      ComputeCurrentValue();
3330    }
3331    virtual ParamIteratorInterface<ParamType>* Clone() const {
3332      return new Iterator(*this);
3333    }
3334    virtual const ParamType* Current() const { return &current_value_; }
3335    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
3336      // Having the same base generator guarantees that the other
3337      // iterator is of the same type and we can downcast.
3338      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
3339          << "The program attempted to compare iterators "
3340          << "from different generators." << std::endl;
3341      const Iterator* typed_other =
3342          CheckedDowncastToActualType<const Iterator>(&other);
3343      // We must report iterators equal if they both point beyond their
3344      // respective ranges. That can happen in a variety of fashions,
3345      // so we have to consult AtEnd().
3346      return (AtEnd() && typed_other->AtEnd()) ||
3347         (
3348          current1_ == typed_other->current1_ &&
3349          current2_ == typed_other->current2_ &&
3350          current3_ == typed_other->current3_);
3351    }
3352
3353   private:
3354    Iterator(const Iterator& other)
3355        : base_(other.base_),
3356        begin1_(other.begin1_),
3357        end1_(other.end1_),
3358        current1_(other.current1_),
3359        begin2_(other.begin2_),
3360        end2_(other.end2_),
3361        current2_(other.current2_),
3362        begin3_(other.begin3_),
3363        end3_(other.end3_),
3364        current3_(other.current3_) {
3365      ComputeCurrentValue();
3366    }
3367
3368    void ComputeCurrentValue() {
3369      if (!AtEnd())
3370        current_value_ = ParamType(*current1_, *current2_, *current3_);
3371    }
3372    bool AtEnd() const {
3373      // We must report iterator past the end of the range when either of the
3374      // component iterators has reached the end of its range.
3375      return
3376          current1_ == end1_ ||
3377          current2_ == end2_ ||
3378          current3_ == end3_;
3379    }
3380
3381    // No implementation - assignment is unsupported.
3382    void operator=(const Iterator& other);
3383
3384    const ParamGeneratorInterface<ParamType>* const base_;
3385    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
3386    // current[i]_ is the actual traversing iterator.
3387    const typename ParamGenerator<T1>::iterator begin1_;
3388    const typename ParamGenerator<T1>::iterator end1_;
3389    typename ParamGenerator<T1>::iterator current1_;
3390    const typename ParamGenerator<T2>::iterator begin2_;
3391    const typename ParamGenerator<T2>::iterator end2_;
3392    typename ParamGenerator<T2>::iterator current2_;
3393    const typename ParamGenerator<T3>::iterator begin3_;
3394    const typename ParamGenerator<T3>::iterator end3_;
3395    typename ParamGenerator<T3>::iterator current3_;
3396    ParamType current_value_;
3397  };  // class CartesianProductGenerator3::Iterator
3398
3399  // No implementation - assignment is unsupported.
3400  void operator=(const CartesianProductGenerator3& other);
3401
3402  const ParamGenerator<T1> g1_;
3403  const ParamGenerator<T2> g2_;
3404  const ParamGenerator<T3> g3_;
3405};  // class CartesianProductGenerator3
3406
3407
3408template <typename T1, typename T2, typename T3, typename T4>
3409class CartesianProductGenerator4
3410    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4> > {
3411 public:
3412  typedef ::testing::tuple<T1, T2, T3, T4> ParamType;
3413
3414  CartesianProductGenerator4(const ParamGenerator<T1>& g1,
3415      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3,
3416      const ParamGenerator<T4>& g4)
3417      : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {}
3418  virtual ~CartesianProductGenerator4() {}
3419
3420  virtual ParamIteratorInterface<ParamType>* Begin() const {
3421    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
3422        g3_.begin(), g4_, g4_.begin());
3423  }
3424  virtual ParamIteratorInterface<ParamType>* End() const {
3425    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(),
3426        g4_, g4_.end());
3427  }
3428
3429 private:
3430  class Iterator : public ParamIteratorInterface<ParamType> {
3431   public:
3432    Iterator(const ParamGeneratorInterface<ParamType>* base,
3433      const ParamGenerator<T1>& g1,
3434      const typename ParamGenerator<T1>::iterator& current1,
3435      const ParamGenerator<T2>& g2,
3436      const typename ParamGenerator<T2>::iterator& current2,
3437      const ParamGenerator<T3>& g3,
3438      const typename ParamGenerator<T3>::iterator& current3,
3439      const ParamGenerator<T4>& g4,
3440      const typename ParamGenerator<T4>::iterator& current4)
3441        : base_(base),
3442          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
3443          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
3444          begin3_(g3.begin()), end3_(g3.end()), current3_(current3),
3445          begin4_(g4.begin()), end4_(g4.end()), current4_(current4)    {
3446      ComputeCurrentValue();
3447    }
3448    virtual ~Iterator() {}
3449
3450    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
3451      return base_;
3452    }
3453    // Advance should not be called on beyond-of-range iterators
3454    // so no component iterators must be beyond end of range, either.
3455    virtual void Advance() {
3456      assert(!AtEnd());
3457      ++current4_;
3458      if (current4_ == end4_) {
3459        current4_ = begin4_;
3460        ++current3_;
3461      }
3462      if (current3_ == end3_) {
3463        current3_ = begin3_;
3464        ++current2_;
3465      }
3466      if (current2_ == end2_) {
3467        current2_ = begin2_;
3468        ++current1_;
3469      }
3470      ComputeCurrentValue();
3471    }
3472    virtual ParamIteratorInterface<ParamType>* Clone() const {
3473      return new Iterator(*this);
3474    }
3475    virtual const ParamType* Current() const { return &current_value_; }
3476    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
3477      // Having the same base generator guarantees that the other
3478      // iterator is of the same type and we can downcast.
3479      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
3480          << "The program attempted to compare iterators "
3481          << "from different generators." << std::endl;
3482      const Iterator* typed_other =
3483          CheckedDowncastToActualType<const Iterator>(&other);
3484      // We must report iterators equal if they both point beyond their
3485      // respective ranges. That can happen in a variety of fashions,
3486      // so we have to consult AtEnd().
3487      return (AtEnd() && typed_other->AtEnd()) ||
3488         (
3489          current1_ == typed_other->current1_ &&
3490          current2_ == typed_other->current2_ &&
3491          current3_ == typed_other->current3_ &&
3492          current4_ == typed_other->current4_);
3493    }
3494
3495   private:
3496    Iterator(const Iterator& other)
3497        : base_(other.base_),
3498        begin1_(other.begin1_),
3499        end1_(other.end1_),
3500        current1_(other.current1_),
3501        begin2_(other.begin2_),
3502        end2_(other.end2_),
3503        current2_(other.current2_),
3504        begin3_(other.begin3_),
3505        end3_(other.end3_),
3506        current3_(other.current3_),
3507        begin4_(other.begin4_),
3508        end4_(other.end4_),
3509        current4_(other.current4_) {
3510      ComputeCurrentValue();
3511    }
3512
3513    void ComputeCurrentValue() {
3514      if (!AtEnd())
3515        current_value_ = ParamType(*current1_, *current2_, *current3_,
3516            *current4_);
3517    }
3518    bool AtEnd() const {
3519      // We must report iterator past the end of the range when either of the
3520      // component iterators has reached the end of its range.
3521      return
3522          current1_ == end1_ ||
3523          current2_ == end2_ ||
3524          current3_ == end3_ ||
3525          current4_ == end4_;
3526    }
3527
3528    // No implementation - assignment is unsupported.
3529    void operator=(const Iterator& other);
3530
3531    const ParamGeneratorInterface<ParamType>* const base_;
3532    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
3533    // current[i]_ is the actual traversing iterator.
3534    const typename ParamGenerator<T1>::iterator begin1_;
3535    const typename ParamGenerator<T1>::iterator end1_;
3536    typename ParamGenerator<T1>::iterator current1_;
3537    const typename ParamGenerator<T2>::iterator begin2_;
3538    const typename ParamGenerator<T2>::iterator end2_;
3539    typename ParamGenerator<T2>::iterator current2_;
3540    const typename ParamGenerator<T3>::iterator begin3_;
3541    const typename ParamGenerator<T3>::iterator end3_;
3542    typename ParamGenerator<T3>::iterator current3_;
3543    const typename ParamGenerator<T4>::iterator begin4_;
3544    const typename ParamGenerator<T4>::iterator end4_;
3545    typename ParamGenerator<T4>::iterator current4_;
3546    ParamType current_value_;
3547  };  // class CartesianProductGenerator4::Iterator
3548
3549  // No implementation - assignment is unsupported.
3550  void operator=(const CartesianProductGenerator4& other);
3551
3552  const ParamGenerator<T1> g1_;
3553  const ParamGenerator<T2> g2_;
3554  const ParamGenerator<T3> g3_;
3555  const ParamGenerator<T4> g4_;
3556};  // class CartesianProductGenerator4
3557
3558
3559template <typename T1, typename T2, typename T3, typename T4, typename T5>
3560class CartesianProductGenerator5
3561    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5> > {
3562 public:
3563  typedef ::testing::tuple<T1, T2, T3, T4, T5> ParamType;
3564
3565  CartesianProductGenerator5(const ParamGenerator<T1>& g1,
3566      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3,
3567      const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5)
3568      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {}
3569  virtual ~CartesianProductGenerator5() {}
3570
3571  virtual ParamIteratorInterface<ParamType>* Begin() const {
3572    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
3573        g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin());
3574  }
3575  virtual ParamIteratorInterface<ParamType>* End() const {
3576    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(),
3577        g4_, g4_.end(), g5_, g5_.end());
3578  }
3579
3580 private:
3581  class Iterator : public ParamIteratorInterface<ParamType> {
3582   public:
3583    Iterator(const ParamGeneratorInterface<ParamType>* base,
3584      const ParamGenerator<T1>& g1,
3585      const typename ParamGenerator<T1>::iterator& current1,
3586      const ParamGenerator<T2>& g2,
3587      const typename ParamGenerator<T2>::iterator& current2,
3588      const ParamGenerator<T3>& g3,
3589      const typename ParamGenerator<T3>::iterator& current3,
3590      const ParamGenerator<T4>& g4,
3591      const typename ParamGenerator<T4>::iterator& current4,
3592      const ParamGenerator<T5>& g5,
3593      const typename ParamGenerator<T5>::iterator& current5)
3594        : base_(base),
3595          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
3596          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
3597          begin3_(g3.begin()), end3_(g3.end()), current3_(current3),
3598          begin4_(g4.begin()), end4_(g4.end()), current4_(current4),
3599          begin5_(g5.begin()), end5_(g5.end()), current5_(current5)    {
3600      ComputeCurrentValue();
3601    }
3602    virtual ~Iterator() {}
3603
3604    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
3605      return base_;
3606    }
3607    // Advance should not be called on beyond-of-range iterators
3608    // so no component iterators must be beyond end of range, either.
3609    virtual void Advance() {
3610      assert(!AtEnd());
3611      ++current5_;
3612      if (current5_ == end5_) {
3613        current5_ = begin5_;
3614        ++current4_;
3615      }
3616      if (current4_ == end4_) {
3617        current4_ = begin4_;
3618        ++current3_;
3619      }
3620      if (current3_ == end3_) {
3621        current3_ = begin3_;
3622        ++current2_;
3623      }
3624      if (current2_ == end2_) {
3625        current2_ = begin2_;
3626        ++current1_;
3627      }
3628      ComputeCurrentValue();
3629    }
3630    virtual ParamIteratorInterface<ParamType>* Clone() const {
3631      return new Iterator(*this);
3632    }
3633    virtual const ParamType* Current() const { return &current_value_; }
3634    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
3635      // Having the same base generator guarantees that the other
3636      // iterator is of the same type and we can downcast.
3637      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
3638          << "The program attempted to compare iterators "
3639          << "from different generators." << std::endl;
3640      const Iterator* typed_other =
3641          CheckedDowncastToActualType<const Iterator>(&other);
3642      // We must report iterators equal if they both point beyond their
3643      // respective ranges. That can happen in a variety of fashions,
3644      // so we have to consult AtEnd().
3645      return (AtEnd() && typed_other->AtEnd()) ||
3646         (
3647          current1_ == typed_other->current1_ &&
3648          current2_ == typed_other->current2_ &&
3649          current3_ == typed_other->current3_ &&
3650          current4_ == typed_other->current4_ &&
3651          current5_ == typed_other->current5_);
3652    }
3653
3654   private:
3655    Iterator(const Iterator& other)
3656        : base_(other.base_),
3657        begin1_(other.begin1_),
3658        end1_(other.end1_),
3659        current1_(other.current1_),
3660        begin2_(other.begin2_),
3661        end2_(other.end2_),
3662        current2_(other.current2_),
3663        begin3_(other.begin3_),
3664        end3_(other.end3_),
3665        current3_(other.current3_),
3666        begin4_(other.begin4_),
3667        end4_(other.end4_),
3668        current4_(other.current4_),
3669        begin5_(other.begin5_),
3670        end5_(other.end5_),
3671        current5_(other.current5_) {
3672      ComputeCurrentValue();
3673    }
3674
3675    void ComputeCurrentValue() {
3676      if (!AtEnd())
3677        current_value_ = ParamType(*current1_, *current2_, *current3_,
3678            *current4_, *current5_);
3679    }
3680    bool AtEnd() const {
3681      // We must report iterator past the end of the range when either of the
3682      // component iterators has reached the end of its range.
3683      return
3684          current1_ == end1_ ||
3685          current2_ == end2_ ||
3686          current3_ == end3_ ||
3687          current4_ == end4_ ||
3688          current5_ == end5_;
3689    }
3690
3691    // No implementation - assignment is unsupported.
3692    void operator=(const Iterator& other);
3693
3694    const ParamGeneratorInterface<ParamType>* const base_;
3695    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
3696    // current[i]_ is the actual traversing iterator.
3697    const typename ParamGenerator<T1>::iterator begin1_;
3698    const typename ParamGenerator<T1>::iterator end1_;
3699    typename ParamGenerator<T1>::iterator current1_;
3700    const typename ParamGenerator<T2>::iterator begin2_;
3701    const typename ParamGenerator<T2>::iterator end2_;
3702    typename ParamGenerator<T2>::iterator current2_;
3703    const typename ParamGenerator<T3>::iterator begin3_;
3704    const typename ParamGenerator<T3>::iterator end3_;
3705    typename ParamGenerator<T3>::iterator current3_;
3706    const typename ParamGenerator<T4>::iterator begin4_;
3707    const typename ParamGenerator<T4>::iterator end4_;
3708    typename ParamGenerator<T4>::iterator current4_;
3709    const typename ParamGenerator<T5>::iterator begin5_;
3710    const typename ParamGenerator<T5>::iterator end5_;
3711    typename ParamGenerator<T5>::iterator current5_;
3712    ParamType current_value_;
3713  };  // class CartesianProductGenerator5::Iterator
3714
3715  // No implementation - assignment is unsupported.
3716  void operator=(const CartesianProductGenerator5& other);
3717
3718  const ParamGenerator<T1> g1_;
3719  const ParamGenerator<T2> g2_;
3720  const ParamGenerator<T3> g3_;
3721  const ParamGenerator<T4> g4_;
3722  const ParamGenerator<T5> g5_;
3723};  // class CartesianProductGenerator5
3724
3725
3726template <typename T1, typename T2, typename T3, typename T4, typename T5,
3727    typename T6>
3728class CartesianProductGenerator6
3729    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5,
3730        T6> > {
3731 public:
3732  typedef ::testing::tuple<T1, T2, T3, T4, T5, T6> ParamType;
3733
3734  CartesianProductGenerator6(const ParamGenerator<T1>& g1,
3735      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3,
3736      const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5,
3737      const ParamGenerator<T6>& g6)
3738      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {}
3739  virtual ~CartesianProductGenerator6() {}
3740
3741  virtual ParamIteratorInterface<ParamType>* Begin() const {
3742    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
3743        g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin());
3744  }
3745  virtual ParamIteratorInterface<ParamType>* End() const {
3746    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(),
3747        g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end());
3748  }
3749
3750 private:
3751  class Iterator : public ParamIteratorInterface<ParamType> {
3752   public:
3753    Iterator(const ParamGeneratorInterface<ParamType>* base,
3754      const ParamGenerator<T1>& g1,
3755      const typename ParamGenerator<T1>::iterator& current1,
3756      const ParamGenerator<T2>& g2,
3757      const typename ParamGenerator<T2>::iterator& current2,
3758      const ParamGenerator<T3>& g3,
3759      const typename ParamGenerator<T3>::iterator& current3,
3760      const ParamGenerator<T4>& g4,
3761      const typename ParamGenerator<T4>::iterator& current4,
3762      const ParamGenerator<T5>& g5,
3763      const typename ParamGenerator<T5>::iterator& current5,
3764      const ParamGenerator<T6>& g6,
3765      const typename ParamGenerator<T6>::iterator& current6)
3766        : base_(base),
3767          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
3768          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
3769          begin3_(g3.begin()), end3_(g3.end()), current3_(current3),
3770          begin4_(g4.begin()), end4_(g4.end()), current4_(current4),
3771          begin5_(g5.begin()), end5_(g5.end()), current5_(current5),
3772          begin6_(g6.begin()), end6_(g6.end()), current6_(current6)    {
3773      ComputeCurrentValue();
3774    }
3775    virtual ~Iterator() {}
3776
3777    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
3778      return base_;
3779    }
3780    // Advance should not be called on beyond-of-range iterators
3781    // so no component iterators must be beyond end of range, either.
3782    virtual void Advance() {
3783      assert(!AtEnd());
3784      ++current6_;
3785      if (current6_ == end6_) {
3786        current6_ = begin6_;
3787        ++current5_;
3788      }
3789      if (current5_ == end5_) {
3790        current5_ = begin5_;
3791        ++current4_;
3792      }
3793      if (current4_ == end4_) {
3794        current4_ = begin4_;
3795        ++current3_;
3796      }
3797      if (current3_ == end3_) {
3798        current3_ = begin3_;
3799        ++current2_;
3800      }
3801      if (current2_ == end2_) {
3802        current2_ = begin2_;
3803        ++current1_;
3804      }
3805      ComputeCurrentValue();
3806    }
3807    virtual ParamIteratorInterface<ParamType>* Clone() const {
3808      return new Iterator(*this);
3809    }
3810    virtual const ParamType* Current() const { return &current_value_; }
3811    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
3812      // Having the same base generator guarantees that the other
3813      // iterator is of the same type and we can downcast.
3814      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
3815          << "The program attempted to compare iterators "
3816          << "from different generators." << std::endl;
3817      const Iterator* typed_other =
3818          CheckedDowncastToActualType<const Iterator>(&other);
3819      // We must report iterators equal if they both point beyond their
3820      // respective ranges. That can happen in a variety of fashions,
3821      // so we have to consult AtEnd().
3822      return (AtEnd() && typed_other->AtEnd()) ||
3823         (
3824          current1_ == typed_other->current1_ &&
3825          current2_ == typed_other->current2_ &&
3826          current3_ == typed_other->current3_ &&
3827          current4_ == typed_other->current4_ &&
3828          current5_ == typed_other->current5_ &&
3829          current6_ == typed_other->current6_);
3830    }
3831
3832   private:
3833    Iterator(const Iterator& other)
3834        : base_(other.base_),
3835        begin1_(other.begin1_),
3836        end1_(other.end1_),
3837        current1_(other.current1_),
3838        begin2_(other.begin2_),
3839        end2_(other.end2_),
3840        current2_(other.current2_),
3841        begin3_(other.begin3_),
3842        end3_(other.end3_),
3843        current3_(other.current3_),
3844        begin4_(other.begin4_),
3845        end4_(other.end4_),
3846        current4_(other.current4_),
3847        begin5_(other.begin5_),
3848        end5_(other.end5_),
3849        current5_(other.current5_),
3850        begin6_(other.begin6_),
3851        end6_(other.end6_),
3852        current6_(other.current6_) {
3853      ComputeCurrentValue();
3854    }
3855
3856    void ComputeCurrentValue() {
3857      if (!AtEnd())
3858        current_value_ = ParamType(*current1_, *current2_, *current3_,
3859            *current4_, *current5_, *current6_);
3860    }
3861    bool AtEnd() const {
3862      // We must report iterator past the end of the range when either of the
3863      // component iterators has reached the end of its range.
3864      return
3865          current1_ == end1_ ||
3866          current2_ == end2_ ||
3867          current3_ == end3_ ||
3868          current4_ == end4_ ||
3869          current5_ == end5_ ||
3870          current6_ == end6_;
3871    }
3872
3873    // No implementation - assignment is unsupported.
3874    void operator=(const Iterator& other);
3875
3876    const ParamGeneratorInterface<ParamType>* const base_;
3877    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
3878    // current[i]_ is the actual traversing iterator.
3879    const typename ParamGenerator<T1>::iterator begin1_;
3880    const typename ParamGenerator<T1>::iterator end1_;
3881    typename ParamGenerator<T1>::iterator current1_;
3882    const typename ParamGenerator<T2>::iterator begin2_;
3883    const typename ParamGenerator<T2>::iterator end2_;
3884    typename ParamGenerator<T2>::iterator current2_;
3885    const typename ParamGenerator<T3>::iterator begin3_;
3886    const typename ParamGenerator<T3>::iterator end3_;
3887    typename ParamGenerator<T3>::iterator current3_;
3888    const typename ParamGenerator<T4>::iterator begin4_;
3889    const typename ParamGenerator<T4>::iterator end4_;
3890    typename ParamGenerator<T4>::iterator current4_;
3891    const typename ParamGenerator<T5>::iterator begin5_;
3892    const typename ParamGenerator<T5>::iterator end5_;
3893    typename ParamGenerator<T5>::iterator current5_;
3894    const typename ParamGenerator<T6>::iterator begin6_;
3895    const typename ParamGenerator<T6>::iterator end6_;
3896    typename ParamGenerator<T6>::iterator current6_;
3897    ParamType current_value_;
3898  };  // class CartesianProductGenerator6::Iterator
3899
3900  // No implementation - assignment is unsupported.
3901  void operator=(const CartesianProductGenerator6& other);
3902
3903  const ParamGenerator<T1> g1_;
3904  const ParamGenerator<T2> g2_;
3905  const ParamGenerator<T3> g3_;
3906  const ParamGenerator<T4> g4_;
3907  const ParamGenerator<T5> g5_;
3908  const ParamGenerator<T6> g6_;
3909};  // class CartesianProductGenerator6
3910
3911
3912template <typename T1, typename T2, typename T3, typename T4, typename T5,
3913    typename T6, typename T7>
3914class CartesianProductGenerator7
3915    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6,
3916        T7> > {
3917 public:
3918  typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> ParamType;
3919
3920  CartesianProductGenerator7(const ParamGenerator<T1>& g1,
3921      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3,
3922      const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5,
3923      const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7)
3924      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {}
3925  virtual ~CartesianProductGenerator7() {}
3926
3927  virtual ParamIteratorInterface<ParamType>* Begin() const {
3928    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
3929        g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_,
3930        g7_.begin());
3931  }
3932  virtual ParamIteratorInterface<ParamType>* End() const {
3933    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(),
3934        g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end());
3935  }
3936
3937 private:
3938  class Iterator : public ParamIteratorInterface<ParamType> {
3939   public:
3940    Iterator(const ParamGeneratorInterface<ParamType>* base,
3941      const ParamGenerator<T1>& g1,
3942      const typename ParamGenerator<T1>::iterator& current1,
3943      const ParamGenerator<T2>& g2,
3944      const typename ParamGenerator<T2>::iterator& current2,
3945      const ParamGenerator<T3>& g3,
3946      const typename ParamGenerator<T3>::iterator& current3,
3947      const ParamGenerator<T4>& g4,
3948      const typename ParamGenerator<T4>::iterator& current4,
3949      const ParamGenerator<T5>& g5,
3950      const typename ParamGenerator<T5>::iterator& current5,
3951      const ParamGenerator<T6>& g6,
3952      const typename ParamGenerator<T6>::iterator& current6,
3953      const ParamGenerator<T7>& g7,
3954      const typename ParamGenerator<T7>::iterator& current7)
3955        : base_(base),
3956          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
3957          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
3958          begin3_(g3.begin()), end3_(g3.end()), current3_(current3),
3959          begin4_(g4.begin()), end4_(g4.end()), current4_(current4),
3960          begin5_(g5.begin()), end5_(g5.end()), current5_(current5),
3961          begin6_(g6.begin()), end6_(g6.end()), current6_(current6),
3962          begin7_(g7.begin()), end7_(g7.end()), current7_(current7)    {
3963      ComputeCurrentValue();
3964    }
3965    virtual ~Iterator() {}
3966
3967    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
3968      return base_;
3969    }
3970    // Advance should not be called on beyond-of-range iterators
3971    // so no component iterators must be beyond end of range, either.
3972    virtual void Advance() {
3973      assert(!AtEnd());
3974      ++current7_;
3975      if (current7_ == end7_) {
3976        current7_ = begin7_;
3977        ++current6_;
3978      }
3979      if (current6_ == end6_) {
3980        current6_ = begin6_;
3981        ++current5_;
3982      }
3983      if (current5_ == end5_) {
3984        current5_ = begin5_;
3985        ++current4_;
3986      }
3987      if (current4_ == end4_) {
3988        current4_ = begin4_;
3989        ++current3_;
3990      }
3991      if (current3_ == end3_) {
3992        current3_ = begin3_;
3993        ++current2_;
3994      }
3995      if (current2_ == end2_) {
3996        current2_ = begin2_;
3997        ++current1_;
3998      }
3999      ComputeCurrentValue();
4000    }
4001    virtual ParamIteratorInterface<ParamType>* Clone() const {
4002      return new Iterator(*this);
4003    }
4004    virtual const ParamType* Current() const { return &current_value_; }
4005    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
4006      // Having the same base generator guarantees that the other
4007      // iterator is of the same type and we can downcast.
4008      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
4009          << "The program attempted to compare iterators "
4010          << "from different generators." << std::endl;
4011      const Iterator* typed_other =
4012          CheckedDowncastToActualType<const Iterator>(&other);
4013      // We must report iterators equal if they both point beyond their
4014      // respective ranges. That can happen in a variety of fashions,
4015      // so we have to consult AtEnd().
4016      return (AtEnd() && typed_other->AtEnd()) ||
4017         (
4018          current1_ == typed_other->current1_ &&
4019          current2_ == typed_other->current2_ &&
4020          current3_ == typed_other->current3_ &&
4021          current4_ == typed_other->current4_ &&
4022          current5_ == typed_other->current5_ &&
4023          current6_ == typed_other->current6_ &&
4024          current7_ == typed_other->current7_);
4025    }
4026
4027   private:
4028    Iterator(const Iterator& other)
4029        : base_(other.base_),
4030        begin1_(other.begin1_),
4031        end1_(other.end1_),
4032        current1_(other.current1_),
4033        begin2_(other.begin2_),
4034        end2_(other.end2_),
4035        current2_(other.current2_),
4036        begin3_(other.begin3_),
4037        end3_(other.end3_),
4038        current3_(other.current3_),
4039        begin4_(other.begin4_),
4040        end4_(other.end4_),
4041        current4_(other.current4_),
4042        begin5_(other.begin5_),
4043        end5_(other.end5_),
4044        current5_(other.current5_),
4045        begin6_(other.begin6_),
4046        end6_(other.end6_),
4047        current6_(other.current6_),
4048        begin7_(other.begin7_),
4049        end7_(other.end7_),
4050        current7_(other.current7_) {
4051      ComputeCurrentValue();
4052    }
4053
4054    void ComputeCurrentValue() {
4055      if (!AtEnd())
4056        current_value_ = ParamType(*current1_, *current2_, *current3_,
4057            *current4_, *current5_, *current6_, *current7_);
4058    }
4059    bool AtEnd() const {
4060      // We must report iterator past the end of the range when either of the
4061      // component iterators has reached the end of its range.
4062      return
4063          current1_ == end1_ ||
4064          current2_ == end2_ ||
4065          current3_ == end3_ ||
4066          current4_ == end4_ ||
4067          current5_ == end5_ ||
4068          current6_ == end6_ ||
4069          current7_ == end7_;
4070    }
4071
4072    // No implementation - assignment is unsupported.
4073    void operator=(const Iterator& other);
4074
4075    const ParamGeneratorInterface<ParamType>* const base_;
4076    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
4077    // current[i]_ is the actual traversing iterator.
4078    const typename ParamGenerator<T1>::iterator begin1_;
4079    const typename ParamGenerator<T1>::iterator end1_;
4080    typename ParamGenerator<T1>::iterator current1_;
4081    const typename ParamGenerator<T2>::iterator begin2_;
4082    const typename ParamGenerator<T2>::iterator end2_;
4083    typename ParamGenerator<T2>::iterator current2_;
4084    const typename ParamGenerator<T3>::iterator begin3_;
4085    const typename ParamGenerator<T3>::iterator end3_;
4086    typename ParamGenerator<T3>::iterator current3_;
4087    const typename ParamGenerator<T4>::iterator begin4_;
4088    const typename ParamGenerator<T4>::iterator end4_;
4089    typename ParamGenerator<T4>::iterator current4_;
4090    const typename ParamGenerator<T5>::iterator begin5_;
4091    const typename ParamGenerator<T5>::iterator end5_;
4092    typename ParamGenerator<T5>::iterator current5_;
4093    const typename ParamGenerator<T6>::iterator begin6_;
4094    const typename ParamGenerator<T6>::iterator end6_;
4095    typename ParamGenerator<T6>::iterator current6_;
4096    const typename ParamGenerator<T7>::iterator begin7_;
4097    const typename ParamGenerator<T7>::iterator end7_;
4098    typename ParamGenerator<T7>::iterator current7_;
4099    ParamType current_value_;
4100  };  // class CartesianProductGenerator7::Iterator
4101
4102  // No implementation - assignment is unsupported.
4103  void operator=(const CartesianProductGenerator7& other);
4104
4105  const ParamGenerator<T1> g1_;
4106  const ParamGenerator<T2> g2_;
4107  const ParamGenerator<T3> g3_;
4108  const ParamGenerator<T4> g4_;
4109  const ParamGenerator<T5> g5_;
4110  const ParamGenerator<T6> g6_;
4111  const ParamGenerator<T7> g7_;
4112};  // class CartesianProductGenerator7
4113
4114
4115template <typename T1, typename T2, typename T3, typename T4, typename T5,
4116    typename T6, typename T7, typename T8>
4117class CartesianProductGenerator8
4118    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6,
4119        T7, T8> > {
4120 public:
4121  typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> ParamType;
4122
4123  CartesianProductGenerator8(const ParamGenerator<T1>& g1,
4124      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3,
4125      const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5,
4126      const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7,
4127      const ParamGenerator<T8>& g8)
4128      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7),
4129          g8_(g8) {}
4130  virtual ~CartesianProductGenerator8() {}
4131
4132  virtual ParamIteratorInterface<ParamType>* Begin() const {
4133    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
4134        g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_,
4135        g7_.begin(), g8_, g8_.begin());
4136  }
4137  virtual ParamIteratorInterface<ParamType>* End() const {
4138    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(),
4139        g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_,
4140        g8_.end());
4141  }
4142
4143 private:
4144  class Iterator : public ParamIteratorInterface<ParamType> {
4145   public:
4146    Iterator(const ParamGeneratorInterface<ParamType>* base,
4147      const ParamGenerator<T1>& g1,
4148      const typename ParamGenerator<T1>::iterator& current1,
4149      const ParamGenerator<T2>& g2,
4150      const typename ParamGenerator<T2>::iterator& current2,
4151      const ParamGenerator<T3>& g3,
4152      const typename ParamGenerator<T3>::iterator& current3,
4153      const ParamGenerator<T4>& g4,
4154      const typename ParamGenerator<T4>::iterator& current4,
4155      const ParamGenerator<T5>& g5,
4156      const typename ParamGenerator<T5>::iterator& current5,
4157      const ParamGenerator<T6>& g6,
4158      const typename ParamGenerator<T6>::iterator& current6,
4159      const ParamGenerator<T7>& g7,
4160      const typename ParamGenerator<T7>::iterator& current7,
4161      const ParamGenerator<T8>& g8,
4162      const typename ParamGenerator<T8>::iterator& current8)
4163        : base_(base),
4164          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
4165          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
4166          begin3_(g3.begin()), end3_(g3.end()), current3_(current3),
4167          begin4_(g4.begin()), end4_(g4.end()), current4_(current4),
4168          begin5_(g5.begin()), end5_(g5.end()), current5_(current5),
4169          begin6_(g6.begin()), end6_(g6.end()), current6_(current6),
4170          begin7_(g7.begin()), end7_(g7.end()), current7_(current7),
4171          begin8_(g8.begin()), end8_(g8.end()), current8_(current8)    {
4172      ComputeCurrentValue();
4173    }
4174    virtual ~Iterator() {}
4175
4176    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
4177      return base_;
4178    }
4179    // Advance should not be called on beyond-of-range iterators
4180    // so no component iterators must be beyond end of range, either.
4181    virtual void Advance() {
4182      assert(!AtEnd());
4183      ++current8_;
4184      if (current8_ == end8_) {
4185        current8_ = begin8_;
4186        ++current7_;
4187      }
4188      if (current7_ == end7_) {
4189        current7_ = begin7_;
4190        ++current6_;
4191      }
4192      if (current6_ == end6_) {
4193        current6_ = begin6_;
4194        ++current5_;
4195      }
4196      if (current5_ == end5_) {
4197        current5_ = begin5_;
4198        ++current4_;
4199      }
4200      if (current4_ == end4_) {
4201        current4_ = begin4_;
4202        ++current3_;
4203      }
4204      if (current3_ == end3_) {
4205        current3_ = begin3_;
4206        ++current2_;
4207      }
4208      if (current2_ == end2_) {
4209        current2_ = begin2_;
4210        ++current1_;
4211      }
4212      ComputeCurrentValue();
4213    }
4214    virtual ParamIteratorInterface<ParamType>* Clone() const {
4215      return new Iterator(*this);
4216    }
4217    virtual const ParamType* Current() const { return &current_value_; }
4218    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
4219      // Having the same base generator guarantees that the other
4220      // iterator is of the same type and we can downcast.
4221      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
4222          << "The program attempted to compare iterators "
4223          << "from different generators." << std::endl;
4224      const Iterator* typed_other =
4225          CheckedDowncastToActualType<const Iterator>(&other);
4226      // We must report iterators equal if they both point beyond their
4227      // respective ranges. That can happen in a variety of fashions,
4228      // so we have to consult AtEnd().
4229      return (AtEnd() && typed_other->AtEnd()) ||
4230         (
4231          current1_ == typed_other->current1_ &&
4232          current2_ == typed_other->current2_ &&
4233          current3_ == typed_other->current3_ &&
4234          current4_ == typed_other->current4_ &&
4235          current5_ == typed_other->current5_ &&
4236          current6_ == typed_other->current6_ &&
4237          current7_ == typed_other->current7_ &&
4238          current8_ == typed_other->current8_);
4239    }
4240
4241   private:
4242    Iterator(const Iterator& other)
4243        : base_(other.base_),
4244        begin1_(other.begin1_),
4245        end1_(other.end1_),
4246        current1_(other.current1_),
4247        begin2_(other.begin2_),
4248        end2_(other.end2_),
4249        current2_(other.current2_),
4250        begin3_(other.begin3_),
4251        end3_(other.end3_),
4252        current3_(other.current3_),
4253        begin4_(other.begin4_),
4254        end4_(other.end4_),
4255        current4_(other.current4_),
4256        begin5_(other.begin5_),
4257        end5_(other.end5_),
4258        current5_(other.current5_),
4259        begin6_(other.begin6_),
4260        end6_(other.end6_),
4261        current6_(other.current6_),
4262        begin7_(other.begin7_),
4263        end7_(other.end7_),
4264        current7_(other.current7_),
4265        begin8_(other.begin8_),
4266        end8_(other.end8_),
4267        current8_(other.current8_) {
4268      ComputeCurrentValue();
4269    }
4270
4271    void ComputeCurrentValue() {
4272      if (!AtEnd())
4273        current_value_ = ParamType(*current1_, *current2_, *current3_,
4274            *current4_, *current5_, *current6_, *current7_, *current8_);
4275    }
4276    bool AtEnd() const {
4277      // We must report iterator past the end of the range when either of the
4278      // component iterators has reached the end of its range.
4279      return
4280          current1_ == end1_ ||
4281          current2_ == end2_ ||
4282          current3_ == end3_ ||
4283          current4_ == end4_ ||
4284          current5_ == end5_ ||
4285          current6_ == end6_ ||
4286          current7_ == end7_ ||
4287          current8_ == end8_;
4288    }
4289
4290    // No implementation - assignment is unsupported.
4291    void operator=(const Iterator& other);
4292
4293    const ParamGeneratorInterface<ParamType>* const base_;
4294    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
4295    // current[i]_ is the actual traversing iterator.
4296    const typename ParamGenerator<T1>::iterator begin1_;
4297    const typename ParamGenerator<T1>::iterator end1_;
4298    typename ParamGenerator<T1>::iterator current1_;
4299    const typename ParamGenerator<T2>::iterator begin2_;
4300    const typename ParamGenerator<T2>::iterator end2_;
4301    typename ParamGenerator<T2>::iterator current2_;
4302    const typename ParamGenerator<T3>::iterator begin3_;
4303    const typename ParamGenerator<T3>::iterator end3_;
4304    typename ParamGenerator<T3>::iterator current3_;
4305    const typename ParamGenerator<T4>::iterator begin4_;
4306    const typename ParamGenerator<T4>::iterator end4_;
4307    typename ParamGenerator<T4>::iterator current4_;
4308    const typename ParamGenerator<T5>::iterator begin5_;
4309    const typename ParamGenerator<T5>::iterator end5_;
4310    typename ParamGenerator<T5>::iterator current5_;
4311    const typename ParamGenerator<T6>::iterator begin6_;
4312    const typename ParamGenerator<T6>::iterator end6_;
4313    typename ParamGenerator<T6>::iterator current6_;
4314    const typename ParamGenerator<T7>::iterator begin7_;
4315    const typename ParamGenerator<T7>::iterator end7_;
4316    typename ParamGenerator<T7>::iterator current7_;
4317    const typename ParamGenerator<T8>::iterator begin8_;
4318    const typename ParamGenerator<T8>::iterator end8_;
4319    typename ParamGenerator<T8>::iterator current8_;
4320    ParamType current_value_;
4321  };  // class CartesianProductGenerator8::Iterator
4322
4323  // No implementation - assignment is unsupported.
4324  void operator=(const CartesianProductGenerator8& other);
4325
4326  const ParamGenerator<T1> g1_;
4327  const ParamGenerator<T2> g2_;
4328  const ParamGenerator<T3> g3_;
4329  const ParamGenerator<T4> g4_;
4330  const ParamGenerator<T5> g5_;
4331  const ParamGenerator<T6> g6_;
4332  const ParamGenerator<T7> g7_;
4333  const ParamGenerator<T8> g8_;
4334};  // class CartesianProductGenerator8
4335
4336
4337template <typename T1, typename T2, typename T3, typename T4, typename T5,
4338    typename T6, typename T7, typename T8, typename T9>
4339class CartesianProductGenerator9
4340    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6,
4341        T7, T8, T9> > {
4342 public:
4343  typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> ParamType;
4344
4345  CartesianProductGenerator9(const ParamGenerator<T1>& g1,
4346      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3,
4347      const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5,
4348      const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7,
4349      const ParamGenerator<T8>& g8, const ParamGenerator<T9>& g9)
4350      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8),
4351          g9_(g9) {}
4352  virtual ~CartesianProductGenerator9() {}
4353
4354  virtual ParamIteratorInterface<ParamType>* Begin() const {
4355    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
4356        g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_,
4357        g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin());
4358  }
4359  virtual ParamIteratorInterface<ParamType>* End() const {
4360    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(),
4361        g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_,
4362        g8_.end(), g9_, g9_.end());
4363  }
4364
4365 private:
4366  class Iterator : public ParamIteratorInterface<ParamType> {
4367   public:
4368    Iterator(const ParamGeneratorInterface<ParamType>* base,
4369      const ParamGenerator<T1>& g1,
4370      const typename ParamGenerator<T1>::iterator& current1,
4371      const ParamGenerator<T2>& g2,
4372      const typename ParamGenerator<T2>::iterator& current2,
4373      const ParamGenerator<T3>& g3,
4374      const typename ParamGenerator<T3>::iterator& current3,
4375      const ParamGenerator<T4>& g4,
4376      const typename ParamGenerator<T4>::iterator& current4,
4377      const ParamGenerator<T5>& g5,
4378      const typename ParamGenerator<T5>::iterator& current5,
4379      const ParamGenerator<T6>& g6,
4380      const typename ParamGenerator<T6>::iterator& current6,
4381      const ParamGenerator<T7>& g7,
4382      const typename ParamGenerator<T7>::iterator& current7,
4383      const ParamGenerator<T8>& g8,
4384      const typename ParamGenerator<T8>::iterator& current8,
4385      const ParamGenerator<T9>& g9,
4386      const typename ParamGenerator<T9>::iterator& current9)
4387        : base_(base),
4388          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
4389          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
4390          begin3_(g3.begin()), end3_(g3.end()), current3_(current3),
4391          begin4_(g4.begin()), end4_(g4.end()), current4_(current4),
4392          begin5_(g5.begin()), end5_(g5.end()), current5_(current5),
4393          begin6_(g6.begin()), end6_(g6.end()), current6_(current6),
4394          begin7_(g7.begin()), end7_(g7.end()), current7_(current7),
4395          begin8_(g8.begin()), end8_(g8.end()), current8_(current8),
4396          begin9_(g9.begin()), end9_(g9.end()), current9_(current9)    {
4397      ComputeCurrentValue();
4398    }
4399    virtual ~Iterator() {}
4400
4401    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
4402      return base_;
4403    }
4404    // Advance should not be called on beyond-of-range iterators
4405    // so no component iterators must be beyond end of range, either.
4406    virtual void Advance() {
4407      assert(!AtEnd());
4408      ++current9_;
4409      if (current9_ == end9_) {
4410        current9_ = begin9_;
4411        ++current8_;
4412      }
4413      if (current8_ == end8_) {
4414        current8_ = begin8_;
4415        ++current7_;
4416      }
4417      if (current7_ == end7_) {
4418        current7_ = begin7_;
4419        ++current6_;
4420      }
4421      if (current6_ == end6_) {
4422        current6_ = begin6_;
4423        ++current5_;
4424      }
4425      if (current5_ == end5_) {
4426        current5_ = begin5_;
4427        ++current4_;
4428      }
4429      if (current4_ == end4_) {
4430        current4_ = begin4_;
4431        ++current3_;
4432      }
4433      if (current3_ == end3_) {
4434        current3_ = begin3_;
4435        ++current2_;
4436      }
4437      if (current2_ == end2_) {
4438        current2_ = begin2_;
4439        ++current1_;
4440      }
4441      ComputeCurrentValue();
4442    }
4443    virtual ParamIteratorInterface<ParamType>* Clone() const {
4444      return new Iterator(*this);
4445    }
4446    virtual const ParamType* Current() const { return &current_value_; }
4447    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
4448      // Having the same base generator guarantees that the other
4449      // iterator is of the same type and we can downcast.
4450      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
4451          << "The program attempted to compare iterators "
4452          << "from different generators." << std::endl;
4453      const Iterator* typed_other =
4454          CheckedDowncastToActualType<const Iterator>(&other);
4455      // We must report iterators equal if they both point beyond their
4456      // respective ranges. That can happen in a variety of fashions,
4457      // so we have to consult AtEnd().
4458      return (AtEnd() && typed_other->AtEnd()) ||
4459         (
4460          current1_ == typed_other->current1_ &&
4461          current2_ == typed_other->current2_ &&
4462          current3_ == typed_other->current3_ &&
4463          current4_ == typed_other->current4_ &&
4464          current5_ == typed_other->current5_ &&
4465          current6_ == typed_other->current6_ &&
4466          current7_ == typed_other->current7_ &&
4467          current8_ == typed_other->current8_ &&
4468          current9_ == typed_other->current9_);
4469    }
4470
4471   private:
4472    Iterator(const Iterator& other)
4473        : base_(other.base_),
4474        begin1_(other.begin1_),
4475        end1_(other.end1_),
4476        current1_(other.current1_),
4477        begin2_(other.begin2_),
4478        end2_(other.end2_),
4479        current2_(other.current2_),
4480        begin3_(other.begin3_),
4481        end3_(other.end3_),
4482        current3_(other.current3_),
4483        begin4_(other.begin4_),
4484        end4_(other.end4_),
4485        current4_(other.current4_),
4486        begin5_(other.begin5_),
4487        end5_(other.end5_),
4488        current5_(other.current5_),
4489        begin6_(other.begin6_),
4490        end6_(other.end6_),
4491        current6_(other.current6_),
4492        begin7_(other.begin7_),
4493        end7_(other.end7_),
4494        current7_(other.current7_),
4495        begin8_(other.begin8_),
4496        end8_(other.end8_),
4497        current8_(other.current8_),
4498        begin9_(other.begin9_),
4499        end9_(other.end9_),
4500        current9_(other.current9_) {
4501      ComputeCurrentValue();
4502    }
4503
4504    void ComputeCurrentValue() {
4505      if (!AtEnd())
4506        current_value_ = ParamType(*current1_, *current2_, *current3_,
4507            *current4_, *current5_, *current6_, *current7_, *current8_,
4508            *current9_);
4509    }
4510    bool AtEnd() const {
4511      // We must report iterator past the end of the range when either of the
4512      // component iterators has reached the end of its range.
4513      return
4514          current1_ == end1_ ||
4515          current2_ == end2_ ||
4516          current3_ == end3_ ||
4517          current4_ == end4_ ||
4518          current5_ == end5_ ||
4519          current6_ == end6_ ||
4520          current7_ == end7_ ||
4521          current8_ == end8_ ||
4522          current9_ == end9_;
4523    }
4524
4525    // No implementation - assignment is unsupported.
4526    void operator=(const Iterator& other);
4527
4528    const ParamGeneratorInterface<ParamType>* const base_;
4529    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
4530    // current[i]_ is the actual traversing iterator.
4531    const typename ParamGenerator<T1>::iterator begin1_;
4532    const typename ParamGenerator<T1>::iterator end1_;
4533    typename ParamGenerator<T1>::iterator current1_;
4534    const typename ParamGenerator<T2>::iterator begin2_;
4535    const typename ParamGenerator<T2>::iterator end2_;
4536    typename ParamGenerator<T2>::iterator current2_;
4537    const typename ParamGenerator<T3>::iterator begin3_;
4538    const typename ParamGenerator<T3>::iterator end3_;
4539    typename ParamGenerator<T3>::iterator current3_;
4540    const typename ParamGenerator<T4>::iterator begin4_;
4541    const typename ParamGenerator<T4>::iterator end4_;
4542    typename ParamGenerator<T4>::iterator current4_;
4543    const typename ParamGenerator<T5>::iterator begin5_;
4544    const typename ParamGenerator<T5>::iterator end5_;
4545    typename ParamGenerator<T5>::iterator current5_;
4546    const typename ParamGenerator<T6>::iterator begin6_;
4547    const typename ParamGenerator<T6>::iterator end6_;
4548    typename ParamGenerator<T6>::iterator current6_;
4549    const typename ParamGenerator<T7>::iterator begin7_;
4550    const typename ParamGenerator<T7>::iterator end7_;
4551    typename ParamGenerator<T7>::iterator current7_;
4552    const typename ParamGenerator<T8>::iterator begin8_;
4553    const typename ParamGenerator<T8>::iterator end8_;
4554    typename ParamGenerator<T8>::iterator current8_;
4555    const typename ParamGenerator<T9>::iterator begin9_;
4556    const typename ParamGenerator<T9>::iterator end9_;
4557    typename ParamGenerator<T9>::iterator current9_;
4558    ParamType current_value_;
4559  };  // class CartesianProductGenerator9::Iterator
4560
4561  // No implementation - assignment is unsupported.
4562  void operator=(const CartesianProductGenerator9& other);
4563
4564  const ParamGenerator<T1> g1_;
4565  const ParamGenerator<T2> g2_;
4566  const ParamGenerator<T3> g3_;
4567  const ParamGenerator<T4> g4_;
4568  const ParamGenerator<T5> g5_;
4569  const ParamGenerator<T6> g6_;
4570  const ParamGenerator<T7> g7_;
4571  const ParamGenerator<T8> g8_;
4572  const ParamGenerator<T9> g9_;
4573};  // class CartesianProductGenerator9
4574
4575
4576template <typename T1, typename T2, typename T3, typename T4, typename T5,
4577    typename T6, typename T7, typename T8, typename T9, typename T10>
4578class CartesianProductGenerator10
4579    : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6,
4580        T7, T8, T9, T10> > {
4581 public:
4582  typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> ParamType;
4583
4584  CartesianProductGenerator10(const ParamGenerator<T1>& g1,
4585      const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3,
4586      const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5,
4587      const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7,
4588      const ParamGenerator<T8>& g8, const ParamGenerator<T9>& g9,
4589      const ParamGenerator<T10>& g10)
4590      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8),
4591          g9_(g9), g10_(g10) {}
4592  virtual ~CartesianProductGenerator10() {}
4593
4594  virtual ParamIteratorInterface<ParamType>* Begin() const {
4595    return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_,
4596        g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_,
4597        g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin());
4598  }
4599  virtual ParamIteratorInterface<ParamType>* End() const {
4600    return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(),
4601        g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_,
4602        g8_.end(), g9_, g9_.end(), g10_, g10_.end());
4603  }
4604
4605 private:
4606  class Iterator : public ParamIteratorInterface<ParamType> {
4607   public:
4608    Iterator(const ParamGeneratorInterface<ParamType>* base,
4609      const ParamGenerator<T1>& g1,
4610      const typename ParamGenerator<T1>::iterator& current1,
4611      const ParamGenerator<T2>& g2,
4612      const typename ParamGenerator<T2>::iterator& current2,
4613      const ParamGenerator<T3>& g3,
4614      const typename ParamGenerator<T3>::iterator& current3,
4615      const ParamGenerator<T4>& g4,
4616      const typename ParamGenerator<T4>::iterator& current4,
4617      const ParamGenerator<T5>& g5,
4618      const typename ParamGenerator<T5>::iterator& current5,
4619      const ParamGenerator<T6>& g6,
4620      const typename ParamGenerator<T6>::iterator& current6,
4621      const ParamGenerator<T7>& g7,
4622      const typename ParamGenerator<T7>::iterator& current7,
4623      const ParamGenerator<T8>& g8,
4624      const typename ParamGenerator<T8>::iterator& current8,
4625      const ParamGenerator<T9>& g9,
4626      const typename ParamGenerator<T9>::iterator& current9,
4627      const ParamGenerator<T10>& g10,
4628      const typename ParamGenerator<T10>::iterator& current10)
4629        : base_(base),
4630          begin1_(g1.begin()), end1_(g1.end()), current1_(current1),
4631          begin2_(g2.begin()), end2_(g2.end()), current2_(current2),
4632          begin3_(g3.begin()), end3_(g3.end()), current3_(current3),
4633          begin4_(g4.begin()), end4_(g4.end()), current4_(current4),
4634          begin5_(g5.begin()), end5_(g5.end()), current5_(current5),
4635          begin6_(g6.begin()), end6_(g6.end()), current6_(current6),
4636          begin7_(g7.begin()), end7_(g7.end()), current7_(current7),
4637          begin8_(g8.begin()), end8_(g8.end()), current8_(current8),
4638          begin9_(g9.begin()), end9_(g9.end()), current9_(current9),
4639          begin10_(g10.begin()), end10_(g10.end()), current10_(current10)    {
4640      ComputeCurrentValue();
4641    }
4642    virtual ~Iterator() {}
4643
4644    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
4645      return base_;
4646    }
4647    // Advance should not be called on beyond-of-range iterators
4648    // so no component iterators must be beyond end of range, either.
4649    virtual void Advance() {
4650      assert(!AtEnd());
4651      ++current10_;
4652      if (current10_ == end10_) {
4653        current10_ = begin10_;
4654        ++current9_;
4655      }
4656      if (current9_ == end9_) {
4657        current9_ = begin9_;
4658        ++current8_;
4659      }
4660      if (current8_ == end8_) {
4661        current8_ = begin8_;
4662        ++current7_;
4663      }
4664      if (current7_ == end7_) {
4665        current7_ = begin7_;
4666        ++current6_;
4667      }
4668      if (current6_ == end6_) {
4669        current6_ = begin6_;
4670        ++current5_;
4671      }
4672      if (current5_ == end5_) {
4673        current5_ = begin5_;
4674        ++current4_;
4675      }
4676      if (current4_ == end4_) {
4677        current4_ = begin4_;
4678        ++current3_;
4679      }
4680      if (current3_ == end3_) {
4681        current3_ = begin3_;
4682        ++current2_;
4683      }
4684      if (current2_ == end2_) {
4685        current2_ = begin2_;
4686        ++current1_;
4687      }
4688      ComputeCurrentValue();
4689    }
4690    virtual ParamIteratorInterface<ParamType>* Clone() const {
4691      return new Iterator(*this);
4692    }
4693    virtual const ParamType* Current() const { return &current_value_; }
4694    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
4695      // Having the same base generator guarantees that the other
4696      // iterator is of the same type and we can downcast.
4697      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
4698          << "The program attempted to compare iterators "
4699          << "from different generators." << std::endl;
4700      const Iterator* typed_other =
4701          CheckedDowncastToActualType<const Iterator>(&other);
4702      // We must report iterators equal if they both point beyond their
4703      // respective ranges. That can happen in a variety of fashions,
4704      // so we have to consult AtEnd().
4705      return (AtEnd() && typed_other->AtEnd()) ||
4706         (
4707          current1_ == typed_other->current1_ &&
4708          current2_ == typed_other->current2_ &&
4709          current3_ == typed_other->current3_ &&
4710          current4_ == typed_other->current4_ &&
4711          current5_ == typed_other->current5_ &&
4712          current6_ == typed_other->current6_ &&
4713          current7_ == typed_other->current7_ &&
4714          current8_ == typed_other->current8_ &&
4715          current9_ == typed_other->current9_ &&
4716          current10_ == typed_other->current10_);
4717    }
4718
4719   private:
4720    Iterator(const Iterator& other)
4721        : base_(other.base_),
4722        begin1_(other.begin1_),
4723        end1_(other.end1_),
4724        current1_(other.current1_),
4725        begin2_(other.begin2_),
4726        end2_(other.end2_),
4727        current2_(other.current2_),
4728        begin3_(other.begin3_),
4729        end3_(other.end3_),
4730        current3_(other.current3_),
4731        begin4_(other.begin4_),
4732        end4_(other.end4_),
4733        current4_(other.current4_),
4734        begin5_(other.begin5_),
4735        end5_(other.end5_),
4736        current5_(other.current5_),
4737        begin6_(other.begin6_),
4738        end6_(other.end6_),
4739        current6_(other.current6_),
4740        begin7_(other.begin7_),
4741        end7_(other.end7_),
4742        current7_(other.current7_),
4743        begin8_(other.begin8_),
4744        end8_(other.end8_),
4745        current8_(other.current8_),
4746        begin9_(other.begin9_),
4747        end9_(other.end9_),
4748        current9_(other.current9_),
4749        begin10_(other.begin10_),
4750        end10_(other.end10_),
4751        current10_(other.current10_) {
4752      ComputeCurrentValue();
4753    }
4754
4755    void ComputeCurrentValue() {
4756      if (!AtEnd())
4757        current_value_ = ParamType(*current1_, *current2_, *current3_,
4758            *current4_, *current5_, *current6_, *current7_, *current8_,
4759            *current9_, *current10_);
4760    }
4761    bool AtEnd() const {
4762      // We must report iterator past the end of the range when either of the
4763      // component iterators has reached the end of its range.
4764      return
4765          current1_ == end1_ ||
4766          current2_ == end2_ ||
4767          current3_ == end3_ ||
4768          current4_ == end4_ ||
4769          current5_ == end5_ ||
4770          current6_ == end6_ ||
4771          current7_ == end7_ ||
4772          current8_ == end8_ ||
4773          current9_ == end9_ ||
4774          current10_ == end10_;
4775    }
4776
4777    // No implementation - assignment is unsupported.
4778    void operator=(const Iterator& other);
4779
4780    const ParamGeneratorInterface<ParamType>* const base_;
4781    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
4782    // current[i]_ is the actual traversing iterator.
4783    const typename ParamGenerator<T1>::iterator begin1_;
4784    const typename ParamGenerator<T1>::iterator end1_;
4785    typename ParamGenerator<T1>::iterator current1_;
4786    const typename ParamGenerator<T2>::iterator begin2_;
4787    const typename ParamGenerator<T2>::iterator end2_;
4788    typename ParamGenerator<T2>::iterator current2_;
4789    const typename ParamGenerator<T3>::iterator begin3_;
4790    const typename ParamGenerator<T3>::iterator end3_;
4791    typename ParamGenerator<T3>::iterator current3_;
4792    const typename ParamGenerator<T4>::iterator begin4_;
4793    const typename ParamGenerator<T4>::iterator end4_;
4794    typename ParamGenerator<T4>::iterator current4_;
4795    const typename ParamGenerator<T5>::iterator begin5_;
4796    const typename ParamGenerator<T5>::iterator end5_;
4797    typename ParamGenerator<T5>::iterator current5_;
4798    const typename ParamGenerator<T6>::iterator begin6_;
4799    const typename ParamGenerator<T6>::iterator end6_;
4800    typename ParamGenerator<T6>::iterator current6_;
4801    const typename ParamGenerator<T7>::iterator begin7_;
4802    const typename ParamGenerator<T7>::iterator end7_;
4803    typename ParamGenerator<T7>::iterator current7_;
4804    const typename ParamGenerator<T8>::iterator begin8_;
4805    const typename ParamGenerator<T8>::iterator end8_;
4806    typename ParamGenerator<T8>::iterator current8_;
4807    const typename ParamGenerator<T9>::iterator begin9_;
4808    const typename ParamGenerator<T9>::iterator end9_;
4809    typename ParamGenerator<T9>::iterator current9_;
4810    const typename ParamGenerator<T10>::iterator begin10_;
4811    const typename ParamGenerator<T10>::iterator end10_;
4812    typename ParamGenerator<T10>::iterator current10_;
4813    ParamType current_value_;
4814  };  // class CartesianProductGenerator10::Iterator
4815
4816  // No implementation - assignment is unsupported.
4817  void operator=(const CartesianProductGenerator10& other);
4818
4819  const ParamGenerator<T1> g1_;
4820  const ParamGenerator<T2> g2_;
4821  const ParamGenerator<T3> g3_;
4822  const ParamGenerator<T4> g4_;
4823  const ParamGenerator<T5> g5_;
4824  const ParamGenerator<T6> g6_;
4825  const ParamGenerator<T7> g7_;
4826  const ParamGenerator<T8> g8_;
4827  const ParamGenerator<T9> g9_;
4828  const ParamGenerator<T10> g10_;
4829};  // class CartesianProductGenerator10
4830
4831
4832// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
4833//
4834// Helper classes providing Combine() with polymorphic features. They allow
4835// casting CartesianProductGeneratorN<T> to ParamGenerator<U> if T is
4836// convertible to U.
4837//
4838template <class Generator1, class Generator2>
4839class CartesianProductHolder2 {
4840 public:
4841CartesianProductHolder2(const Generator1& g1, const Generator2& g2)
4842      : g1_(g1), g2_(g2) {}
4843  template <typename T1, typename T2>
4844  operator ParamGenerator< ::testing::tuple<T1, T2> >() const {
4845    return ParamGenerator< ::testing::tuple<T1, T2> >(
4846        new CartesianProductGenerator2<T1, T2>(
4847        static_cast<ParamGenerator<T1> >(g1_),
4848        static_cast<ParamGenerator<T2> >(g2_)));
4849  }
4850
4851 private:
4852  // No implementation - assignment is unsupported.
4853  void operator=(const CartesianProductHolder2& other);
4854
4855  const Generator1 g1_;
4856  const Generator2 g2_;
4857};  // class CartesianProductHolder2
4858
4859template <class Generator1, class Generator2, class Generator3>
4860class CartesianProductHolder3 {
4861 public:
4862CartesianProductHolder3(const Generator1& g1, const Generator2& g2,
4863    const Generator3& g3)
4864      : g1_(g1), g2_(g2), g3_(g3) {}
4865  template <typename T1, typename T2, typename T3>
4866  operator ParamGenerator< ::testing::tuple<T1, T2, T3> >() const {
4867    return ParamGenerator< ::testing::tuple<T1, T2, T3> >(
4868        new CartesianProductGenerator3<T1, T2, T3>(
4869        static_cast<ParamGenerator<T1> >(g1_),
4870        static_cast<ParamGenerator<T2> >(g2_),
4871        static_cast<ParamGenerator<T3> >(g3_)));
4872  }
4873
4874 private:
4875  // No implementation - assignment is unsupported.
4876  void operator=(const CartesianProductHolder3& other);
4877
4878  const Generator1 g1_;
4879  const Generator2 g2_;
4880  const Generator3 g3_;
4881};  // class CartesianProductHolder3
4882
4883template <class Generator1, class Generator2, class Generator3,
4884    class Generator4>
4885class CartesianProductHolder4 {
4886 public:
4887CartesianProductHolder4(const Generator1& g1, const Generator2& g2,
4888    const Generator3& g3, const Generator4& g4)
4889      : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {}
4890  template <typename T1, typename T2, typename T3, typename T4>
4891  operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4> >() const {
4892    return ParamGenerator< ::testing::tuple<T1, T2, T3, T4> >(
4893        new CartesianProductGenerator4<T1, T2, T3, T4>(
4894        static_cast<ParamGenerator<T1> >(g1_),
4895        static_cast<ParamGenerator<T2> >(g2_),
4896        static_cast<ParamGenerator<T3> >(g3_),
4897        static_cast<ParamGenerator<T4> >(g4_)));
4898  }
4899
4900 private:
4901  // No implementation - assignment is unsupported.
4902  void operator=(const CartesianProductHolder4& other);
4903
4904  const Generator1 g1_;
4905  const Generator2 g2_;
4906  const Generator3 g3_;
4907  const Generator4 g4_;
4908};  // class CartesianProductHolder4
4909
4910template <class Generator1, class Generator2, class Generator3,
4911    class Generator4, class Generator5>
4912class CartesianProductHolder5 {
4913 public:
4914CartesianProductHolder5(const Generator1& g1, const Generator2& g2,
4915    const Generator3& g3, const Generator4& g4, const Generator5& g5)
4916      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {}
4917  template <typename T1, typename T2, typename T3, typename T4, typename T5>
4918  operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5> >() const {
4919    return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5> >(
4920        new CartesianProductGenerator5<T1, T2, T3, T4, T5>(
4921        static_cast<ParamGenerator<T1> >(g1_),
4922        static_cast<ParamGenerator<T2> >(g2_),
4923        static_cast<ParamGenerator<T3> >(g3_),
4924        static_cast<ParamGenerator<T4> >(g4_),
4925        static_cast<ParamGenerator<T5> >(g5_)));
4926  }
4927
4928 private:
4929  // No implementation - assignment is unsupported.
4930  void operator=(const CartesianProductHolder5& other);
4931
4932  const Generator1 g1_;
4933  const Generator2 g2_;
4934  const Generator3 g3_;
4935  const Generator4 g4_;
4936  const Generator5 g5_;
4937};  // class CartesianProductHolder5
4938
4939template <class Generator1, class Generator2, class Generator3,
4940    class Generator4, class Generator5, class Generator6>
4941class CartesianProductHolder6 {
4942 public:
4943CartesianProductHolder6(const Generator1& g1, const Generator2& g2,
4944    const Generator3& g3, const Generator4& g4, const Generator5& g5,
4945    const Generator6& g6)
4946      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {}
4947  template <typename T1, typename T2, typename T3, typename T4, typename T5,
4948      typename T6>
4949  operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6> >() const {
4950    return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6> >(
4951        new CartesianProductGenerator6<T1, T2, T3, T4, T5, T6>(
4952        static_cast<ParamGenerator<T1> >(g1_),
4953        static_cast<ParamGenerator<T2> >(g2_),
4954        static_cast<ParamGenerator<T3> >(g3_),
4955        static_cast<ParamGenerator<T4> >(g4_),
4956        static_cast<ParamGenerator<T5> >(g5_),
4957        static_cast<ParamGenerator<T6> >(g6_)));
4958  }
4959
4960 private:
4961  // No implementation - assignment is unsupported.
4962  void operator=(const CartesianProductHolder6& other);
4963
4964  const Generator1 g1_;
4965  const Generator2 g2_;
4966  const Generator3 g3_;
4967  const Generator4 g4_;
4968  const Generator5 g5_;
4969  const Generator6 g6_;
4970};  // class CartesianProductHolder6
4971
4972template <class Generator1, class Generator2, class Generator3,
4973    class Generator4, class Generator5, class Generator6, class Generator7>
4974class CartesianProductHolder7 {
4975 public:
4976CartesianProductHolder7(const Generator1& g1, const Generator2& g2,
4977    const Generator3& g3, const Generator4& g4, const Generator5& g5,
4978    const Generator6& g6, const Generator7& g7)
4979      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {}
4980  template <typename T1, typename T2, typename T3, typename T4, typename T5,
4981      typename T6, typename T7>
4982  operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6,
4983      T7> >() const {
4984    return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> >(
4985        new CartesianProductGenerator7<T1, T2, T3, T4, T5, T6, T7>(
4986        static_cast<ParamGenerator<T1> >(g1_),
4987        static_cast<ParamGenerator<T2> >(g2_),
4988        static_cast<ParamGenerator<T3> >(g3_),
4989        static_cast<ParamGenerator<T4> >(g4_),
4990        static_cast<ParamGenerator<T5> >(g5_),
4991        static_cast<ParamGenerator<T6> >(g6_),
4992        static_cast<ParamGenerator<T7> >(g7_)));
4993  }
4994
4995 private:
4996  // No implementation - assignment is unsupported.
4997  void operator=(const CartesianProductHolder7& other);
4998
4999  const Generator1 g1_;
5000  const Generator2 g2_;
5001  const Generator3 g3_;
5002  const Generator4 g4_;
5003  const Generator5 g5_;
5004  const Generator6 g6_;
5005  const Generator7 g7_;
5006};  // class CartesianProductHolder7
5007
5008template <class Generator1, class Generator2, class Generator3,
5009    class Generator4, class Generator5, class Generator6, class Generator7,
5010    class Generator8>
5011class CartesianProductHolder8 {
5012 public:
5013CartesianProductHolder8(const Generator1& g1, const Generator2& g2,
5014    const Generator3& g3, const Generator4& g4, const Generator5& g5,
5015    const Generator6& g6, const Generator7& g7, const Generator8& g8)
5016      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7),
5017          g8_(g8) {}
5018  template <typename T1, typename T2, typename T3, typename T4, typename T5,
5019      typename T6, typename T7, typename T8>
5020  operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7,
5021      T8> >() const {
5022    return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> >(
5023        new CartesianProductGenerator8<T1, T2, T3, T4, T5, T6, T7, T8>(
5024        static_cast<ParamGenerator<T1> >(g1_),
5025        static_cast<ParamGenerator<T2> >(g2_),
5026        static_cast<ParamGenerator<T3> >(g3_),
5027        static_cast<ParamGenerator<T4> >(g4_),
5028        static_cast<ParamGenerator<T5> >(g5_),
5029        static_cast<ParamGenerator<T6> >(g6_),
5030        static_cast<ParamGenerator<T7> >(g7_),
5031        static_cast<ParamGenerator<T8> >(g8_)));
5032  }
5033
5034 private:
5035  // No implementation - assignment is unsupported.
5036  void operator=(const CartesianProductHolder8& other);
5037
5038  const Generator1 g1_;
5039  const Generator2 g2_;
5040  const Generator3 g3_;
5041  const Generator4 g4_;
5042  const Generator5 g5_;
5043  const Generator6 g6_;
5044  const Generator7 g7_;
5045  const Generator8 g8_;
5046};  // class CartesianProductHolder8
5047
5048template <class Generator1, class Generator2, class Generator3,
5049    class Generator4, class Generator5, class Generator6, class Generator7,
5050    class Generator8, class Generator9>
5051class CartesianProductHolder9 {
5052 public:
5053CartesianProductHolder9(const Generator1& g1, const Generator2& g2,
5054    const Generator3& g3, const Generator4& g4, const Generator5& g5,
5055    const Generator6& g6, const Generator7& g7, const Generator8& g8,
5056    const Generator9& g9)
5057      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8),
5058          g9_(g9) {}
5059  template <typename T1, typename T2, typename T3, typename T4, typename T5,
5060      typename T6, typename T7, typename T8, typename T9>
5061  operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8,
5062      T9> >() const {
5063    return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8,
5064        T9> >(
5065        new CartesianProductGenerator9<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
5066        static_cast<ParamGenerator<T1> >(g1_),
5067        static_cast<ParamGenerator<T2> >(g2_),
5068        static_cast<ParamGenerator<T3> >(g3_),
5069        static_cast<ParamGenerator<T4> >(g4_),
5070        static_cast<ParamGenerator<T5> >(g5_),
5071        static_cast<ParamGenerator<T6> >(g6_),
5072        static_cast<ParamGenerator<T7> >(g7_),
5073        static_cast<ParamGenerator<T8> >(g8_),
5074        static_cast<ParamGenerator<T9> >(g9_)));
5075  }
5076
5077 private:
5078  // No implementation - assignment is unsupported.
5079  void operator=(const CartesianProductHolder9& other);
5080
5081  const Generator1 g1_;
5082  const Generator2 g2_;
5083  const Generator3 g3_;
5084  const Generator4 g4_;
5085  const Generator5 g5_;
5086  const Generator6 g6_;
5087  const Generator7 g7_;
5088  const Generator8 g8_;
5089  const Generator9 g9_;
5090};  // class CartesianProductHolder9
5091
5092template <class Generator1, class Generator2, class Generator3,
5093    class Generator4, class Generator5, class Generator6, class Generator7,
5094    class Generator8, class Generator9, class Generator10>
5095class CartesianProductHolder10 {
5096 public:
5097CartesianProductHolder10(const Generator1& g1, const Generator2& g2,
5098    const Generator3& g3, const Generator4& g4, const Generator5& g5,
5099    const Generator6& g6, const Generator7& g7, const Generator8& g8,
5100    const Generator9& g9, const Generator10& g10)
5101      : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8),
5102          g9_(g9), g10_(g10) {}
5103  template <typename T1, typename T2, typename T3, typename T4, typename T5,
5104      typename T6, typename T7, typename T8, typename T9, typename T10>
5105  operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9,
5106      T10> >() const {
5107    return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9,
5108        T10> >(
5109        new CartesianProductGenerator10<T1, T2, T3, T4, T5, T6, T7, T8, T9,
5110            T10>(
5111        static_cast<ParamGenerator<T1> >(g1_),
5112        static_cast<ParamGenerator<T2> >(g2_),
5113        static_cast<ParamGenerator<T3> >(g3_),
5114        static_cast<ParamGenerator<T4> >(g4_),
5115        static_cast<ParamGenerator<T5> >(g5_),
5116        static_cast<ParamGenerator<T6> >(g6_),
5117        static_cast<ParamGenerator<T7> >(g7_),
5118        static_cast<ParamGenerator<T8> >(g8_),
5119        static_cast<ParamGenerator<T9> >(g9_),
5120        static_cast<ParamGenerator<T10> >(g10_)));
5121  }
5122
5123 private:
5124  // No implementation - assignment is unsupported.
5125  void operator=(const CartesianProductHolder10& other);
5126
5127  const Generator1 g1_;
5128  const Generator2 g2_;
5129  const Generator3 g3_;
5130  const Generator4 g4_;
5131  const Generator5 g5_;
5132  const Generator6 g6_;
5133  const Generator7 g7_;
5134  const Generator8 g8_;
5135  const Generator9 g9_;
5136  const Generator10 g10_;
5137};  // class CartesianProductHolder10
5138
5139# endif  // GTEST_HAS_COMBINE
5140
5141}  // namespace internal
5142}  // namespace testing
5143
5144#endif  //  GTEST_HAS_PARAM_TEST
5145
5146#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-param-util-generated.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$var n = 50  $$ Maximum length of Values arguments we want to support.
3$var maxtuple = 10  $$ Maximum number of Combine arguments we want to support.
4// Copyright 2008 Google Inc.
5// All Rights Reserved.
6//
7// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions are
9// met:
10//
11//     * Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//     * Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following disclaimer
15// in the documentation and/or other materials provided with the
16// distribution.
17//     * Neither the name of Google Inc. nor the names of its
18// contributors may be used to endorse or promote products derived from
19// this software without specific prior written permission.
20//
21// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32//
33// Author: vladl@google.com (Vlad Losev)
34
35// Type and function utilities for implementing parameterized tests.
36// This file is generated by a SCRIPT.  DO NOT EDIT BY HAND!
37//
38// Currently Google Test supports at most $n arguments in Values,
39// and at most $maxtuple arguments in Combine. Please contact
40// googletestframework@googlegroups.com if you need more.
41// Please note that the number of arguments to Combine is limited
42// by the maximum arity of the implementation of tuple which is
43// currently set at $maxtuple.
44
45#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
46#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
47
48// scripts/fuse_gtest.py depends on gtest's own header being #included
49// *unconditionally*.  Therefore these #includes cannot be moved
50// inside #if GTEST_HAS_PARAM_TEST.
51#include "gtest/internal/gtest-param-util.h"
52#include "gtest/internal/gtest-port.h"
53
54#if GTEST_HAS_PARAM_TEST
55
56namespace testing {
57
58// Forward declarations of ValuesIn(), which is implemented in
59// include/gtest/gtest-param-test.h.
60template <typename ForwardIterator>
61internal::ParamGenerator<
62  typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type>
63ValuesIn(ForwardIterator begin, ForwardIterator end);
64
65template <typename T, size_t N>
66internal::ParamGenerator<T> ValuesIn(const T (&array)[N]);
67
68template <class Container>
69internal::ParamGenerator<typename Container::value_type> ValuesIn(
70    const Container& container);
71
72namespace internal {
73
74// Used in the Values() function to provide polymorphic capabilities.
75$range i 1..n
76$for i [[
77$range j 1..i
78
79template <$for j, [[typename T$j]]>
80class ValueArray$i {
81 public:
82  $if i==1 [[explicit ]]ValueArray$i($for j, [[T$j v$j]]) : $for j, [[v$(j)_(v$j)]] {}
83
84  template <typename T>
85  operator ParamGenerator<T>() const {
86    const T array[] = {$for j, [[static_cast<T>(v$(j)_)]]};
87    return ValuesIn(array);
88  }
89
90 private:
91  // No implementation - assignment is unsupported.
92  void operator=(const ValueArray$i& other);
93
94$for j [[
95
96  const T$j v$(j)_;
97]]
98
99};
100
101]]
102
103# if GTEST_HAS_COMBINE
104// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
105//
106// Generates values from the Cartesian product of values produced
107// by the argument generators.
108//
109$range i 2..maxtuple
110$for i [[
111$range j 1..i
112$range k 2..i
113
114template <$for j, [[typename T$j]]>
115class CartesianProductGenerator$i
116    : public ParamGeneratorInterface< ::testing::tuple<$for j, [[T$j]]> > {
117 public:
118  typedef ::testing::tuple<$for j, [[T$j]]> ParamType;
119
120  CartesianProductGenerator$i($for j, [[const ParamGenerator<T$j>& g$j]])
121      : $for j, [[g$(j)_(g$j)]] {}
122  virtual ~CartesianProductGenerator$i() {}
123
124  virtual ParamIteratorInterface<ParamType>* Begin() const {
125    return new Iterator(this, $for j, [[g$(j)_, g$(j)_.begin()]]);
126  }
127  virtual ParamIteratorInterface<ParamType>* End() const {
128    return new Iterator(this, $for j, [[g$(j)_, g$(j)_.end()]]);
129  }
130
131 private:
132  class Iterator : public ParamIteratorInterface<ParamType> {
133   public:
134    Iterator(const ParamGeneratorInterface<ParamType>* base, $for j, [[
135
136      const ParamGenerator<T$j>& g$j,
137      const typename ParamGenerator<T$j>::iterator& current$(j)]])
138        : base_(base),
139$for j, [[
140
141          begin$(j)_(g$j.begin()), end$(j)_(g$j.end()), current$(j)_(current$j)
142]]    {
143      ComputeCurrentValue();
144    }
145    virtual ~Iterator() {}
146
147    virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const {
148      return base_;
149    }
150    // Advance should not be called on beyond-of-range iterators
151    // so no component iterators must be beyond end of range, either.
152    virtual void Advance() {
153      assert(!AtEnd());
154      ++current$(i)_;
155
156$for k [[
157      if (current$(i+2-k)_ == end$(i+2-k)_) {
158        current$(i+2-k)_ = begin$(i+2-k)_;
159        ++current$(i+2-k-1)_;
160      }
161
162]]
163      ComputeCurrentValue();
164    }
165    virtual ParamIteratorInterface<ParamType>* Clone() const {
166      return new Iterator(*this);
167    }
168    virtual const ParamType* Current() const { return &current_value_; }
169    virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const {
170      // Having the same base generator guarantees that the other
171      // iterator is of the same type and we can downcast.
172      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
173          << "The program attempted to compare iterators "
174          << "from different generators." << std::endl;
175      const Iterator* typed_other =
176          CheckedDowncastToActualType<const Iterator>(&other);
177      // We must report iterators equal if they both point beyond their
178      // respective ranges. That can happen in a variety of fashions,
179      // so we have to consult AtEnd().
180      return (AtEnd() && typed_other->AtEnd()) ||
181         ($for j  && [[
182
183          current$(j)_ == typed_other->current$(j)_
184]]);
185    }
186
187   private:
188    Iterator(const Iterator& other)
189        : base_(other.base_), $for j, [[
190
191        begin$(j)_(other.begin$(j)_),
192        end$(j)_(other.end$(j)_),
193        current$(j)_(other.current$(j)_)
194]] {
195      ComputeCurrentValue();
196    }
197
198    void ComputeCurrentValue() {
199      if (!AtEnd())
200        current_value_ = ParamType($for j, [[*current$(j)_]]);
201    }
202    bool AtEnd() const {
203      // We must report iterator past the end of the range when either of the
204      // component iterators has reached the end of its range.
205      return
206$for j  || [[
207
208          current$(j)_ == end$(j)_
209]];
210    }
211
212    // No implementation - assignment is unsupported.
213    void operator=(const Iterator& other);
214
215    const ParamGeneratorInterface<ParamType>* const base_;
216    // begin[i]_ and end[i]_ define the i-th range that Iterator traverses.
217    // current[i]_ is the actual traversing iterator.
218$for j [[
219
220    const typename ParamGenerator<T$j>::iterator begin$(j)_;
221    const typename ParamGenerator<T$j>::iterator end$(j)_;
222    typename ParamGenerator<T$j>::iterator current$(j)_;
223]]
224
225    ParamType current_value_;
226  };  // class CartesianProductGenerator$i::Iterator
227
228  // No implementation - assignment is unsupported.
229  void operator=(const CartesianProductGenerator$i& other);
230
231
232$for j [[
233  const ParamGenerator<T$j> g$(j)_;
234
235]]
236};  // class CartesianProductGenerator$i
237
238
239]]
240
241// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
242//
243// Helper classes providing Combine() with polymorphic features. They allow
244// casting CartesianProductGeneratorN<T> to ParamGenerator<U> if T is
245// convertible to U.
246//
247$range i 2..maxtuple
248$for i [[
249$range j 1..i
250
251template <$for j, [[class Generator$j]]>
252class CartesianProductHolder$i {
253 public:
254CartesianProductHolder$i($for j, [[const Generator$j& g$j]])
255      : $for j, [[g$(j)_(g$j)]] {}
256  template <$for j, [[typename T$j]]>
257  operator ParamGenerator< ::testing::tuple<$for j, [[T$j]]> >() const {
258    return ParamGenerator< ::testing::tuple<$for j, [[T$j]]> >(
259        new CartesianProductGenerator$i<$for j, [[T$j]]>(
260$for j,[[
261
262        static_cast<ParamGenerator<T$j> >(g$(j)_)
263]]));
264  }
265
266 private:
267  // No implementation - assignment is unsupported.
268  void operator=(const CartesianProductHolder$i& other);
269
270
271$for j [[
272  const Generator$j g$(j)_;
273
274]]
275};  // class CartesianProductHolder$i
276
277]]
278
279# endif  // GTEST_HAS_COMBINE
280
281}  // namespace internal
282}  // namespace testing
283
284#endif  //  GTEST_HAS_PARAM_TEST
285
286#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-param-util.h
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31
32// Type and function utilities for implementing parameterized tests.
33
34#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
35#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
36
37#include <ctype.h>
38
39#include <iterator>
40#include <set>
41#include <utility>
42#include <vector>
43
44// scripts/fuse_gtest.py depends on gtest's own header being #included
45// *unconditionally*.  Therefore these #includes cannot be moved
46// inside #if GTEST_HAS_PARAM_TEST.
47#include "gtest/internal/gtest-internal.h"
48#include "gtest/internal/gtest-linked_ptr.h"
49#include "gtest/internal/gtest-port.h"
50#include "gtest/gtest-printers.h"
51
52#if GTEST_HAS_PARAM_TEST
53
54namespace testing {
55
56// Input to a parameterized test name generator, describing a test parameter.
57// Consists of the parameter value and the integer parameter index.
58template <class ParamType>
59struct TestParamInfo {
60  TestParamInfo(const ParamType& a_param, size_t an_index) :
61    param(a_param),
62    index(an_index) {}
63  ParamType param;
64  size_t index;
65};
66
67// A builtin parameterized test name generator which returns the result of
68// testing::PrintToString.
69struct PrintToStringParamName {
70  template <class ParamType>
71  std::string operator()(const TestParamInfo<ParamType>& info) const {
72    return PrintToString(info.param);
73  }
74};
75
76namespace internal {
77
78// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
79//
80// Outputs a message explaining invalid registration of different
81// fixture class for the same test case. This may happen when
82// TEST_P macro is used to define two tests with the same name
83// but in different namespaces.
84GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name,
85                                          CodeLocation code_location);
86
87template <typename> class ParamGeneratorInterface;
88template <typename> class ParamGenerator;
89
90// Interface for iterating over elements provided by an implementation
91// of ParamGeneratorInterface<T>.
92template <typename T>
93class ParamIteratorInterface {
94 public:
95  virtual ~ParamIteratorInterface() {}
96  // A pointer to the base generator instance.
97  // Used only for the purposes of iterator comparison
98  // to make sure that two iterators belong to the same generator.
99  virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
100  // Advances iterator to point to the next element
101  // provided by the generator. The caller is responsible
102  // for not calling Advance() on an iterator equal to
103  // BaseGenerator()->End().
104  virtual void Advance() = 0;
105  // Clones the iterator object. Used for implementing copy semantics
106  // of ParamIterator<T>.
107  virtual ParamIteratorInterface* Clone() const = 0;
108  // Dereferences the current iterator and provides (read-only) access
109  // to the pointed value. It is the caller's responsibility not to call
110  // Current() on an iterator equal to BaseGenerator()->End().
111  // Used for implementing ParamGenerator<T>::operator*().
112  virtual const T* Current() const = 0;
113  // Determines whether the given iterator and other point to the same
114  // element in the sequence generated by the generator.
115  // Used for implementing ParamGenerator<T>::operator==().
116  virtual bool Equals(const ParamIteratorInterface& other) const = 0;
117};
118
119// Class iterating over elements provided by an implementation of
120// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
121// and implements the const forward iterator concept.
122template <typename T>
123class ParamIterator {
124 public:
125  typedef T value_type;
126  typedef const T& reference;
127  typedef ptrdiff_t difference_type;
128
129  // ParamIterator assumes ownership of the impl_ pointer.
130  ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
131  ParamIterator& operator=(const ParamIterator& other) {
132    if (this != &other)
133      impl_.reset(other.impl_->Clone());
134    return *this;
135  }
136
137  const T& operator*() const { return *impl_->Current(); }
138  const T* operator->() const { return impl_->Current(); }
139  // Prefix version of operator++.
140  ParamIterator& operator++() {
141    impl_->Advance();
142    return *this;
143  }
144  // Postfix version of operator++.
145  ParamIterator operator++(int /*unused*/) {
146    ParamIteratorInterface<T>* clone = impl_->Clone();
147    impl_->Advance();
148    return ParamIterator(clone);
149  }
150  bool operator==(const ParamIterator& other) const {
151    return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
152  }
153  bool operator!=(const ParamIterator& other) const {
154    return !(*this == other);
155  }
156
157 private:
158  friend class ParamGenerator<T>;
159  explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
160  scoped_ptr<ParamIteratorInterface<T> > impl_;
161};
162
163// ParamGeneratorInterface<T> is the binary interface to access generators
164// defined in other translation units.
165template <typename T>
166class ParamGeneratorInterface {
167 public:
168  typedef T ParamType;
169
170  virtual ~ParamGeneratorInterface() {}
171
172  // Generator interface definition
173  virtual ParamIteratorInterface<T>* Begin() const = 0;
174  virtual ParamIteratorInterface<T>* End() const = 0;
175};
176
177// Wraps ParamGeneratorInterface<T> and provides general generator syntax
178// compatible with the STL Container concept.
179// This class implements copy initialization semantics and the contained
180// ParamGeneratorInterface<T> instance is shared among all copies
181// of the original object. This is possible because that instance is immutable.
182template<typename T>
183class ParamGenerator {
184 public:
185  typedef ParamIterator<T> iterator;
186
187  explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
188  ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
189
190  ParamGenerator& operator=(const ParamGenerator& other) {
191    impl_ = other.impl_;
192    return *this;
193  }
194
195  iterator begin() const { return iterator(impl_->Begin()); }
196  iterator end() const { return iterator(impl_->End()); }
197
198 private:
199  linked_ptr<const ParamGeneratorInterface<T> > impl_;
200};
201
202// Generates values from a range of two comparable values. Can be used to
203// generate sequences of user-defined types that implement operator+() and
204// operator<().
205// This class is used in the Range() function.
206template <typename T, typename IncrementT>
207class RangeGenerator : public ParamGeneratorInterface<T> {
208 public:
209  RangeGenerator(T begin, T end, IncrementT step)
210      : begin_(begin), end_(end),
211        step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
212  virtual ~RangeGenerator() {}
213
214  virtual ParamIteratorInterface<T>* Begin() const {
215    return new Iterator(this, begin_, 0, step_);
216  }
217  virtual ParamIteratorInterface<T>* End() const {
218    return new Iterator(this, end_, end_index_, step_);
219  }
220
221 private:
222  class Iterator : public ParamIteratorInterface<T> {
223   public:
224    Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
225             IncrementT step)
226        : base_(base), value_(value), index_(index), step_(step) {}
227    virtual ~Iterator() {}
228
229    virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
230      return base_;
231    }
232    virtual void Advance() {
233      value_ = static_cast<T>(value_ + step_);
234      index_++;
235    }
236    virtual ParamIteratorInterface<T>* Clone() const {
237      return new Iterator(*this);
238    }
239    virtual const T* Current() const { return &value_; }
240    virtual bool Equals(const ParamIteratorInterface<T>& other) const {
241      // Having the same base generator guarantees that the other
242      // iterator is of the same type and we can downcast.
243      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
244          << "The program attempted to compare iterators "
245          << "from different generators." << std::endl;
246      const int other_index =
247          CheckedDowncastToActualType<const Iterator>(&other)->index_;
248      return index_ == other_index;
249    }
250
251   private:
252    Iterator(const Iterator& other)
253        : ParamIteratorInterface<T>(),
254          base_(other.base_), value_(other.value_), index_(other.index_),
255          step_(other.step_) {}
256
257    // No implementation - assignment is unsupported.
258    void operator=(const Iterator& other);
259
260    const ParamGeneratorInterface<T>* const base_;
261    T value_;
262    int index_;
263    const IncrementT step_;
264  };  // class RangeGenerator::Iterator
265
266  static int CalculateEndIndex(const T& begin,
267                               const T& end,
268                               const IncrementT& step) {
269    int end_index = 0;
270    for (T i = begin; i < end; i = static_cast<T>(i + step))
271      end_index++;
272    return end_index;
273  }
274
275  // No implementation - assignment is unsupported.
276  void operator=(const RangeGenerator& other);
277
278  const T begin_;
279  const T end_;
280  const IncrementT step_;
281  // The index for the end() iterator. All the elements in the generated
282  // sequence are indexed (0-based) to aid iterator comparison.
283  const int end_index_;
284};  // class RangeGenerator
285
286
287// Generates values from a pair of STL-style iterators. Used in the
288// ValuesIn() function. The elements are copied from the source range
289// since the source can be located on the stack, and the generator
290// is likely to persist beyond that stack frame.
291template <typename T>
292class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
293 public:
294  template <typename ForwardIterator>
295  ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
296      : container_(begin, end) {}
297  virtual ~ValuesInIteratorRangeGenerator() {}
298
299  virtual ParamIteratorInterface<T>* Begin() const {
300    return new Iterator(this, container_.begin());
301  }
302  virtual ParamIteratorInterface<T>* End() const {
303    return new Iterator(this, container_.end());
304  }
305
306 private:
307  typedef typename ::std::vector<T> ContainerType;
308
309  class Iterator : public ParamIteratorInterface<T> {
310   public:
311    Iterator(const ParamGeneratorInterface<T>* base,
312             typename ContainerType::const_iterator iterator)
313        : base_(base), iterator_(iterator) {}
314    virtual ~Iterator() {}
315
316    virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
317      return base_;
318    }
319    virtual void Advance() {
320      ++iterator_;
321      value_.reset();
322    }
323    virtual ParamIteratorInterface<T>* Clone() const {
324      return new Iterator(*this);
325    }
326    // We need to use cached value referenced by iterator_ because *iterator_
327    // can return a temporary object (and of type other then T), so just
328    // having "return &*iterator_;" doesn't work.
329    // value_ is updated here and not in Advance() because Advance()
330    // can advance iterator_ beyond the end of the range, and we cannot
331    // detect that fact. The client code, on the other hand, is
332    // responsible for not calling Current() on an out-of-range iterator.
333    virtual const T* Current() const {
334      if (value_.get() == NULL)
335        value_.reset(new T(*iterator_));
336      return value_.get();
337    }
338    virtual bool Equals(const ParamIteratorInterface<T>& other) const {
339      // Having the same base generator guarantees that the other
340      // iterator is of the same type and we can downcast.
341      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
342          << "The program attempted to compare iterators "
343          << "from different generators." << std::endl;
344      return iterator_ ==
345          CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
346    }
347
348   private:
349    Iterator(const Iterator& other)
350          // The explicit constructor call suppresses a false warning
351          // emitted by gcc when supplied with the -Wextra option.
352        : ParamIteratorInterface<T>(),
353          base_(other.base_),
354          iterator_(other.iterator_) {}
355
356    const ParamGeneratorInterface<T>* const base_;
357    typename ContainerType::const_iterator iterator_;
358    // A cached value of *iterator_. We keep it here to allow access by
359    // pointer in the wrapping iterator's operator->().
360    // value_ needs to be mutable to be accessed in Current().
361    // Use of scoped_ptr helps manage cached value's lifetime,
362    // which is bound by the lifespan of the iterator itself.
363    mutable scoped_ptr<const T> value_;
364  };  // class ValuesInIteratorRangeGenerator::Iterator
365
366  // No implementation - assignment is unsupported.
367  void operator=(const ValuesInIteratorRangeGenerator& other);
368
369  const ContainerType container_;
370};  // class ValuesInIteratorRangeGenerator
371
372// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
373//
374// Default parameterized test name generator, returns a string containing the
375// integer test parameter index.
376template <class ParamType>
377std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
378  Message name_stream;
379  name_stream << info.index;
380  return name_stream.GetString();
381}
382
383// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
384//
385// Parameterized test name overload helpers, which help the
386// INSTANTIATE_TEST_CASE_P macro choose between the default parameterized
387// test name generator and user param name generator.
388template <class ParamType, class ParamNameGenFunctor>
389ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) {
390  return func;
391}
392
393template <class ParamType>
394struct ParamNameGenFunc {
395  typedef std::string Type(const TestParamInfo<ParamType>&);
396};
397
398template <class ParamType>
399typename ParamNameGenFunc<ParamType>::Type *GetParamNameGen() {
400  return DefaultParamName;
401}
402
403// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
404//
405// Stores a parameter value and later creates tests parameterized with that
406// value.
407template <class TestClass>
408class ParameterizedTestFactory : public TestFactoryBase {
409 public:
410  typedef typename TestClass::ParamType ParamType;
411  explicit ParameterizedTestFactory(ParamType parameter) :
412      parameter_(parameter) {}
413  virtual Test* CreateTest() {
414    TestClass::SetParam(&parameter_);
415    return new TestClass();
416  }
417
418 private:
419  const ParamType parameter_;
420
421  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
422};
423
424// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
425//
426// TestMetaFactoryBase is a base class for meta-factories that create
427// test factories for passing into MakeAndRegisterTestInfo function.
428template <class ParamType>
429class TestMetaFactoryBase {
430 public:
431  virtual ~TestMetaFactoryBase() {}
432
433  virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
434};
435
436// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
437//
438// TestMetaFactory creates test factories for passing into
439// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
440// ownership of test factory pointer, same factory object cannot be passed
441// into that method twice. But ParameterizedTestCaseInfo is going to call
442// it for each Test/Parameter value combination. Thus it needs meta factory
443// creator class.
444template <class TestCase>
445class TestMetaFactory
446    : public TestMetaFactoryBase<typename TestCase::ParamType> {
447 public:
448  typedef typename TestCase::ParamType ParamType;
449
450  TestMetaFactory() {}
451
452  virtual TestFactoryBase* CreateTestFactory(ParamType parameter) {
453    return new ParameterizedTestFactory<TestCase>(parameter);
454  }
455
456 private:
457  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
458};
459
460// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
461//
462// ParameterizedTestCaseInfoBase is a generic interface
463// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase
464// accumulates test information provided by TEST_P macro invocations
465// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations
466// and uses that information to register all resulting test instances
467// in RegisterTests method. The ParameterizeTestCaseRegistry class holds
468// a collection of pointers to the ParameterizedTestCaseInfo objects
469// and calls RegisterTests() on each of them when asked.
470class ParameterizedTestCaseInfoBase {
471 public:
472  virtual ~ParameterizedTestCaseInfoBase() {}
473
474  // Base part of test case name for display purposes.
475  virtual const string& GetTestCaseName() const = 0;
476  // Test case id to verify identity.
477  virtual TypeId GetTestCaseTypeId() const = 0;
478  // UnitTest class invokes this method to register tests in this
479  // test case right before running them in RUN_ALL_TESTS macro.
480  // This method should not be called more then once on any single
481  // instance of a ParameterizedTestCaseInfoBase derived class.
482  virtual void RegisterTests() = 0;
483
484 protected:
485  ParameterizedTestCaseInfoBase() {}
486
487 private:
488  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase);
489};
490
491// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
492//
493// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P
494// macro invocations for a particular test case and generators
495// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that
496// test case. It registers tests with all values generated by all
497// generators when asked.
498template <class TestCase>
499class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
500 public:
501  // ParamType and GeneratorCreationFunc are private types but are required
502  // for declarations of public methods AddTestPattern() and
503  // AddTestCaseInstantiation().
504  typedef typename TestCase::ParamType ParamType;
505  // A function that returns an instance of appropriate generator type.
506  typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
507  typedef typename ParamNameGenFunc<ParamType>::Type ParamNameGeneratorFunc;
508
509  explicit ParameterizedTestCaseInfo(
510      const char* name, CodeLocation code_location)
511      : test_case_name_(name), code_location_(code_location) {}
512
513  // Test case base name for display purposes.
514  virtual const string& GetTestCaseName() const { return test_case_name_; }
515  // Test case id to verify identity.
516  virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); }
517  // TEST_P macro uses AddTestPattern() to record information
518  // about a single test in a LocalTestInfo structure.
519  // test_case_name is the base name of the test case (without invocation
520  // prefix). test_base_name is the name of an individual test without
521  // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
522  // test case base name and DoBar is test base name.
523  void AddTestPattern(const char* test_case_name,
524                      const char* test_base_name,
525                      TestMetaFactoryBase<ParamType>* meta_factory) {
526    tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name,
527                                                       test_base_name,
528                                                       meta_factory)));
529  }
530  // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information
531  // about a generator.
532  int AddTestCaseInstantiation(const string& instantiation_name,
533                               GeneratorCreationFunc* func,
534                               ParamNameGeneratorFunc* name_func,
535                               const char* file,
536                               int line) {
537    instantiations_.push_back(
538        InstantiationInfo(instantiation_name, func, name_func, file, line));
539    return 0;  // Return value used only to run this method in namespace scope.
540  }
541  // UnitTest class invokes this method to register tests in this test case
542  // test cases right before running tests in RUN_ALL_TESTS macro.
543  // This method should not be called more then once on any single
544  // instance of a ParameterizedTestCaseInfoBase derived class.
545  // UnitTest has a guard to prevent from calling this method more then once.
546  virtual void RegisterTests() {
547    for (typename TestInfoContainer::iterator test_it = tests_.begin();
548         test_it != tests_.end(); ++test_it) {
549      linked_ptr<TestInfo> test_info = *test_it;
550      for (typename InstantiationContainer::iterator gen_it =
551               instantiations_.begin(); gen_it != instantiations_.end();
552               ++gen_it) {
553        const string& instantiation_name = gen_it->name;
554        ParamGenerator<ParamType> generator((*gen_it->generator)());
555        ParamNameGeneratorFunc* name_func = gen_it->name_func;
556        const char* file = gen_it->file;
557        int line = gen_it->line;
558
559        string test_case_name;
560        if ( !instantiation_name.empty() )
561          test_case_name = instantiation_name + "/";
562        test_case_name += test_info->test_case_base_name;
563
564        size_t i = 0;
565        std::set<std::string> test_param_names;
566        for (typename ParamGenerator<ParamType>::iterator param_it =
567                 generator.begin();
568             param_it != generator.end(); ++param_it, ++i) {
569          Message test_name_stream;
570
571          std::string param_name = name_func(
572              TestParamInfo<ParamType>(*param_it, i));
573
574          GTEST_CHECK_(IsValidParamName(param_name))
575              << "Parameterized test name '" << param_name
576              << "' is invalid, in " << file
577              << " line " << line << std::endl;
578
579          GTEST_CHECK_(test_param_names.count(param_name) == 0)
580              << "Duplicate parameterized test name '" << param_name
581              << "', in " << file << " line " << line << std::endl;
582
583          test_param_names.insert(param_name);
584
585          test_name_stream << test_info->test_base_name << "/" << param_name;
586          MakeAndRegisterTestInfo(
587              test_case_name.c_str(),
588              test_name_stream.GetString().c_str(),
589              NULL,  // No type parameter.
590              PrintToString(*param_it).c_str(),
591              code_location_,
592              GetTestCaseTypeId(),
593              TestCase::SetUpTestCase,
594              TestCase::TearDownTestCase,
595              test_info->test_meta_factory->CreateTestFactory(*param_it));
596        }  // for param_it
597      }  // for gen_it
598    }  // for test_it
599  }  // RegisterTests
600
601 private:
602  // LocalTestInfo structure keeps information about a single test registered
603  // with TEST_P macro.
604  struct TestInfo {
605    TestInfo(const char* a_test_case_base_name,
606             const char* a_test_base_name,
607             TestMetaFactoryBase<ParamType>* a_test_meta_factory) :
608        test_case_base_name(a_test_case_base_name),
609        test_base_name(a_test_base_name),
610        test_meta_factory(a_test_meta_factory) {}
611
612    const string test_case_base_name;
613    const string test_base_name;
614    const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
615  };
616  typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer;
617  // Records data received from INSTANTIATE_TEST_CASE_P macros:
618  //  <Instantiation name, Sequence generator creation function,
619  //     Name generator function, Source file, Source line>
620  struct InstantiationInfo {
621      InstantiationInfo(const std::string &name_in,
622                        GeneratorCreationFunc* generator_in,
623                        ParamNameGeneratorFunc* name_func_in,
624                        const char* file_in,
625                        int line_in)
626          : name(name_in),
627            generator(generator_in),
628            name_func(name_func_in),
629            file(file_in),
630            line(line_in) {}
631
632      std::string name;
633      GeneratorCreationFunc* generator;
634      ParamNameGeneratorFunc* name_func;
635      const char* file;
636      int line;
637  };
638  typedef ::std::vector<InstantiationInfo> InstantiationContainer;
639
640  static bool IsValidParamName(const std::string& name) {
641    // Check for empty string
642    if (name.empty())
643      return false;
644
645    // Check for invalid characters
646    for (std::string::size_type index = 0; index < name.size(); ++index) {
647      if (!isalnum(name[index]) && name[index] != '_')
648        return false;
649    }
650
651    return true;
652  }
653
654  const string test_case_name_;
655  CodeLocation code_location_;
656  TestInfoContainer tests_;
657  InstantiationContainer instantiations_;
658
659  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo);
660};  // class ParameterizedTestCaseInfo
661
662// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
663//
664// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase
665// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P
666// macros use it to locate their corresponding ParameterizedTestCaseInfo
667// descriptors.
668class ParameterizedTestCaseRegistry {
669 public:
670  ParameterizedTestCaseRegistry() {}
671  ~ParameterizedTestCaseRegistry() {
672    for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
673         it != test_case_infos_.end(); ++it) {
674      delete *it;
675    }
676  }
677
678  // Looks up or creates and returns a structure containing information about
679  // tests and instantiations of a particular test case.
680  template <class TestCase>
681  ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
682      const char* test_case_name,
683      CodeLocation code_location) {
684    ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL;
685    for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
686         it != test_case_infos_.end(); ++it) {
687      if ((*it)->GetTestCaseName() == test_case_name) {
688        if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) {
689          // Complain about incorrect usage of Google Test facilities
690          // and terminate the program since we cannot guaranty correct
691          // test case setup and tear-down in this case.
692          ReportInvalidTestCaseType(test_case_name, code_location);
693          posix::Abort();
694        } else {
695          // At this point we are sure that the object we found is of the same
696          // type we are looking for, so we downcast it to that type
697          // without further checks.
698          typed_test_info = CheckedDowncastToActualType<
699              ParameterizedTestCaseInfo<TestCase> >(*it);
700        }
701        break;
702      }
703    }
704    if (typed_test_info == NULL) {
705      typed_test_info = new ParameterizedTestCaseInfo<TestCase>(
706          test_case_name, code_location);
707      test_case_infos_.push_back(typed_test_info);
708    }
709    return typed_test_info;
710  }
711  void RegisterTests() {
712    for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
713         it != test_case_infos_.end(); ++it) {
714      (*it)->RegisterTests();
715    }
716  }
717
718 private:
719  typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer;
720
721  TestCaseInfoContainer test_case_infos_;
722
723  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry);
724};
725
726}  // namespace internal
727}  // namespace testing
728
729#endif  //  GTEST_HAS_PARAM_TEST
730
731#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-port-arch.h
r0r249096
1// Copyright 2015, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// The Google C++ Testing Framework (Google Test)
31//
32// This header file defines the GTEST_OS_* macro.
33// It is separate from gtest-port.h so that custom/gtest-port.h can include it.
34
35#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
36#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
37
38// Determines the platform on which Google Test is compiled.
39#ifdef __CYGWIN__
40# define GTEST_OS_CYGWIN 1
41#elif defined __SYMBIAN32__
42# define GTEST_OS_SYMBIAN 1
43#elif defined _WIN32
44# define GTEST_OS_WINDOWS 1
45# ifdef _WIN32_WCE
46#  define GTEST_OS_WINDOWS_MOBILE 1
47# elif defined(__MINGW__) || defined(__MINGW32__)
48#  define GTEST_OS_WINDOWS_MINGW 1
49# elif defined(WINAPI_FAMILY)
50#  include <winapifamily.h>
51#  if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
52#   define GTEST_OS_WINDOWS_DESKTOP 1
53#  elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
54#   define GTEST_OS_WINDOWS_PHONE 1
55#  elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
56#   define GTEST_OS_WINDOWS_RT 1
57#  else
58    // WINAPI_FAMILY defined but no known partition matched.
59    // Default to desktop.
60#   define GTEST_OS_WINDOWS_DESKTOP 1
61#  endif
62# else
63#  define GTEST_OS_WINDOWS_DESKTOP 1
64# endif  // _WIN32_WCE
65#elif defined __APPLE__
66# define GTEST_OS_MAC 1
67# if TARGET_OS_IPHONE
68#  define GTEST_OS_IOS 1
69# endif
70#elif defined __FreeBSD__
71# define GTEST_OS_FREEBSD 1
72#elif defined __linux__
73# define GTEST_OS_LINUX 1
74# if defined __ANDROID__
75#  define GTEST_OS_LINUX_ANDROID 1
76# endif
77#elif defined __MVS__
78# define GTEST_OS_ZOS 1
79#elif defined(__sun) && defined(__SVR4)
80# define GTEST_OS_SOLARIS 1
81#elif defined(_AIX)
82# define GTEST_OS_AIX 1
83#elif defined(__hpux)
84# define GTEST_OS_HPUX 1
85#elif defined __native_client__
86# define GTEST_OS_NACL 1
87#elif defined __OpenBSD__
88# define GTEST_OS_OPENBSD 1
89#elif defined __QNX__
90# define GTEST_OS_QNX 1
91#endif  // __CYGWIN__
92
93#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-port.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: wan@google.com (Zhanyong Wan)
31//
32// Low-level types and utilities for porting Google Test to various
33// platforms.  All macros ending with _ and symbols defined in an
34// internal namespace are subject to change without notice.  Code
35// outside Google Test MUST NOT USE THEM DIRECTLY.  Macros that don't
36// end with _ are part of Google Test's public API and can be used by
37// code outside Google Test.
38//
39// This file is fundamental to Google Test.  All other Google Test source
40// files are expected to #include this.  Therefore, it cannot #include
41// any other Google Test header.
42
43#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
44#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
45
46// Environment-describing macros
47// -----------------------------
48//
49// Google Test can be used in many different environments.  Macros in
50// this section tell Google Test what kind of environment it is being
51// used in, such that Google Test can provide environment-specific
52// features and implementations.
53//
54// Google Test tries to automatically detect the properties of its
55// environment, so users usually don't need to worry about these
56// macros.  However, the automatic detection is not perfect.
57// Sometimes it's necessary for a user to define some of the following
58// macros in the build script to override Google Test's decisions.
59//
60// If the user doesn't define a macro in the list, Google Test will
61// provide a default definition.  After this header is #included, all
62// macros in this list will be defined to either 1 or 0.
63//
64// Notes to maintainers:
65//   - Each macro here is a user-tweakable knob; do not grow the list
66//     lightly.
67//   - Use #if to key off these macros.  Don't use #ifdef or "#if
68//     defined(...)", which will not work as these macros are ALWAYS
69//     defined.
70//
71//   GTEST_HAS_CLONE          - Define it to 1/0 to indicate that clone(2)
72//                              is/isn't available.
73//   GTEST_HAS_EXCEPTIONS     - Define it to 1/0 to indicate that exceptions
74//                              are enabled.
75//   GTEST_HAS_GLOBAL_STRING  - Define it to 1/0 to indicate that ::string
76//                              is/isn't available (some systems define
77//                              ::string, which is different to std::string).
78//   GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
79//                              is/isn't available (some systems define
80//                              ::wstring, which is different to std::wstring).
81//   GTEST_HAS_POSIX_RE       - Define it to 1/0 to indicate that POSIX regular
82//                              expressions are/aren't available.
83//   GTEST_HAS_PTHREAD        - Define it to 1/0 to indicate that <pthread.h>
84//                              is/isn't available.
85//   GTEST_HAS_RTTI           - Define it to 1/0 to indicate that RTTI is/isn't
86//                              enabled.
87//   GTEST_HAS_STD_WSTRING    - Define it to 1/0 to indicate that
88//                              std::wstring does/doesn't work (Google Test can
89//                              be used where std::wstring is unavailable).
90//   GTEST_HAS_TR1_TUPLE      - Define it to 1/0 to indicate tr1::tuple
91//                              is/isn't available.
92//   GTEST_HAS_SEH            - Define it to 1/0 to indicate whether the
93//                              compiler supports Microsoft's "Structured
94//                              Exception Handling".
95//   GTEST_HAS_STREAM_REDIRECTION
96//                            - Define it to 1/0 to indicate whether the
97//                              platform supports I/O stream redirection using
98//                              dup() and dup2().
99//   GTEST_USE_OWN_TR1_TUPLE  - Define it to 1/0 to indicate whether Google
100//                              Test's own tr1 tuple implementation should be
101//                              used.  Unused when the user sets
102//                              GTEST_HAS_TR1_TUPLE to 0.
103//   GTEST_LANG_CXX11         - Define it to 1/0 to indicate that Google Test
104//                              is building in C++11/C++98 mode.
105//   GTEST_LINKED_AS_SHARED_LIBRARY
106//                            - Define to 1 when compiling tests that use
107//                              Google Test as a shared library (known as
108//                              DLL on Windows).
109//   GTEST_CREATE_SHARED_LIBRARY
110//                            - Define to 1 when compiling Google Test itself
111//                              as a shared library.
112
113// Platform-indicating macros
114// --------------------------
115//
116// Macros indicating the platform on which Google Test is being used
117// (a macro is defined to 1 if compiled on the given platform;
118// otherwise UNDEFINED -- it's never defined to 0.).  Google Test
119// defines these macros automatically.  Code outside Google Test MUST
120// NOT define them.
121//
122//   GTEST_OS_AIX      - IBM AIX
123//   GTEST_OS_CYGWIN   - Cygwin
124//   GTEST_OS_FREEBSD  - FreeBSD
125//   GTEST_OS_HPUX     - HP-UX
126//   GTEST_OS_LINUX    - Linux
127//     GTEST_OS_LINUX_ANDROID - Google Android
128//   GTEST_OS_MAC      - Mac OS X
129//     GTEST_OS_IOS    - iOS
130//   GTEST_OS_NACL     - Google Native Client (NaCl)
131//   GTEST_OS_OPENBSD  - OpenBSD
132//   GTEST_OS_QNX      - QNX
133//   GTEST_OS_SOLARIS  - Sun Solaris
134//   GTEST_OS_SYMBIAN  - Symbian
135//   GTEST_OS_WINDOWS  - Windows (Desktop, MinGW, or Mobile)
136//     GTEST_OS_WINDOWS_DESKTOP  - Windows Desktop
137//     GTEST_OS_WINDOWS_MINGW    - MinGW
138//     GTEST_OS_WINDOWS_MOBILE   - Windows Mobile
139//     GTEST_OS_WINDOWS_PHONE    - Windows Phone
140//     GTEST_OS_WINDOWS_RT       - Windows Store App/WinRT
141//   GTEST_OS_ZOS      - z/OS
142//
143// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
144// most stable support.  Since core members of the Google Test project
145// don't have access to other platforms, support for them may be less
146// stable.  If you notice any problems on your platform, please notify
147// googletestframework@googlegroups.com (patches for fixing them are
148// even more welcome!).
149//
150// It is possible that none of the GTEST_OS_* macros are defined.
151
152// Feature-indicating macros
153// -------------------------
154//
155// Macros indicating which Google Test features are available (a macro
156// is defined to 1 if the corresponding feature is supported;
157// otherwise UNDEFINED -- it's never defined to 0.).  Google Test
158// defines these macros automatically.  Code outside Google Test MUST
159// NOT define them.
160//
161// These macros are public so that portable tests can be written.
162// Such tests typically surround code using a feature with an #if
163// which controls that code.  For example:
164//
165// #if GTEST_HAS_DEATH_TEST
166//   EXPECT_DEATH(DoSomethingDeadly());
167// #endif
168//
169//   GTEST_HAS_COMBINE      - the Combine() function (for value-parameterized
170//                            tests)
171//   GTEST_HAS_DEATH_TEST   - death tests
172//   GTEST_HAS_PARAM_TEST   - value-parameterized tests
173//   GTEST_HAS_TYPED_TEST   - typed tests
174//   GTEST_HAS_TYPED_TEST_P - type-parameterized tests
175//   GTEST_IS_THREADSAFE    - Google Test is thread-safe.
176//   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used. Do not confuse with
177//                            GTEST_HAS_POSIX_RE (see above) which users can
178//                            define themselves.
179//   GTEST_USES_SIMPLE_RE   - our own simple regex is used;
180//                            the above two are mutually exclusive.
181//   GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
182
183// Misc public macros
184// ------------------
185//
186//   GTEST_FLAG(flag_name)  - references the variable corresponding to
187//                            the given Google Test flag.
188
189// Internal utilities
190// ------------------
191//
192// The following macros and utilities are for Google Test's INTERNAL
193// use only.  Code outside Google Test MUST NOT USE THEM DIRECTLY.
194//
195// Macros for basic C++ coding:
196//   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
197//   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a
198//                              variable don't have to be used.
199//   GTEST_DISALLOW_ASSIGN_   - disables operator=.
200//   GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
201//   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.
202//   GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
203//                                        suppressed (constant conditional).
204//   GTEST_INTENTIONAL_CONST_COND_POP_  - finish code section where MSVC C4127
205//                                        is suppressed.
206//
207// C++11 feature wrappers:
208//
209//   testing::internal::move  - portability wrapper for std::move.
210//
211// Synchronization:
212//   Mutex, MutexLock, ThreadLocal, GetThreadCount()
213//                            - synchronization primitives.
214//
215// Template meta programming:
216//   is_pointer     - as in TR1; needed on Symbian and IBM XL C/C++ only.
217//   IteratorTraits - partial implementation of std::iterator_traits, which
218//                    is not available in libCstd when compiled with Sun C++.
219//
220// Smart pointers:
221//   scoped_ptr     - as in TR2.
222//
223// Regular expressions:
224//   RE             - a simple regular expression class using the POSIX
225//                    Extended Regular Expression syntax on UNIX-like
226//                    platforms, or a reduced regular exception syntax on
227//                    other platforms, including Windows.
228//
229// Logging:
230//   GTEST_LOG_()   - logs messages at the specified severity level.
231//   LogToStderr()  - directs all log messages to stderr.
232//   FlushInfoLog() - flushes informational log messages.
233//
234// Stdout and stderr capturing:
235//   CaptureStdout()     - starts capturing stdout.
236//   GetCapturedStdout() - stops capturing stdout and returns the captured
237//                         string.
238//   CaptureStderr()     - starts capturing stderr.
239//   GetCapturedStderr() - stops capturing stderr and returns the captured
240//                         string.
241//
242// Integer types:
243//   TypeWithSize   - maps an integer to a int type.
244//   Int32, UInt32, Int64, UInt64, TimeInMillis
245//                  - integers of known sizes.
246//   BiggestInt     - the biggest signed integer type.
247//
248// Command-line utilities:
249//   GTEST_DECLARE_*()  - declares a flag.
250//   GTEST_DEFINE_*()   - defines a flag.
251//   GetInjectableArgvs() - returns the command line as a vector of strings.
252//
253// Environment variable utilities:
254//   GetEnv()             - gets the value of an environment variable.
255//   BoolFromGTestEnv()   - parses a bool environment variable.
256//   Int32FromGTestEnv()  - parses an Int32 environment variable.
257//   StringFromGTestEnv() - parses a string environment variable.
258
259#include <ctype.h>   // for isspace, etc
260#include <stddef.h>  // for ptrdiff_t
261#include <stdlib.h>
262#include <stdio.h>
263#include <string.h>
264#ifndef _WIN32_WCE
265# include <sys/types.h>
266# include <sys/stat.h>
267#endif  // !_WIN32_WCE
268
269#if defined __APPLE__
270# include <AvailabilityMacros.h>
271# include <TargetConditionals.h>
272#endif
273
274#include <algorithm>  // NOLINT
275#include <iostream>  // NOLINT
276#include <sstream>  // NOLINT
277#include <string>  // NOLINT
278#include <utility>
279#include <vector>  // NOLINT
280
281#include "gtest/internal/gtest-port-arch.h"
282#include "gtest/internal/custom/gtest-port.h"
283
284#if !defined(GTEST_DEV_EMAIL_)
285# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
286# define GTEST_FLAG_PREFIX_ "gtest_"
287# define GTEST_FLAG_PREFIX_DASH_ "gtest-"
288# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
289# define GTEST_NAME_ "Google Test"
290# define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/"
291#endif  // !defined(GTEST_DEV_EMAIL_)
292
293#if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
294# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
295#endif  // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
296
297// Determines the version of gcc that is used to compile this.
298#ifdef __GNUC__
299// 40302 means version 4.3.2.
300# define GTEST_GCC_VER_ \
301    (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
302#endif  // __GNUC__
303
304// Macros for disabling Microsoft Visual C++ warnings.
305//
306//   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
307//   /* code that triggers warnings C4800 and C4385 */
308//   GTEST_DISABLE_MSC_WARNINGS_POP_()
309#if _MSC_VER >= 1500
310# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
311    __pragma(warning(push))                        \
312    __pragma(warning(disable: warnings))
313# define GTEST_DISABLE_MSC_WARNINGS_POP_()          \
314    __pragma(warning(pop))
315#else
316// Older versions of MSVC don't have __pragma.
317# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
318# define GTEST_DISABLE_MSC_WARNINGS_POP_()
319#endif
320
321#ifndef GTEST_LANG_CXX11
322// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when
323// -std={c,gnu}++{0x,11} is passed.  The C++11 standard specifies a
324// value for __cplusplus, and recent versions of clang, gcc, and
325// probably other compilers set that too in C++11 mode.
326# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L
327// Compiling in at least C++11 mode.
328#  define GTEST_LANG_CXX11 1
329# else
330#  define GTEST_LANG_CXX11 0
331# endif
332#endif
333
334// Distinct from C++11 language support, some environments don't provide
335// proper C++11 library support. Notably, it's possible to build in
336// C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++
337// with no C++11 support.
338//
339// libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__
340// 20110325, but maintenance releases in the 4.4 and 4.5 series followed
341// this date, so check for those versions by their date stamps.
342// https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning
343#if GTEST_LANG_CXX11 && \
344    (!defined(__GLIBCXX__) || ( \
345        __GLIBCXX__ >= 20110325ul &&  /* GCC >= 4.6.0 */ \
346        /* Blacklist of patch releases of older branches: */ \
347        __GLIBCXX__ != 20110416ul &&  /* GCC 4.4.6 */ \
348        __GLIBCXX__ != 20120313ul &&  /* GCC 4.4.7 */ \
349        __GLIBCXX__ != 20110428ul &&  /* GCC 4.5.3 */ \
350        __GLIBCXX__ != 20120702ul))   /* GCC 4.5.4 */
351# define GTEST_STDLIB_CXX11 1
352#endif
353
354// Only use C++11 library features if the library provides them.
355#if GTEST_STDLIB_CXX11
356# define GTEST_HAS_STD_BEGIN_AND_END_ 1
357# define GTEST_HAS_STD_FORWARD_LIST_ 1
358# define GTEST_HAS_STD_FUNCTION_ 1
359# define GTEST_HAS_STD_INITIALIZER_LIST_ 1
360# define GTEST_HAS_STD_MOVE_ 1
361# define GTEST_HAS_STD_UNIQUE_PTR_ 1
362# define GTEST_HAS_STD_SHARED_PTR_ 1
363#endif
364
365// C++11 specifies that <tuple> provides std::tuple.
366// Some platforms still might not have it, however.
367#if GTEST_LANG_CXX11
368# define GTEST_HAS_STD_TUPLE_ 1
369# if defined(__clang__)
370// Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include
371#  if defined(__has_include) && !__has_include(<tuple>)
372#   undef GTEST_HAS_STD_TUPLE_
373#  endif
374# elif defined(_MSC_VER)
375// Inspired by boost/config/stdlib/dinkumware.hpp
376#  if defined(_CPPLIB_VER) && _CPPLIB_VER < 520
377#   undef GTEST_HAS_STD_TUPLE_
378#  endif
379# elif defined(__GLIBCXX__)
380// Inspired by boost/config/stdlib/libstdcpp3.hpp,
381// http://gcc.gnu.org/gcc-4.2/changes.html and
382// http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x
383#  if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
384#   undef GTEST_HAS_STD_TUPLE_
385#  endif
386# endif
387#endif
388
389// Brings in definitions for functions used in the testing::internal::posix
390// namespace (read, write, close, chdir, isatty, stat). We do not currently
391// use them on Windows Mobile.
392#if GTEST_OS_WINDOWS
393# if !GTEST_OS_WINDOWS_MOBILE
394#  include <direct.h>
395#  include <io.h>
396# endif
397// In order to avoid having to include <windows.h>, use forward declaration
398// assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
399// This assumption is verified by
400// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
401struct _RTL_CRITICAL_SECTION;
402#else
403// This assumes that non-Windows OSes provide unistd.h. For OSes where this
404// is not the case, we need to include headers that provide the functions
405// mentioned above.
406# include <unistd.h>
407# include <strings.h>
408#endif  // GTEST_OS_WINDOWS
409
410#if GTEST_OS_LINUX_ANDROID
411// Used to define __ANDROID_API__ matching the target NDK API level.
412#  include <android/api-level.h>  // NOLINT
413#endif
414
415// Defines this to true iff Google Test can use POSIX regular expressions.
416#ifndef GTEST_HAS_POSIX_RE
417# if GTEST_OS_LINUX_ANDROID
418// On Android, <regex.h> is only available starting with Gingerbread.
419#  define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
420# else
421#  define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS)
422# endif
423#endif
424
425#if GTEST_USES_PCRE
426// The appropriate headers have already been included.
427
428#elif GTEST_HAS_POSIX_RE
429
430// On some platforms, <regex.h> needs someone to define size_t, and
431// won't compile otherwise.  We can #include it here as we already
432// included <stdlib.h>, which is guaranteed to define size_t through
433// <stddef.h>.
434# include <regex.h>  // NOLINT
435
436# define GTEST_USES_POSIX_RE 1
437
438#elif GTEST_OS_WINDOWS
439
440// <regex.h> is not available on Windows.  Use our own simple regex
441// implementation instead.
442# define GTEST_USES_SIMPLE_RE 1
443
444#else
445
446// <regex.h> may not be available on this platform.  Use our own
447// simple regex implementation instead.
448# define GTEST_USES_SIMPLE_RE 1
449
450#endif  // GTEST_USES_PCRE
451
452#ifndef GTEST_HAS_EXCEPTIONS
453// The user didn't tell us whether exceptions are enabled, so we need
454// to figure it out.
455# if defined(_MSC_VER) || defined(__BORLANDC__)
456// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
457// macro to enable exceptions, so we'll do the same.
458// Assumes that exceptions are enabled by default.
459#  ifndef _HAS_EXCEPTIONS
460#   define _HAS_EXCEPTIONS 1
461#  endif  // _HAS_EXCEPTIONS
462#  define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
463# elif defined(__clang__)
464// clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714,
465// but iff cleanups are enabled after that. In Obj-C++ files, there can be
466// cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions
467// are disabled. clang has __has_feature(cxx_exceptions) which checks for C++
468// exceptions starting at clang r206352, but which checked for cleanups prior to
469// that. To reliably check for C++ exception availability with clang, check for
470// __EXCEPTIONS && __has_feature(cxx_exceptions).
471#  define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
472# elif defined(__GNUC__) && __EXCEPTIONS
473// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
474#  define GTEST_HAS_EXCEPTIONS 1
475# elif defined(__SUNPRO_CC)
476// Sun Pro CC supports exceptions.  However, there is no compile-time way of
477// detecting whether they are enabled or not.  Therefore, we assume that
478// they are enabled unless the user tells us otherwise.
479#  define GTEST_HAS_EXCEPTIONS 1
480# elif defined(__IBMCPP__) && __EXCEPTIONS
481// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
482#  define GTEST_HAS_EXCEPTIONS 1
483# elif defined(__HP_aCC)
484// Exception handling is in effect by default in HP aCC compiler. It has to
485// be turned of by +noeh compiler option if desired.
486#  define GTEST_HAS_EXCEPTIONS 1
487# else
488// For other compilers, we assume exceptions are disabled to be
489// conservative.
490#  define GTEST_HAS_EXCEPTIONS 0
491# endif  // defined(_MSC_VER) || defined(__BORLANDC__)
492#endif  // GTEST_HAS_EXCEPTIONS
493
494#if !defined(GTEST_HAS_STD_STRING)
495// Even though we don't use this macro any longer, we keep it in case
496// some clients still depend on it.
497# define GTEST_HAS_STD_STRING 1
498#elif !GTEST_HAS_STD_STRING
499// The user told us that ::std::string isn't available.
500# error "Google Test cannot be used where ::std::string isn't available."
501#endif  // !defined(GTEST_HAS_STD_STRING)
502
503#ifndef GTEST_HAS_GLOBAL_STRING
504// The user didn't tell us whether ::string is available, so we need
505// to figure it out.
506
507# define GTEST_HAS_GLOBAL_STRING 0
508
509#endif  // GTEST_HAS_GLOBAL_STRING
510
511#ifndef GTEST_HAS_STD_WSTRING
512// The user didn't tell us whether ::std::wstring is available, so we need
513// to figure it out.
514// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
515//   is available.
516
517// Cygwin 1.7 and below doesn't support ::std::wstring.
518// Solaris' libc++ doesn't support it either.  Android has
519// no support for it at least as recent as Froyo (2.2).
520# define GTEST_HAS_STD_WSTRING \
521    (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS))
522
523#endif  // GTEST_HAS_STD_WSTRING
524
525#ifndef GTEST_HAS_GLOBAL_WSTRING
526// The user didn't tell us whether ::wstring is available, so we need
527// to figure it out.
528# define GTEST_HAS_GLOBAL_WSTRING \
529    (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
530#endif  // GTEST_HAS_GLOBAL_WSTRING
531
532// Determines whether RTTI is available.
533#ifndef GTEST_HAS_RTTI
534// The user didn't tell us whether RTTI is enabled, so we need to
535// figure it out.
536
537# ifdef _MSC_VER
538
539#  ifdef _CPPRTTI  // MSVC defines this macro iff RTTI is enabled.
540#   define GTEST_HAS_RTTI 1
541#  else
542#   define GTEST_HAS_RTTI 0
543#  endif
544
545// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
546# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
547
548#  ifdef __GXX_RTTI
549// When building against STLport with the Android NDK and with
550// -frtti -fno-exceptions, the build fails at link time with undefined
551// references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
552// so disable RTTI when detected.
553#   if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
554       !defined(__EXCEPTIONS)
555#    define GTEST_HAS_RTTI 0
556#   else
557#    define GTEST_HAS_RTTI 1
558#   endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
559#  else
560#   define GTEST_HAS_RTTI 0
561#  endif  // __GXX_RTTI
562
563// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
564// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
565// first version with C++ support.
566# elif defined(__clang__)
567
568#  define GTEST_HAS_RTTI __has_feature(cxx_rtti)
569
570// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
571// both the typeid and dynamic_cast features are present.
572# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
573
574#  ifdef __RTTI_ALL__
575#   define GTEST_HAS_RTTI 1
576#  else
577#   define GTEST_HAS_RTTI 0
578#  endif
579
580# else
581
582// For all other compilers, we assume RTTI is enabled.
583#  define GTEST_HAS_RTTI 1
584
585# endif  // _MSC_VER
586
587#endif  // GTEST_HAS_RTTI
588
589// It's this header's responsibility to #include <typeinfo> when RTTI
590// is enabled.
591#if GTEST_HAS_RTTI
592# include <typeinfo>
593#endif
594
595// Determines whether Google Test can use the pthreads library.
596#ifndef GTEST_HAS_PTHREAD
597// The user didn't tell us explicitly, so we make reasonable assumptions about
598// which platforms have pthreads support.
599//
600// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
601// to your compiler flags.
602# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \
603    || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL)
604#endif  // GTEST_HAS_PTHREAD
605
606#if GTEST_HAS_PTHREAD
607// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
608// true.
609# include <pthread.h>  // NOLINT
610
611// For timespec and nanosleep, used below.
612# include <time.h>  // NOLINT
613#endif
614
615// Determines if hash_map/hash_set are available.
616// Only used for testing against those containers.
617#if !defined(GTEST_HAS_HASH_MAP_)
618# if _MSC_VER
619#  define GTEST_HAS_HASH_MAP_ 1  // Indicates that hash_map is available.
620#  define GTEST_HAS_HASH_SET_ 1  // Indicates that hash_set is available.
621# endif  // _MSC_VER
622#endif  // !defined(GTEST_HAS_HASH_MAP_)
623
624// Determines whether Google Test can use tr1/tuple.  You can define
625// this macro to 0 to prevent Google Test from using tuple (any
626// feature depending on tuple with be disabled in this mode).
627#ifndef GTEST_HAS_TR1_TUPLE
628# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR)
629// STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>.
630#  define GTEST_HAS_TR1_TUPLE 0
631# else
632// The user didn't tell us not to do it, so we assume it's OK.
633#  define GTEST_HAS_TR1_TUPLE 1
634# endif
635#endif  // GTEST_HAS_TR1_TUPLE
636
637// Determines whether Google Test's own tr1 tuple implementation
638// should be used.
639#ifndef GTEST_USE_OWN_TR1_TUPLE
640// The user didn't tell us, so we need to figure it out.
641
642// We use our own TR1 tuple if we aren't sure the user has an
643// implementation of it already.  At this time, libstdc++ 4.0.0+ and
644// MSVC 2010 are the only mainstream standard libraries that come
645// with a TR1 tuple implementation.  NVIDIA's CUDA NVCC compiler
646// pretends to be GCC by defining __GNUC__ and friends, but cannot
647// compile GCC's tuple implementation.  MSVC 2008 (9.0) provides TR1
648// tuple in a 323 MB Feature Pack download, which we cannot assume the
649// user has.  QNX's QCC compiler is a modified GCC but it doesn't
650// support TR1 tuple.  libc++ only provides std::tuple, in C++11 mode,
651// and it can be used with some compilers that define __GNUC__.
652# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
653      && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
654#  define GTEST_ENV_HAS_TR1_TUPLE_ 1
655# endif
656
657// C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
658// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
659// can build with clang but need to use gcc4.2's libstdc++).
660# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
661#  define GTEST_ENV_HAS_STD_TUPLE_ 1
662# endif
663
664# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
665#  define GTEST_USE_OWN_TR1_TUPLE 0
666# else
667#  define GTEST_USE_OWN_TR1_TUPLE 1
668# endif
669
670#endif  // GTEST_USE_OWN_TR1_TUPLE
671
672// To avoid conditional compilation everywhere, we make it
673// gtest-port.h's responsibility to #include the header implementing
674// tuple.
675#if GTEST_HAS_STD_TUPLE_
676# include <tuple>  // IWYU pragma: export
677# define GTEST_TUPLE_NAMESPACE_ ::std
678#endif  // GTEST_HAS_STD_TUPLE_
679
680// We include tr1::tuple even if std::tuple is available to define printers for
681// them.
682#if GTEST_HAS_TR1_TUPLE
683# ifndef GTEST_TUPLE_NAMESPACE_
684#  define GTEST_TUPLE_NAMESPACE_ ::std::tr1
685# endif  // GTEST_TUPLE_NAMESPACE_
686
687# if GTEST_USE_OWN_TR1_TUPLE
688#  include "gtest/internal/gtest-tuple.h"  // IWYU pragma: export  // NOLINT
689# elif GTEST_ENV_HAS_STD_TUPLE_
690#  include <tuple>
691// C++11 puts its tuple into the ::std namespace rather than
692// ::std::tr1.  gtest expects tuple to live in ::std::tr1, so put it there.
693// This causes undefined behavior, but supported compilers react in
694// the way we intend.
695namespace std {
696namespace tr1 {
697using ::std::get;
698using ::std::make_tuple;
699using ::std::tuple;
700using ::std::tuple_element;
701using ::std::tuple_size;
702}
703}
704
705# elif GTEST_OS_SYMBIAN
706
707// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
708// use STLport's tuple implementation, which unfortunately doesn't
709// work as the copy of STLport distributed with Symbian is incomplete.
710// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
711// use its own tuple implementation.
712#  ifdef BOOST_HAS_TR1_TUPLE
713#   undef BOOST_HAS_TR1_TUPLE
714#  endif  // BOOST_HAS_TR1_TUPLE
715
716// This prevents <boost/tr1/detail/config.hpp>, which defines
717// BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
718#  define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
719#  include <tuple>  // IWYU pragma: export  // NOLINT
720
721# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
722// GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header.  This does
723// not conform to the TR1 spec, which requires the header to be <tuple>.
724
725#  if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
726// Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
727// which is #included by <tr1/tuple>, to not compile when RTTI is
728// disabled.  _TR1_FUNCTIONAL is the header guard for
729// <tr1/functional>.  Hence the following #define is a hack to prevent
730// <tr1/functional> from being included.
731#   define _TR1_FUNCTIONAL 1
732#   include <tr1/tuple>
733#   undef _TR1_FUNCTIONAL  // Allows the user to #include
734                        // <tr1/functional> if he chooses to.
735#  else
736#   include <tr1/tuple>  // NOLINT
737#  endif  // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
738
739# else
740// If the compiler is not GCC 4.0+, we assume the user is using a
741// spec-conforming TR1 implementation.
742#  include <tuple>  // IWYU pragma: export  // NOLINT
743# endif  // GTEST_USE_OWN_TR1_TUPLE
744
745#endif  // GTEST_HAS_TR1_TUPLE
746
747// Determines whether clone(2) is supported.
748// Usually it will only be available on Linux, excluding
749// Linux on the Itanium architecture.
750// Also see http://linux.die.net/man/2/clone.
751#ifndef GTEST_HAS_CLONE
752// The user didn't tell us, so we need to figure it out.
753
754# if GTEST_OS_LINUX && !defined(__ia64__)
755#  if GTEST_OS_LINUX_ANDROID
756// On Android, clone() is only available on ARM starting with Gingerbread.
757#    if defined(__arm__) && __ANDROID_API__ >= 9
758#     define GTEST_HAS_CLONE 1
759#    else
760#     define GTEST_HAS_CLONE 0
761#    endif
762#  else
763#   define GTEST_HAS_CLONE 1
764#  endif
765# else
766#  define GTEST_HAS_CLONE 0
767# endif  // GTEST_OS_LINUX && !defined(__ia64__)
768
769#endif  // GTEST_HAS_CLONE
770
771// Determines whether to support stream redirection. This is used to test
772// output correctness and to implement death tests.
773#ifndef GTEST_HAS_STREAM_REDIRECTION
774// By default, we assume that stream redirection is supported on all
775// platforms except known mobile ones.
776# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \
777    GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
778#  define GTEST_HAS_STREAM_REDIRECTION 0
779# else
780#  define GTEST_HAS_STREAM_REDIRECTION 1
781# endif  // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
782#endif  // GTEST_HAS_STREAM_REDIRECTION
783
784// Determines whether to support death tests.
785// Google Test does not support death tests for VC 7.1 and earlier as
786// abort() in a VC 7.1 application compiled as GUI in debug config
787// pops up a dialog window that cannot be suppressed programmatically.
788#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
789     (GTEST_OS_MAC && !GTEST_OS_IOS) || \
790     (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
791     GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
792     GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD)
793# define GTEST_HAS_DEATH_TEST 1
794#endif
795
796// We don't support MSVC 7.1 with exceptions disabled now.  Therefore
797// all the compilers we care about are adequate for supporting
798// value-parameterized tests.
799#define GTEST_HAS_PARAM_TEST 1
800
801// Determines whether to support type-driven tests.
802
803// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
804// Sun Pro CC, IBM Visual Age, and HP aCC support.
805#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
806    defined(__IBMCPP__) || defined(__HP_aCC)
807# define GTEST_HAS_TYPED_TEST 1
808# define GTEST_HAS_TYPED_TEST_P 1
809#endif
810
811// Determines whether to support Combine(). This only makes sense when
812// value-parameterized tests are enabled.  The implementation doesn't
813// work on Sun Studio since it doesn't understand templated conversion
814// operators.
815#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
816# define GTEST_HAS_COMBINE 1
817#endif
818
819// Determines whether the system compiler uses UTF-16 for encoding wide strings.
820#define GTEST_WIDE_STRING_USES_UTF16_ \
821    (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
822
823// Determines whether test results can be streamed to a socket.
824#if GTEST_OS_LINUX
825# define GTEST_CAN_STREAM_RESULTS_ 1
826#endif
827
828// Defines some utility macros.
829
830// The GNU compiler emits a warning if nested "if" statements are followed by
831// an "else" statement and braces are not used to explicitly disambiguate the
832// "else" binding.  This leads to problems with code like:
833//
834//   if (gate)
835//     ASSERT_*(condition) << "Some message";
836//
837// The "switch (0) case 0:" idiom is used to suppress this.
838#ifdef __INTEL_COMPILER
839# define GTEST_AMBIGUOUS_ELSE_BLOCKER_
840#else
841# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default:  // NOLINT
842#endif
843
844// Use this annotation at the end of a struct/class definition to
845// prevent the compiler from optimizing away instances that are never
846// used.  This is useful when all interesting logic happens inside the
847// c'tor and / or d'tor.  Example:
848//
849//   struct Foo {
850//     Foo() { ... }
851//   } GTEST_ATTRIBUTE_UNUSED_;
852//
853// Also use it after a variable or parameter declaration to tell the
854// compiler the variable/parameter does not have to be used.
855#if defined(__GNUC__) && !defined(COMPILER_ICC)
856# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
857#elif defined(__clang__)
858# if __has_attribute(unused)
859#  define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
860# endif
861#endif
862#ifndef GTEST_ATTRIBUTE_UNUSED_
863# define GTEST_ATTRIBUTE_UNUSED_
864#endif
865
866// A macro to disallow operator=
867// This should be used in the private: declarations for a class.
868#define GTEST_DISALLOW_ASSIGN_(type)\
869  void operator=(type const &)
870
871// A macro to disallow copy constructor and operator=
872// This should be used in the private: declarations for a class.
873#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
874  type(type const &);\
875  GTEST_DISALLOW_ASSIGN_(type)
876
877// Tell the compiler to warn about unused return values for functions declared
878// with this macro.  The macro should be used on function declarations
879// following the argument list:
880//
881//   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
882#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
883# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
884#else
885# define GTEST_MUST_USE_RESULT_
886#endif  // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
887
888// MS C++ compiler emits warning when a conditional expression is compile time
889// constant. In some contexts this warning is false positive and needs to be
890// suppressed. Use the following two macros in such cases:
891//
892// GTEST_INTENTIONAL_CONST_COND_PUSH_()
893// while (true) {
894// GTEST_INTENTIONAL_CONST_COND_POP_()
895// }
896# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
897    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
898# define GTEST_INTENTIONAL_CONST_COND_POP_() \
899    GTEST_DISABLE_MSC_WARNINGS_POP_()
900
901// Determine whether the compiler supports Microsoft's Structured Exception
902// Handling.  This is supported by several Windows compilers but generally
903// does not exist on any other system.
904#ifndef GTEST_HAS_SEH
905// The user didn't tell us, so we need to figure it out.
906
907# if defined(_MSC_VER) || defined(__BORLANDC__)
908// These two compilers are known to support SEH.
909#  define GTEST_HAS_SEH 1
910# else
911// Assume no SEH.
912#  define GTEST_HAS_SEH 0
913# endif
914
915#define GTEST_IS_THREADSAFE \
916    (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \
917     || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \
918     || GTEST_HAS_PTHREAD)
919
920#endif  // GTEST_HAS_SEH
921
922#ifdef _MSC_VER
923
924# if GTEST_LINKED_AS_SHARED_LIBRARY
925#  define GTEST_API_ __declspec(dllimport)
926# elif GTEST_CREATE_SHARED_LIBRARY
927#  define GTEST_API_ __declspec(dllexport)
928# endif
929
930#endif  // _MSC_VER
931
932#ifndef GTEST_API_
933# define GTEST_API_
934#endif
935
936#ifdef __GNUC__
937// Ask the compiler to never inline a given function.
938# define GTEST_NO_INLINE_ __attribute__((noinline))
939#else
940# define GTEST_NO_INLINE_
941#endif
942
943// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
944#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
945# define GTEST_HAS_CXXABI_H_ 1
946#else
947# define GTEST_HAS_CXXABI_H_ 0
948#endif
949
950// A function level attribute to disable checking for use of uninitialized
951// memory when built with MemorySanitizer.
952#if defined(__clang__)
953# if __has_feature(memory_sanitizer)
954#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
955       __attribute__((no_sanitize_memory))
956# else
957#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
958# endif  // __has_feature(memory_sanitizer)
959#else
960# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
961#endif  // __clang__
962
963// A function level attribute to disable AddressSanitizer instrumentation.
964#if defined(__clang__)
965# if __has_feature(address_sanitizer)
966#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
967       __attribute__((no_sanitize_address))
968# else
969#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
970# endif  // __has_feature(address_sanitizer)
971#else
972# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
973#endif  // __clang__
974
975// A function level attribute to disable ThreadSanitizer instrumentation.
976#if defined(__clang__)
977# if __has_feature(thread_sanitizer)
978#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
979       __attribute__((no_sanitize_thread))
980# else
981#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
982# endif  // __has_feature(thread_sanitizer)
983#else
984# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
985#endif  // __clang__
986
987namespace testing {
988
989class Message;
990
991#if defined(GTEST_TUPLE_NAMESPACE_)
992// Import tuple and friends into the ::testing namespace.
993// It is part of our interface, having them in ::testing allows us to change
994// their types as needed.
995using GTEST_TUPLE_NAMESPACE_::get;
996using GTEST_TUPLE_NAMESPACE_::make_tuple;
997using GTEST_TUPLE_NAMESPACE_::tuple;
998using GTEST_TUPLE_NAMESPACE_::tuple_size;
999using GTEST_TUPLE_NAMESPACE_::tuple_element;
1000#endif  // defined(GTEST_TUPLE_NAMESPACE_)
1001
1002namespace internal {
1003
1004// A secret type that Google Test users don't know about.  It has no
1005// definition on purpose.  Therefore it's impossible to create a
1006// Secret object, which is what we want.
1007class Secret;
1008
1009// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
1010// expression is true. For example, you could use it to verify the
1011// size of a static array:
1012//
1013//   GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
1014//                         names_incorrect_size);
1015//
1016// or to make sure a struct is smaller than a certain size:
1017//
1018//   GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
1019//
1020// The second argument to the macro is the name of the variable. If
1021// the expression is false, most compilers will issue a warning/error
1022// containing the name of the variable.
1023
1024#if GTEST_LANG_CXX11
1025# define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
1026#else  // !GTEST_LANG_CXX11
1027template <bool>
1028  struct CompileAssert {
1029};
1030
1031# define GTEST_COMPILE_ASSERT_(expr, msg) \
1032  typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
1033      msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
1034#endif  // !GTEST_LANG_CXX11
1035
1036// Implementation details of GTEST_COMPILE_ASSERT_:
1037//
1038// (In C++11, we simply use static_assert instead of the following)
1039//
1040// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
1041//   elements (and thus is invalid) when the expression is false.
1042//
1043// - The simpler definition
1044//
1045//    #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
1046//
1047//   does not work, as gcc supports variable-length arrays whose sizes
1048//   are determined at run-time (this is gcc's extension and not part
1049//   of the C++ standard).  As a result, gcc fails to reject the
1050//   following code with the simple definition:
1051//
1052//     int foo;
1053//     GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
1054//                                      // not a compile-time constant.
1055//
1056// - By using the type CompileAssert<(bool(expr))>, we ensures that
1057//   expr is a compile-time constant.  (Template arguments must be
1058//   determined at compile-time.)
1059//
1060// - The outter parentheses in CompileAssert<(bool(expr))> are necessary
1061//   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
1062//
1063//     CompileAssert<bool(expr)>
1064//
1065//   instead, these compilers will refuse to compile
1066//
1067//     GTEST_COMPILE_ASSERT_(5 > 0, some_message);
1068//
1069//   (They seem to think the ">" in "5 > 0" marks the end of the
1070//   template argument list.)
1071//
1072// - The array size is (bool(expr) ? 1 : -1), instead of simply
1073//
1074//     ((expr) ? 1 : -1).
1075//
1076//   This is to avoid running into a bug in MS VC 7.1, which
1077//   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
1078
1079// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
1080//
1081// This template is declared, but intentionally undefined.
1082template <typename T1, typename T2>
1083struct StaticAssertTypeEqHelper;
1084
1085template <typename T>
1086struct StaticAssertTypeEqHelper<T, T> {
1087  enum { value = true };
1088};
1089
1090// Evaluates to the number of elements in 'array'.
1091#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
1092
1093#if GTEST_HAS_GLOBAL_STRING
1094typedef ::string string;
1095#else
1096typedef ::std::string string;
1097#endif  // GTEST_HAS_GLOBAL_STRING
1098
1099#if GTEST_HAS_GLOBAL_WSTRING
1100typedef ::wstring wstring;
1101#elif GTEST_HAS_STD_WSTRING
1102typedef ::std::wstring wstring;
1103#endif  // GTEST_HAS_GLOBAL_WSTRING
1104
1105// A helper for suppressing warnings on constant condition.  It just
1106// returns 'condition'.
1107GTEST_API_ bool IsTrue(bool condition);
1108
1109// Defines scoped_ptr.
1110
1111// This implementation of scoped_ptr is PARTIAL - it only contains
1112// enough stuff to satisfy Google Test's need.
1113template <typename T>
1114class scoped_ptr {
1115 public:
1116  typedef T element_type;
1117
1118  explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
1119  ~scoped_ptr() { reset(); }
1120
1121  T& operator*() const { return *ptr_; }
1122  T* operator->() const { return ptr_; }
1123  T* get() const { return ptr_; }
1124
1125  T* release() {
1126    T* const ptr = ptr_;
1127    ptr_ = NULL;
1128    return ptr;
1129  }
1130
1131  void reset(T* p = NULL) {
1132    if (p != ptr_) {
1133      if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
1134        delete ptr_;
1135      }
1136      ptr_ = p;
1137    }
1138  }
1139
1140  friend void swap(scoped_ptr& a, scoped_ptr& b) {
1141    using std::swap;
1142    swap(a.ptr_, b.ptr_);
1143  }
1144
1145 private:
1146  T* ptr_;
1147
1148  GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
1149};
1150
1151// Defines RE.
1152
1153// A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
1154// Regular Expression syntax.
1155class GTEST_API_ RE {
1156 public:
1157  // A copy constructor is required by the Standard to initialize object
1158  // references from r-values.
1159  RE(const RE& other) { Init(other.pattern()); }
1160
1161  // Constructs an RE from a string.
1162  RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
1163
1164#if GTEST_HAS_GLOBAL_STRING
1165
1166  RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
1167
1168#endif  // GTEST_HAS_GLOBAL_STRING
1169
1170  RE(const char* regex) { Init(regex); }  // NOLINT
1171  ~RE();
1172
1173  // Returns the string representation of the regex.
1174  const char* pattern() const { return pattern_; }
1175
1176  // FullMatch(str, re) returns true iff regular expression re matches
1177  // the entire str.
1178  // PartialMatch(str, re) returns true iff regular expression re
1179  // matches a substring of str (including str itself).
1180  //
1181  // TODO(wan@google.com): make FullMatch() and PartialMatch() work
1182  // when str contains NUL characters.
1183  static bool FullMatch(const ::std::string& str, const RE& re) {
1184    return FullMatch(str.c_str(), re);
1185  }
1186  static bool PartialMatch(const ::std::string& str, const RE& re) {
1187    return PartialMatch(str.c_str(), re);
1188  }
1189
1190#if GTEST_HAS_GLOBAL_STRING
1191
1192  static bool FullMatch(const ::string& str, const RE& re) {
1193    return FullMatch(str.c_str(), re);
1194  }
1195  static bool PartialMatch(const ::string& str, const RE& re) {
1196    return PartialMatch(str.c_str(), re);
1197  }
1198
1199#endif  // GTEST_HAS_GLOBAL_STRING
1200
1201  static bool FullMatch(const char* str, const RE& re);
1202  static bool PartialMatch(const char* str, const RE& re);
1203
1204 private:
1205  void Init(const char* regex);
1206
1207  // We use a const char* instead of an std::string, as Google Test used to be
1208  // used where std::string is not available.  TODO(wan@google.com): change to
1209  // std::string.
1210  const char* pattern_;
1211  bool is_valid_;
1212
1213#if GTEST_USES_POSIX_RE
1214
1215  regex_t full_regex_;     // For FullMatch().
1216  regex_t partial_regex_;  // For PartialMatch().
1217
1218#else  // GTEST_USES_SIMPLE_RE
1219
1220  const char* full_pattern_;  // For FullMatch();
1221
1222#endif
1223
1224  GTEST_DISALLOW_ASSIGN_(RE);
1225};
1226
1227// Formats a source file path and a line number as they would appear
1228// in an error message from the compiler used to compile this code.
1229GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
1230
1231// Formats a file location for compiler-independent XML output.
1232// Although this function is not platform dependent, we put it next to
1233// FormatFileLocation in order to contrast the two functions.
1234GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
1235                                                               int line);
1236
1237// Defines logging utilities:
1238//   GTEST_LOG_(severity) - logs messages at the specified severity level. The
1239//                          message itself is streamed into the macro.
1240//   LogToStderr()  - directs all log messages to stderr.
1241//   FlushInfoLog() - flushes informational log messages.
1242
1243enum GTestLogSeverity {
1244  GTEST_INFO,
1245  GTEST_WARNING,
1246  GTEST_ERROR,
1247  GTEST_FATAL
1248};
1249
1250// Formats log entry severity, provides a stream object for streaming the
1251// log message, and terminates the message with a newline when going out of
1252// scope.
1253class GTEST_API_ GTestLog {
1254 public:
1255  GTestLog(GTestLogSeverity severity, const char* file, int line);
1256
1257  // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1258  ~GTestLog();
1259
1260  ::std::ostream& GetStream() { return ::std::cerr; }
1261
1262 private:
1263  const GTestLogSeverity severity_;
1264
1265  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
1266};
1267
1268#if !defined(GTEST_LOG_)
1269
1270# define GTEST_LOG_(severity) \
1271    ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
1272                                  __FILE__, __LINE__).GetStream()
1273
1274inline void LogToStderr() {}
1275inline void FlushInfoLog() { fflush(NULL); }
1276
1277#endif  // !defined(GTEST_LOG_)
1278
1279#if !defined(GTEST_CHECK_)
1280// INTERNAL IMPLEMENTATION - DO NOT USE.
1281//
1282// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
1283// is not satisfied.
1284//  Synopsys:
1285//    GTEST_CHECK_(boolean_condition);
1286//     or
1287//    GTEST_CHECK_(boolean_condition) << "Additional message";
1288//
1289//    This checks the condition and if the condition is not satisfied
1290//    it prints message about the condition violation, including the
1291//    condition itself, plus additional message streamed into it, if any,
1292//    and then it aborts the program. It aborts the program irrespective of
1293//    whether it is built in the debug mode or not.
1294# define GTEST_CHECK_(condition) \
1295    GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1296    if (::testing::internal::IsTrue(condition)) \
1297      ; \
1298    else \
1299      GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
1300#endif  // !defined(GTEST_CHECK_)
1301
1302// An all-mode assert to verify that the given POSIX-style function
1303// call returns 0 (indicating success).  Known limitation: this
1304// doesn't expand to a balanced 'if' statement, so enclose the macro
1305// in {} if you need to use it as the only statement in an 'if'
1306// branch.
1307#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
1308  if (const int gtest_error = (posix_call)) \
1309    GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
1310                      << gtest_error
1311
1312#if GTEST_HAS_STD_MOVE_
1313using std::move;
1314#else  // GTEST_HAS_STD_MOVE_
1315template <typename T>
1316const T& move(const T& t) {
1317  return t;
1318}
1319#endif  // GTEST_HAS_STD_MOVE_
1320
1321// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1322//
1323// Use ImplicitCast_ as a safe version of static_cast for upcasting in
1324// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
1325// const Foo*).  When you use ImplicitCast_, the compiler checks that
1326// the cast is safe.  Such explicit ImplicitCast_s are necessary in
1327// surprisingly many situations where C++ demands an exact type match
1328// instead of an argument type convertable to a target type.
1329//
1330// The syntax for using ImplicitCast_ is the same as for static_cast:
1331//
1332//   ImplicitCast_<ToType>(expr)
1333//
1334// ImplicitCast_ would have been part of the C++ standard library,
1335// but the proposal was submitted too late.  It will probably make
1336// its way into the language in the future.
1337//
1338// This relatively ugly name is intentional. It prevents clashes with
1339// similar functions users may have (e.g., implicit_cast). The internal
1340// namespace alone is not enough because the function can be found by ADL.
1341template<typename To>
1342inline To ImplicitCast_(To x) { return x; }
1343
1344// When you upcast (that is, cast a pointer from type Foo to type
1345// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
1346// always succeed.  When you downcast (that is, cast a pointer from
1347// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
1348// how do you know the pointer is really of type SubclassOfFoo?  It
1349// could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
1350// when you downcast, you should use this macro.  In debug mode, we
1351// use dynamic_cast<> to double-check the downcast is legal (we die
1352// if it's not).  In normal mode, we do the efficient static_cast<>
1353// instead.  Thus, it's important to test in debug mode to make sure
1354// the cast is legal!
1355//    This is the only place in the code we should use dynamic_cast<>.
1356// In particular, you SHOULDN'T be using dynamic_cast<> in order to
1357// do RTTI (eg code like this:
1358//    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
1359//    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
1360// You should design the code some other way not to need this.
1361//
1362// This relatively ugly name is intentional. It prevents clashes with
1363// similar functions users may have (e.g., down_cast). The internal
1364// namespace alone is not enough because the function can be found by ADL.
1365template<typename To, typename From>  // use like this: DownCast_<T*>(foo);
1366inline To DownCast_(From* f) {  // so we only accept pointers
1367  // Ensures that To is a sub-type of From *.  This test is here only
1368  // for compile-time type checking, and has no overhead in an
1369  // optimized build at run-time, as it will be optimized away
1370  // completely.
1371  GTEST_INTENTIONAL_CONST_COND_PUSH_()
1372  if (false) {
1373  GTEST_INTENTIONAL_CONST_COND_POP_()
1374    const To to = NULL;
1375    ::testing::internal::ImplicitCast_<From*>(to);
1376  }
1377
1378#if GTEST_HAS_RTTI
1379  // RTTI: debug mode only!
1380  GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL);
1381#endif
1382  return static_cast<To>(f);
1383}
1384
1385// Downcasts the pointer of type Base to Derived.
1386// Derived must be a subclass of Base. The parameter MUST
1387// point to a class of type Derived, not any subclass of it.
1388// When RTTI is available, the function performs a runtime
1389// check to enforce this.
1390template <class Derived, class Base>
1391Derived* CheckedDowncastToActualType(Base* base) {
1392#if GTEST_HAS_RTTI
1393  GTEST_CHECK_(typeid(*base) == typeid(Derived));
1394#endif
1395
1396#if GTEST_HAS_DOWNCAST_
1397  return ::down_cast<Derived*>(base);
1398#elif GTEST_HAS_RTTI
1399  return dynamic_cast<Derived*>(base);  // NOLINT
1400#else
1401  return static_cast<Derived*>(base);  // Poor man's downcast.
1402#endif
1403}
1404
1405#if GTEST_HAS_STREAM_REDIRECTION
1406
1407// Defines the stderr capturer:
1408//   CaptureStdout     - starts capturing stdout.
1409//   GetCapturedStdout - stops capturing stdout and returns the captured string.
1410//   CaptureStderr     - starts capturing stderr.
1411//   GetCapturedStderr - stops capturing stderr and returns the captured string.
1412//
1413GTEST_API_ void CaptureStdout();
1414GTEST_API_ std::string GetCapturedStdout();
1415GTEST_API_ void CaptureStderr();
1416GTEST_API_ std::string GetCapturedStderr();
1417
1418#endif  // GTEST_HAS_STREAM_REDIRECTION
1419
1420// Returns a path to temporary directory.
1421GTEST_API_ std::string TempDir();
1422
1423// Returns the size (in bytes) of a file.
1424GTEST_API_ size_t GetFileSize(FILE* file);
1425
1426// Reads the entire content of a file as a string.
1427GTEST_API_ std::string ReadEntireFile(FILE* file);
1428
1429// All command line arguments.
1430GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs();
1431
1432#if GTEST_HAS_DEATH_TEST
1433
1434const ::std::vector<testing::internal::string>& GetInjectableArgvs();
1435void SetInjectableArgvs(const ::std::vector<testing::internal::string>*
1436                             new_argvs);
1437
1438
1439#endif  // GTEST_HAS_DEATH_TEST
1440
1441// Defines synchronization primitives.
1442#if GTEST_IS_THREADSAFE
1443# if GTEST_HAS_PTHREAD
1444// Sleeps for (roughly) n milliseconds.  This function is only for testing
1445// Google Test's own constructs.  Don't use it in user tests, either
1446// directly or indirectly.
1447inline void SleepMilliseconds(int n) {
1448  const timespec time = {
1449    0,                  // 0 seconds.
1450    n * 1000L * 1000L,  // And n ms.
1451  };
1452  nanosleep(&time, NULL);
1453}
1454# endif  // GTEST_HAS_PTHREAD
1455
1456# if GTEST_HAS_NOTIFICATION_
1457// Notification has already been imported into the namespace.
1458// Nothing to do here.
1459
1460# elif GTEST_HAS_PTHREAD
1461// Allows a controller thread to pause execution of newly created
1462// threads until notified.  Instances of this class must be created
1463// and destroyed in the controller thread.
1464//
1465// This class is only for testing Google Test's own constructs. Do not
1466// use it in user tests, either directly or indirectly.
1467class Notification {
1468 public:
1469  Notification() : notified_(false) {
1470    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
1471  }
1472  ~Notification() {
1473    pthread_mutex_destroy(&mutex_);
1474  }
1475
1476  // Notifies all threads created with this notification to start. Must
1477  // be called from the controller thread.
1478  void Notify() {
1479    pthread_mutex_lock(&mutex_);
1480    notified_ = true;
1481    pthread_mutex_unlock(&mutex_);
1482  }
1483
1484  // Blocks until the controller thread notifies. Must be called from a test
1485  // thread.
1486  void WaitForNotification() {
1487    for (;;) {
1488      pthread_mutex_lock(&mutex_);
1489      const bool notified = notified_;
1490      pthread_mutex_unlock(&mutex_);
1491      if (notified)
1492        break;
1493      SleepMilliseconds(10);
1494    }
1495  }
1496
1497 private:
1498  pthread_mutex_t mutex_;
1499  bool notified_;
1500
1501  GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1502};
1503
1504# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1505
1506GTEST_API_ void SleepMilliseconds(int n);
1507
1508// Provides leak-safe Windows kernel handle ownership.
1509// Used in death tests and in threading support.
1510class GTEST_API_ AutoHandle {
1511 public:
1512  // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
1513  // avoid including <windows.h> in this header file. Including <windows.h> is
1514  // undesirable because it defines a lot of symbols and macros that tend to
1515  // conflict with client code. This assumption is verified by
1516  // WindowsTypesTest.HANDLEIsVoidStar.
1517  typedef void* Handle;
1518  AutoHandle();
1519  explicit AutoHandle(Handle handle);
1520
1521  ~AutoHandle();
1522
1523  Handle Get() const;
1524  void Reset();
1525  void Reset(Handle handle);
1526
1527 private:
1528  // Returns true iff the handle is a valid handle object that can be closed.
1529  bool IsCloseable() const;
1530
1531  Handle handle_;
1532
1533  GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1534};
1535
1536// Allows a controller thread to pause execution of newly created
1537// threads until notified.  Instances of this class must be created
1538// and destroyed in the controller thread.
1539//
1540// This class is only for testing Google Test's own constructs. Do not
1541// use it in user tests, either directly or indirectly.
1542class GTEST_API_ Notification {
1543 public:
1544  Notification();
1545  void Notify();
1546  void WaitForNotification();
1547
1548 private:
1549  AutoHandle event_;
1550
1551  GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1552};
1553# endif  // GTEST_HAS_NOTIFICATION_
1554
1555// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
1556// defined, but we don't want to use MinGW's pthreads implementation, which
1557// has conformance problems with some versions of the POSIX standard.
1558# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1559
1560// As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
1561// Consequently, it cannot select a correct instantiation of ThreadWithParam
1562// in order to call its Run(). Introducing ThreadWithParamBase as a
1563// non-templated base class for ThreadWithParam allows us to bypass this
1564// problem.
1565class ThreadWithParamBase {
1566 public:
1567  virtual ~ThreadWithParamBase() {}
1568  virtual void Run() = 0;
1569};
1570
1571// pthread_create() accepts a pointer to a function type with the C linkage.
1572// According to the Standard (7.5/1), function types with different linkages
1573// are different even if they are otherwise identical.  Some compilers (for
1574// example, SunStudio) treat them as different types.  Since class methods
1575// cannot be defined with C-linkage we need to define a free C-function to
1576// pass into pthread_create().
1577extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
1578  static_cast<ThreadWithParamBase*>(thread)->Run();
1579  return NULL;
1580}
1581
1582// Helper class for testing Google Test's multi-threading constructs.
1583// To use it, write:
1584//
1585//   void ThreadFunc(int param) { /* Do things with param */ }
1586//   Notification thread_can_start;
1587//   ...
1588//   // The thread_can_start parameter is optional; you can supply NULL.
1589//   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
1590//   thread_can_start.Notify();
1591//
1592// These classes are only for testing Google Test's own constructs. Do
1593// not use them in user tests, either directly or indirectly.
1594template <typename T>
1595class ThreadWithParam : public ThreadWithParamBase {
1596 public:
1597  typedef void UserThreadFunc(T);
1598
1599  ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1600      : func_(func),
1601        param_(param),
1602        thread_can_start_(thread_can_start),
1603        finished_(false) {
1604    ThreadWithParamBase* const base = this;
1605    // The thread can be created only after all fields except thread_
1606    // have been initialized.
1607    GTEST_CHECK_POSIX_SUCCESS_(
1608        pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
1609  }
1610  ~ThreadWithParam() { Join(); }
1611
1612  void Join() {
1613    if (!finished_) {
1614      GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
1615      finished_ = true;
1616    }
1617  }
1618
1619  virtual void Run() {
1620    if (thread_can_start_ != NULL)
1621      thread_can_start_->WaitForNotification();
1622    func_(param_);
1623  }
1624
1625 private:
1626  UserThreadFunc* const func_;  // User-supplied thread function.
1627  const T param_;  // User-supplied parameter to the thread function.
1628  // When non-NULL, used to block execution until the controller thread
1629  // notifies.
1630  Notification* const thread_can_start_;
1631  bool finished_;  // true iff we know that the thread function has finished.
1632  pthread_t thread_;  // The native thread object.
1633
1634  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1635};
1636# endif  // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
1637         // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1638
1639# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1640// Mutex and ThreadLocal have already been imported into the namespace.
1641// Nothing to do here.
1642
1643# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1644
1645// Mutex implements mutex on Windows platforms.  It is used in conjunction
1646// with class MutexLock:
1647//
1648//   Mutex mutex;
1649//   ...
1650//   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the
1651//                            // end of the current scope.
1652//
1653// A static Mutex *must* be defined or declared using one of the following
1654// macros:
1655//   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
1656//   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
1657//
1658// (A non-static Mutex is defined/declared in the usual way).
1659class GTEST_API_ Mutex {
1660 public:
1661  enum MutexType { kStatic = 0, kDynamic = 1 };
1662  // We rely on kStaticMutex being 0 as it is to what the linker initializes
1663  // type_ in static mutexes.  critical_section_ will be initialized lazily
1664  // in ThreadSafeLazyInit().
1665  enum StaticConstructorSelector { kStaticMutex = 0 };
1666
1667  // This constructor intentionally does nothing.  It relies on type_ being
1668  // statically initialized to 0 (effectively setting it to kStatic) and on
1669  // ThreadSafeLazyInit() to lazily initialize the rest of the members.
1670  explicit Mutex(StaticConstructorSelector /*dummy*/) {}
1671
1672  Mutex();
1673  ~Mutex();
1674
1675  void Lock();
1676
1677  void Unlock();
1678
1679  // Does nothing if the current thread holds the mutex. Otherwise, crashes
1680  // with high probability.
1681  void AssertHeld();
1682
1683 private:
1684  // Initializes owner_thread_id_ and critical_section_ in static mutexes.
1685  void ThreadSafeLazyInit();
1686
1687  // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx,
1688  // we assume that 0 is an invalid value for thread IDs.
1689  unsigned int owner_thread_id_;
1690
1691  // For static mutexes, we rely on these members being initialized to zeros
1692  // by the linker.
1693  MutexType type_;
1694  long critical_section_init_phase_;  // NOLINT
1695  _RTL_CRITICAL_SECTION* critical_section_;
1696
1697  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1698};
1699
1700# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1701    extern ::testing::internal::Mutex mutex
1702
1703# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1704    ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
1705
1706// We cannot name this class MutexLock because the ctor declaration would
1707// conflict with a macro named MutexLock, which is defined on some
1708// platforms. That macro is used as a defensive measure to prevent against
1709// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1710// "MutexLock l(&mu)".  Hence the typedef trick below.
1711class GTestMutexLock {
1712 public:
1713  explicit GTestMutexLock(Mutex* mutex)
1714      : mutex_(mutex) { mutex_->Lock(); }
1715
1716  ~GTestMutexLock() { mutex_->Unlock(); }
1717
1718 private:
1719  Mutex* const mutex_;
1720
1721  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1722};
1723
1724typedef GTestMutexLock MutexLock;
1725
1726// Base class for ValueHolder<T>.  Allows a caller to hold and delete a value
1727// without knowing its type.
1728class ThreadLocalValueHolderBase {
1729 public:
1730  virtual ~ThreadLocalValueHolderBase() {}
1731};
1732
1733// Provides a way for a thread to send notifications to a ThreadLocal
1734// regardless of its parameter type.
1735class ThreadLocalBase {
1736 public:
1737  // Creates a new ValueHolder<T> object holding a default value passed to
1738  // this ThreadLocal<T>'s constructor and returns it.  It is the caller's
1739  // responsibility not to call this when the ThreadLocal<T> instance already
1740  // has a value on the current thread.
1741  virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
1742
1743 protected:
1744  ThreadLocalBase() {}
1745  virtual ~ThreadLocalBase() {}
1746
1747 private:
1748  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
1749};
1750
1751// Maps a thread to a set of ThreadLocals that have values instantiated on that
1752// thread and notifies them when the thread exits.  A ThreadLocal instance is
1753// expected to persist until all threads it has values on have terminated.
1754class GTEST_API_ ThreadLocalRegistry {
1755 public:
1756  // Registers thread_local_instance as having value on the current thread.
1757  // Returns a value that can be used to identify the thread from other threads.
1758  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
1759      const ThreadLocalBase* thread_local_instance);
1760
1761  // Invoked when a ThreadLocal instance is destroyed.
1762  static void OnThreadLocalDestroyed(
1763      const ThreadLocalBase* thread_local_instance);
1764};
1765
1766class GTEST_API_ ThreadWithParamBase {
1767 public:
1768  void Join();
1769
1770 protected:
1771  class Runnable {
1772   public:
1773    virtual ~Runnable() {}
1774    virtual void Run() = 0;
1775  };
1776
1777  ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
1778  virtual ~ThreadWithParamBase();
1779
1780 private:
1781  AutoHandle thread_;
1782};
1783
1784// Helper class for testing Google Test's multi-threading constructs.
1785template <typename T>
1786class ThreadWithParam : public ThreadWithParamBase {
1787 public:
1788  typedef void UserThreadFunc(T);
1789
1790  ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1791      : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
1792  }
1793  virtual ~ThreadWithParam() {}
1794
1795 private:
1796  class RunnableImpl : public Runnable {
1797   public:
1798    RunnableImpl(UserThreadFunc* func, T param)
1799        : func_(func),
1800          param_(param) {
1801    }
1802    virtual ~RunnableImpl() {}
1803    virtual void Run() {
1804      func_(param_);
1805    }
1806
1807   private:
1808    UserThreadFunc* const func_;
1809    const T param_;
1810
1811    GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
1812  };
1813
1814  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1815};
1816
1817// Implements thread-local storage on Windows systems.
1818//
1819//   // Thread 1
1820//   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.
1821//
1822//   // Thread 2
1823//   tl.set(150);  // Changes the value for thread 2 only.
1824//   EXPECT_EQ(150, tl.get());
1825//
1826//   // Thread 1
1827//   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.
1828//   tl.set(200);
1829//   EXPECT_EQ(200, tl.get());
1830//
1831// The template type argument T must have a public copy constructor.
1832// In addition, the default ThreadLocal constructor requires T to have
1833// a public default constructor.
1834//
1835// The users of a TheadLocal instance have to make sure that all but one
1836// threads (including the main one) using that instance have exited before
1837// destroying it. Otherwise, the per-thread objects managed for them by the
1838// ThreadLocal instance are not guaranteed to be destroyed on all platforms.
1839//
1840// Google Test only uses global ThreadLocal objects.  That means they
1841// will die after main() has returned.  Therefore, no per-thread
1842// object managed by Google Test will be leaked as long as all threads
1843// using Google Test have exited when main() returns.
1844template <typename T>
1845class ThreadLocal : public ThreadLocalBase {
1846 public:
1847  ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
1848  explicit ThreadLocal(const T& value)
1849      : default_factory_(new InstanceValueHolderFactory(value)) {}
1850
1851  ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
1852
1853  T* pointer() { return GetOrCreateValue(); }
1854  const T* pointer() const { return GetOrCreateValue(); }
1855  const T& get() const { return *pointer(); }
1856  void set(const T& value) { *pointer() = value; }
1857
1858 private:
1859  // Holds a value of T.  Can be deleted via its base class without the caller
1860  // knowing the type of T.
1861  class ValueHolder : public ThreadLocalValueHolderBase {
1862   public:
1863    ValueHolder() : value_() {}
1864    explicit ValueHolder(const T& value) : value_(value) {}
1865
1866    T* pointer() { return &value_; }
1867
1868   private:
1869    T value_;
1870    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1871  };
1872
1873
1874  T* GetOrCreateValue() const {
1875    return static_cast<ValueHolder*>(
1876        ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
1877  }
1878
1879  virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
1880    return default_factory_->MakeNewHolder();
1881  }
1882
1883  class ValueHolderFactory {
1884   public:
1885    ValueHolderFactory() {}
1886    virtual ~ValueHolderFactory() {}
1887    virtual ValueHolder* MakeNewHolder() const = 0;
1888
1889   private:
1890    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
1891  };
1892
1893  class DefaultValueHolderFactory : public ValueHolderFactory {
1894   public:
1895    DefaultValueHolderFactory() {}
1896    virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
1897
1898   private:
1899    GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
1900  };
1901
1902  class InstanceValueHolderFactory : public ValueHolderFactory {
1903   public:
1904    explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
1905    virtual ValueHolder* MakeNewHolder() const {
1906      return new ValueHolder(value_);
1907    }
1908
1909   private:
1910    const T value_;  // The value for each thread.
1911
1912    GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
1913  };
1914
1915  scoped_ptr<ValueHolderFactory> default_factory_;
1916
1917  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1918};
1919
1920# elif GTEST_HAS_PTHREAD
1921
1922// MutexBase and Mutex implement mutex on pthreads-based platforms.
1923class MutexBase {
1924 public:
1925  // Acquires this mutex.
1926  void Lock() {
1927    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
1928    owner_ = pthread_self();
1929    has_owner_ = true;
1930  }
1931
1932  // Releases this mutex.
1933  void Unlock() {
1934    // Since the lock is being released the owner_ field should no longer be
1935    // considered valid. We don't protect writing to has_owner_ here, as it's
1936    // the caller's responsibility to ensure that the current thread holds the
1937    // mutex when this is called.
1938    has_owner_ = false;
1939    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
1940  }
1941
1942  // Does nothing if the current thread holds the mutex. Otherwise, crashes
1943  // with high probability.
1944  void AssertHeld() const {
1945    GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
1946        << "The current thread is not holding the mutex @" << this;
1947  }
1948
1949  // A static mutex may be used before main() is entered.  It may even
1950  // be used before the dynamic initialization stage.  Therefore we
1951  // must be able to initialize a static mutex object at link time.
1952  // This means MutexBase has to be a POD and its member variables
1953  // have to be public.
1954 public:
1955  pthread_mutex_t mutex_;  // The underlying pthread mutex.
1956  // has_owner_ indicates whether the owner_ field below contains a valid thread
1957  // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
1958  // accesses to the owner_ field should be protected by a check of this field.
1959  // An alternative might be to memset() owner_ to all zeros, but there's no
1960  // guarantee that a zero'd pthread_t is necessarily invalid or even different
1961  // from pthread_self().
1962  bool has_owner_;
1963  pthread_t owner_;  // The thread holding the mutex.
1964};
1965
1966// Forward-declares a static mutex.
1967#  define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1968     extern ::testing::internal::MutexBase mutex
1969
1970// Defines and statically (i.e. at link time) initializes a static mutex.
1971// The initialization list here does not explicitly initialize each field,
1972// instead relying on default initialization for the unspecified fields. In
1973// particular, the owner_ field (a pthread_t) is not explicitly initialized.
1974// This allows initialization to work whether pthread_t is a scalar or struct.
1975// The flag -Wmissing-field-initializers must not be specified for this to work.
1976#  define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1977     ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false }
1978
1979// The Mutex class can only be used for mutexes created at runtime. It
1980// shares its API with MutexBase otherwise.
1981class Mutex : public MutexBase {
1982 public:
1983  Mutex() {
1984    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
1985    has_owner_ = false;
1986  }
1987  ~Mutex() {
1988    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
1989  }
1990
1991 private:
1992  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1993};
1994
1995// We cannot name this class MutexLock because the ctor declaration would
1996// conflict with a macro named MutexLock, which is defined on some
1997// platforms. That macro is used as a defensive measure to prevent against
1998// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1999// "MutexLock l(&mu)".  Hence the typedef trick below.
2000class GTestMutexLock {
2001 public:
2002  explicit GTestMutexLock(MutexBase* mutex)
2003      : mutex_(mutex) { mutex_->Lock(); }
2004
2005  ~GTestMutexLock() { mutex_->Unlock(); }
2006
2007 private:
2008  MutexBase* const mutex_;
2009
2010  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
2011};
2012
2013typedef GTestMutexLock MutexLock;
2014
2015// Helpers for ThreadLocal.
2016
2017// pthread_key_create() requires DeleteThreadLocalValue() to have
2018// C-linkage.  Therefore it cannot be templatized to access
2019// ThreadLocal<T>.  Hence the need for class
2020// ThreadLocalValueHolderBase.
2021class ThreadLocalValueHolderBase {
2022 public:
2023  virtual ~ThreadLocalValueHolderBase() {}
2024};
2025
2026// Called by pthread to delete thread-local data stored by
2027// pthread_setspecific().
2028extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
2029  delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
2030}
2031
2032// Implements thread-local storage on pthreads-based systems.
2033template <typename T>
2034class ThreadLocal {
2035 public:
2036  ThreadLocal()
2037      : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
2038  explicit ThreadLocal(const T& value)
2039      : key_(CreateKey()),
2040        default_factory_(new InstanceValueHolderFactory(value)) {}
2041
2042  ~ThreadLocal() {
2043    // Destroys the managed object for the current thread, if any.
2044    DeleteThreadLocalValue(pthread_getspecific(key_));
2045
2046    // Releases resources associated with the key.  This will *not*
2047    // delete managed objects for other threads.
2048    GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
2049  }
2050
2051  T* pointer() { return GetOrCreateValue(); }
2052  const T* pointer() const { return GetOrCreateValue(); }
2053  const T& get() const { return *pointer(); }
2054  void set(const T& value) { *pointer() = value; }
2055
2056 private:
2057  // Holds a value of type T.
2058  class ValueHolder : public ThreadLocalValueHolderBase {
2059   public:
2060    ValueHolder() : value_() {}
2061    explicit ValueHolder(const T& value) : value_(value) {}
2062
2063    T* pointer() { return &value_; }
2064
2065   private:
2066    T value_;
2067    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
2068  };
2069
2070  static pthread_key_t CreateKey() {
2071    pthread_key_t key;
2072    // When a thread exits, DeleteThreadLocalValue() will be called on
2073    // the object managed for that thread.
2074    GTEST_CHECK_POSIX_SUCCESS_(
2075        pthread_key_create(&key, &DeleteThreadLocalValue));
2076    return key;
2077  }
2078
2079  T* GetOrCreateValue() const {
2080    ThreadLocalValueHolderBase* const holder =
2081        static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
2082    if (holder != NULL) {
2083      return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
2084    }
2085
2086    ValueHolder* const new_holder = default_factory_->MakeNewHolder();
2087    ThreadLocalValueHolderBase* const holder_base = new_holder;
2088    GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
2089    return new_holder->pointer();
2090  }
2091
2092  class ValueHolderFactory {
2093   public:
2094    ValueHolderFactory() {}
2095    virtual ~ValueHolderFactory() {}
2096    virtual ValueHolder* MakeNewHolder() const = 0;
2097
2098   private:
2099    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
2100  };
2101
2102  class DefaultValueHolderFactory : public ValueHolderFactory {
2103   public:
2104    DefaultValueHolderFactory() {}
2105    virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
2106
2107   private:
2108    GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
2109  };
2110
2111  class InstanceValueHolderFactory : public ValueHolderFactory {
2112   public:
2113    explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
2114    virtual ValueHolder* MakeNewHolder() const {
2115      return new ValueHolder(value_);
2116    }
2117
2118   private:
2119    const T value_;  // The value for each thread.
2120
2121    GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
2122  };
2123
2124  // A key pthreads uses for looking up per-thread values.
2125  const pthread_key_t key_;
2126  scoped_ptr<ValueHolderFactory> default_factory_;
2127
2128  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
2129};
2130
2131# endif  // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
2132
2133#else  // GTEST_IS_THREADSAFE
2134
2135// A dummy implementation of synchronization primitives (mutex, lock,
2136// and thread-local variable).  Necessary for compiling Google Test where
2137// mutex is not supported - using Google Test in multiple threads is not
2138// supported on such platforms.
2139
2140class Mutex {
2141 public:
2142  Mutex() {}
2143  void Lock() {}
2144  void Unlock() {}
2145  void AssertHeld() const {}
2146};
2147
2148# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2149  extern ::testing::internal::Mutex mutex
2150
2151# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
2152
2153// We cannot name this class MutexLock because the ctor declaration would
2154// conflict with a macro named MutexLock, which is defined on some
2155// platforms. That macro is used as a defensive measure to prevent against
2156// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2157// "MutexLock l(&mu)".  Hence the typedef trick below.
2158class GTestMutexLock {
2159 public:
2160  explicit GTestMutexLock(Mutex*) {}  // NOLINT
2161};
2162
2163typedef GTestMutexLock MutexLock;
2164
2165template <typename T>
2166class ThreadLocal {
2167 public:
2168  ThreadLocal() : value_() {}
2169  explicit ThreadLocal(const T& value) : value_(value) {}
2170  T* pointer() { return &value_; }
2171  const T* pointer() const { return &value_; }
2172  const T& get() const { return value_; }
2173  void set(const T& value) { value_ = value; }
2174 private:
2175  T value_;
2176};
2177
2178#endif  // GTEST_IS_THREADSAFE
2179
2180// Returns the number of threads running in the process, or 0 to indicate that
2181// we cannot detect it.
2182GTEST_API_ size_t GetThreadCount();
2183
2184// Passing non-POD classes through ellipsis (...) crashes the ARM
2185// compiler and generates a warning in Sun Studio.  The Nokia Symbian
2186// and the IBM XL C/C++ compiler try to instantiate a copy constructor
2187// for objects passed through ellipsis (...), failing for uncopyable
2188// objects.  We define this to ensure that only POD is passed through
2189// ellipsis on these systems.
2190#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC)
2191// We lose support for NULL detection where the compiler doesn't like
2192// passing non-POD classes through ellipsis (...).
2193# define GTEST_ELLIPSIS_NEEDS_POD_ 1
2194#else
2195# define GTEST_CAN_COMPARE_NULL 1
2196#endif
2197
2198// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
2199// const T& and const T* in a function template.  These compilers
2200// _can_ decide between class template specializations for T and T*,
2201// so a tr1::type_traits-like is_pointer works.
2202#if defined(__SYMBIAN32__) || defined(__IBMCPP__)
2203# define GTEST_NEEDS_IS_POINTER_ 1
2204#endif
2205
2206template <bool bool_value>
2207struct bool_constant {
2208  typedef bool_constant<bool_value> type;
2209  static const bool value = bool_value;
2210};
2211template <bool bool_value> const bool bool_constant<bool_value>::value;
2212
2213typedef bool_constant<false> false_type;
2214typedef bool_constant<true> true_type;
2215
2216template <typename T>
2217struct is_pointer : public false_type {};
2218
2219template <typename T>
2220struct is_pointer<T*> : public true_type {};
2221
2222template <typename Iterator>
2223struct IteratorTraits {
2224  typedef typename Iterator::value_type value_type;
2225};
2226
2227template <typename T>
2228struct IteratorTraits<T*> {
2229  typedef T value_type;
2230};
2231
2232template <typename T>
2233struct IteratorTraits<const T*> {
2234  typedef T value_type;
2235};
2236
2237#if GTEST_OS_WINDOWS
2238# define GTEST_PATH_SEP_ "\\"
2239# define GTEST_HAS_ALT_PATH_SEP_ 1
2240// The biggest signed integer type the compiler supports.
2241typedef __int64 BiggestInt;
2242#else
2243# define GTEST_PATH_SEP_ "/"
2244# define GTEST_HAS_ALT_PATH_SEP_ 0
2245typedef long long BiggestInt;  // NOLINT
2246#endif  // GTEST_OS_WINDOWS
2247
2248// Utilities for char.
2249
2250// isspace(int ch) and friends accept an unsigned char or EOF.  char
2251// may be signed, depending on the compiler (or compiler flags).
2252// Therefore we need to cast a char to unsigned char before calling
2253// isspace(), etc.
2254
2255inline bool IsAlpha(char ch) {
2256  return isalpha(static_cast<unsigned char>(ch)) != 0;
2257}
2258inline bool IsAlNum(char ch) {
2259  return isalnum(static_cast<unsigned char>(ch)) != 0;
2260}
2261inline bool IsDigit(char ch) {
2262  return isdigit(static_cast<unsigned char>(ch)) != 0;
2263}
2264inline bool IsLower(char ch) {
2265  return islower(static_cast<unsigned char>(ch)) != 0;
2266}
2267inline bool IsSpace(char ch) {
2268  return isspace(static_cast<unsigned char>(ch)) != 0;
2269}
2270inline bool IsUpper(char ch) {
2271  return isupper(static_cast<unsigned char>(ch)) != 0;
2272}
2273inline bool IsXDigit(char ch) {
2274  return isxdigit(static_cast<unsigned char>(ch)) != 0;
2275}
2276inline bool IsXDigit(wchar_t ch) {
2277  const unsigned char low_byte = static_cast<unsigned char>(ch);
2278  return ch == low_byte && isxdigit(low_byte) != 0;
2279}
2280
2281inline char ToLower(char ch) {
2282  return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
2283}
2284inline char ToUpper(char ch) {
2285  return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
2286}
2287
2288inline std::string StripTrailingSpaces(std::string str) {
2289  std::string::iterator it = str.end();
2290  while (it != str.begin() && IsSpace(*--it))
2291    it = str.erase(it);
2292  return str;
2293}
2294
2295// The testing::internal::posix namespace holds wrappers for common
2296// POSIX functions.  These wrappers hide the differences between
2297// Windows/MSVC and POSIX systems.  Since some compilers define these
2298// standard functions as macros, the wrapper cannot have the same name
2299// as the wrapped function.
2300
2301namespace posix {
2302
2303// Functions with a different name on Windows.
2304
2305#if GTEST_OS_WINDOWS
2306
2307typedef struct _stat StatStruct;
2308
2309# ifdef __BORLANDC__
2310inline int IsATTY(int fd) { return isatty(fd); }
2311inline int StrCaseCmp(const char* s1, const char* s2) {
2312  return stricmp(s1, s2);
2313}
2314inline char* StrDup(const char* src) { return strdup(src); }
2315# else  // !__BORLANDC__
2316#  if GTEST_OS_WINDOWS_MOBILE
2317inline int IsATTY(int /* fd */) { return 0; }
2318#  else
2319inline int IsATTY(int fd) { return _isatty(fd); }
2320#  endif  // GTEST_OS_WINDOWS_MOBILE
2321inline int StrCaseCmp(const char* s1, const char* s2) {
2322  return _stricmp(s1, s2);
2323}
2324inline char* StrDup(const char* src) { return _strdup(src); }
2325# endif  // __BORLANDC__
2326
2327# if GTEST_OS_WINDOWS_MOBILE
2328inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
2329// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
2330// time and thus not defined there.
2331# else
2332inline int FileNo(FILE* file) { return _fileno(file); }
2333inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
2334inline int RmDir(const char* dir) { return _rmdir(dir); }
2335inline bool IsDir(const StatStruct& st) {
2336  return (_S_IFDIR & st.st_mode) != 0;
2337}
2338# endif  // GTEST_OS_WINDOWS_MOBILE
2339
2340#else
2341
2342typedef struct stat StatStruct;
2343
2344inline int FileNo(FILE* file) { return fileno(file); }
2345inline int IsATTY(int fd) { return isatty(fd); }
2346inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
2347inline int StrCaseCmp(const char* s1, const char* s2) {
2348  return strcasecmp(s1, s2);
2349}
2350inline char* StrDup(const char* src) { return strdup(src); }
2351inline int RmDir(const char* dir) { return rmdir(dir); }
2352inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2353
2354#endif  // GTEST_OS_WINDOWS
2355
2356// Functions deprecated by MSVC 8.0.
2357
2358GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
2359
2360inline const char* StrNCpy(char* dest, const char* src, size_t n) {
2361  return strncpy(dest, src, n);
2362}
2363
2364// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
2365// StrError() aren't needed on Windows CE at this time and thus not
2366// defined there.
2367
2368#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
2369inline int ChDir(const char* dir) { return chdir(dir); }
2370#endif
2371inline FILE* FOpen(const char* path, const char* mode) {
2372  return fopen(path, mode);
2373}
2374#if !GTEST_OS_WINDOWS_MOBILE
2375inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
2376  return freopen(path, mode, stream);
2377}
2378inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
2379#endif
2380inline int FClose(FILE* fp) { return fclose(fp); }
2381#if !GTEST_OS_WINDOWS_MOBILE
2382inline int Read(int fd, void* buf, unsigned int count) {
2383  return static_cast<int>(read(fd, buf, count));
2384}
2385inline int Write(int fd, const void* buf, unsigned int count) {
2386  return static_cast<int>(write(fd, buf, count));
2387}
2388inline int Close(int fd) { return close(fd); }
2389inline const char* StrError(int errnum) { return strerror(errnum); }
2390#endif
2391inline const char* GetEnv(const char* name) {
2392#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT
2393  // We are on Windows CE, which has no environment variables.
2394  static_cast<void>(name);  // To prevent 'unused argument' warning.
2395  return NULL;
2396#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
2397  // Environment variables which we programmatically clear will be set to the
2398  // empty string rather than unset (NULL).  Handle that case.
2399  const char* const env = getenv(name);
2400  return (env != NULL && env[0] != '\0') ? env : NULL;
2401#else
2402  return getenv(name);
2403#endif
2404}
2405
2406GTEST_DISABLE_MSC_WARNINGS_POP_()
2407
2408#if GTEST_OS_WINDOWS_MOBILE
2409// Windows CE has no C library. The abort() function is used in
2410// several places in Google Test. This implementation provides a reasonable
2411// imitation of standard behaviour.
2412void Abort();
2413#else
2414inline void Abort() { abort(); }
2415#endif  // GTEST_OS_WINDOWS_MOBILE
2416
2417}  // namespace posix
2418
2419// MSVC "deprecates" snprintf and issues warnings wherever it is used.  In
2420// order to avoid these warnings, we need to use _snprintf or _snprintf_s on
2421// MSVC-based platforms.  We map the GTEST_SNPRINTF_ macro to the appropriate
2422// function in order to achieve that.  We use macro definition here because
2423// snprintf is a variadic function.
2424#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
2425// MSVC 2005 and above support variadic macros.
2426# define GTEST_SNPRINTF_(buffer, size, format, ...) \
2427     _snprintf_s(buffer, size, size, format, __VA_ARGS__)
2428#elif defined(_MSC_VER)
2429// Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't
2430// complain about _snprintf.
2431# define GTEST_SNPRINTF_ _snprintf
2432#else
2433# define GTEST_SNPRINTF_ snprintf
2434#endif
2435
2436// The maximum number a BiggestInt can represent.  This definition
2437// works no matter BiggestInt is represented in one's complement or
2438// two's complement.
2439//
2440// We cannot rely on numeric_limits in STL, as __int64 and long long
2441// are not part of standard C++ and numeric_limits doesn't need to be
2442// defined for them.
2443const BiggestInt kMaxBiggestInt =
2444    ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
2445
2446// This template class serves as a compile-time function from size to
2447// type.  It maps a size in bytes to a primitive type with that
2448// size. e.g.
2449//
2450//   TypeWithSize<4>::UInt
2451//
2452// is typedef-ed to be unsigned int (unsigned integer made up of 4
2453// bytes).
2454//
2455// Such functionality should belong to STL, but I cannot find it
2456// there.
2457//
2458// Google Test uses this class in the implementation of floating-point
2459// comparison.
2460//
2461// For now it only handles UInt (unsigned int) as that's all Google Test
2462// needs.  Other types can be easily added in the future if need
2463// arises.
2464template <size_t size>
2465class TypeWithSize {
2466 public:
2467  // This prevents the user from using TypeWithSize<N> with incorrect
2468  // values of N.
2469  typedef void UInt;
2470};
2471
2472// The specialization for size 4.
2473template <>
2474class TypeWithSize<4> {
2475 public:
2476  // unsigned int has size 4 in both gcc and MSVC.
2477  //
2478  // As base/basictypes.h doesn't compile on Windows, we cannot use
2479  // uint32, uint64, and etc here.
2480  typedef int Int;
2481  typedef unsigned int UInt;
2482};
2483
2484// The specialization for size 8.
2485template <>
2486class TypeWithSize<8> {
2487 public:
2488#if GTEST_OS_WINDOWS
2489  typedef __int64 Int;
2490  typedef unsigned __int64 UInt;
2491#else
2492  typedef long long Int;  // NOLINT
2493  typedef unsigned long long UInt;  // NOLINT
2494#endif  // GTEST_OS_WINDOWS
2495};
2496
2497// Integer types of known sizes.
2498typedef TypeWithSize<4>::Int Int32;
2499typedef TypeWithSize<4>::UInt UInt32;
2500typedef TypeWithSize<8>::Int Int64;
2501typedef TypeWithSize<8>::UInt UInt64;
2502typedef TypeWithSize<8>::Int TimeInMillis;  // Represents time in milliseconds.
2503
2504// Utilities for command line flags and environment variables.
2505
2506// Macro for referencing flags.
2507#if !defined(GTEST_FLAG)
2508# define GTEST_FLAG(name) FLAGS_gtest_##name
2509#endif  // !defined(GTEST_FLAG)
2510
2511#if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2512# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
2513#endif  // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2514
2515#if !defined(GTEST_DECLARE_bool_)
2516# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
2517
2518// Macros for declaring flags.
2519# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
2520# define GTEST_DECLARE_int32_(name) \
2521    GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
2522#define GTEST_DECLARE_string_(name) \
2523    GTEST_API_ extern ::std::string GTEST_FLAG(name)
2524
2525// Macros for defining flags.
2526#define GTEST_DEFINE_bool_(name, default_val, doc) \
2527    GTEST_API_ bool GTEST_FLAG(name) = (default_val)
2528#define GTEST_DEFINE_int32_(name, default_val, doc) \
2529    GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
2530#define GTEST_DEFINE_string_(name, default_val, doc) \
2531    GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
2532
2533#endif  // !defined(GTEST_DECLARE_bool_)
2534
2535// Thread annotations
2536#if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2537# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
2538# define GTEST_LOCK_EXCLUDED_(locks)
2539#endif  // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2540
2541// Parses 'str' for a 32-bit signed integer.  If successful, writes the result
2542// to *value and returns true; otherwise leaves *value unchanged and returns
2543// false.
2544// TODO(chandlerc): Find a better way to refactor flag and environment parsing
2545// out of both gtest-port.cc and gtest.cc to avoid exporting this utility
2546// function.
2547bool ParseInt32(const Message& src_text, const char* str, Int32* value);
2548
2549// Parses a bool/Int32/string from the environment variable
2550// corresponding to the given Google Test flag.
2551bool BoolFromGTestEnv(const char* flag, bool default_val);
2552GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
2553const char* StringFromGTestEnv(const char* flag, const char* default_val);
2554
2555}  // namespace internal
2556}  // namespace testing
2557
2558#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
2559
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-string.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file declares the String class and functions used internally by
35// Google Test.  They are subject to change without notice. They should not used
36// by code external to Google Test.
37//
38// This header file is #included by <gtest/internal/gtest-internal.h>.
39// It should not be #included by other files.
40
41#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
42#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
43
44#ifdef __BORLANDC__
45// string.h is not guaranteed to provide strcpy on C++ Builder.
46# include <mem.h>
47#endif
48
49#include <string.h>
50#include <string>
51
52#include "gtest/internal/gtest-port.h"
53
54namespace testing {
55namespace internal {
56
57// String - an abstract class holding static string utilities.
58class GTEST_API_ String {
59 public:
60  // Static utility methods
61
62  // Clones a 0-terminated C string, allocating memory using new.  The
63  // caller is responsible for deleting the return value using
64  // delete[].  Returns the cloned string, or NULL if the input is
65  // NULL.
66  //
67  // This is different from strdup() in string.h, which allocates
68  // memory using malloc().
69  static const char* CloneCString(const char* c_str);
70
71#if GTEST_OS_WINDOWS_MOBILE
72  // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
73  // able to pass strings to Win32 APIs on CE we need to convert them
74  // to 'Unicode', UTF-16.
75
76  // Creates a UTF-16 wide string from the given ANSI string, allocating
77  // memory using new. The caller is responsible for deleting the return
78  // value using delete[]. Returns the wide string, or NULL if the
79  // input is NULL.
80  //
81  // The wide string is created using the ANSI codepage (CP_ACP) to
82  // match the behaviour of the ANSI versions of Win32 calls and the
83  // C runtime.
84  static LPCWSTR AnsiToUtf16(const char* c_str);
85
86  // Creates an ANSI string from the given wide string, allocating
87  // memory using new. The caller is responsible for deleting the return
88  // value using delete[]. Returns the ANSI string, or NULL if the
89  // input is NULL.
90  //
91  // The returned string is created using the ANSI codepage (CP_ACP) to
92  // match the behaviour of the ANSI versions of Win32 calls and the
93  // C runtime.
94  static const char* Utf16ToAnsi(LPCWSTR utf16_str);
95#endif
96
97  // Compares two C strings.  Returns true iff they have the same content.
98  //
99  // Unlike strcmp(), this function can handle NULL argument(s).  A
100  // NULL C string is considered different to any non-NULL C string,
101  // including the empty string.
102  static bool CStringEquals(const char* lhs, const char* rhs);
103
104  // Converts a wide C string to a String using the UTF-8 encoding.
105  // NULL will be converted to "(null)".  If an error occurred during
106  // the conversion, "(failed to convert from wide string)" is
107  // returned.
108  static std::string ShowWideCString(const wchar_t* wide_c_str);
109
110  // Compares two wide C strings.  Returns true iff they have the same
111  // content.
112  //
113  // Unlike wcscmp(), this function can handle NULL argument(s).  A
114  // NULL C string is considered different to any non-NULL C string,
115  // including the empty string.
116  static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
117
118  // Compares two C strings, ignoring case.  Returns true iff they
119  // have the same content.
120  //
121  // Unlike strcasecmp(), this function can handle NULL argument(s).
122  // A NULL C string is considered different to any non-NULL C string,
123  // including the empty string.
124  static bool CaseInsensitiveCStringEquals(const char* lhs,
125                                           const char* rhs);
126
127  // Compares two wide C strings, ignoring case.  Returns true iff they
128  // have the same content.
129  //
130  // Unlike wcscasecmp(), this function can handle NULL argument(s).
131  // A NULL C string is considered different to any non-NULL wide C string,
132  // including the empty string.
133  // NB: The implementations on different platforms slightly differ.
134  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
135  // environment variable. On GNU platform this method uses wcscasecmp
136  // which compares according to LC_CTYPE category of the current locale.
137  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
138  // current locale.
139  static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
140                                               const wchar_t* rhs);
141
142  // Returns true iff the given string ends with the given suffix, ignoring
143  // case. Any string is considered to end with an empty suffix.
144  static bool EndsWithCaseInsensitive(
145      const std::string& str, const std::string& suffix);
146
147  // Formats an int value as "%02d".
148  static std::string FormatIntWidth2(int value);  // "%02d" for width == 2
149
150  // Formats an int value as "%X".
151  static std::string FormatHexInt(int value);
152
153  // Formats a byte as "%02X".
154  static std::string FormatByte(unsigned char value);
155
156 private:
157  String();  // Not meant to be instantiated.
158};  // class String
159
160// Gets the content of the stringstream's buffer as an std::string.  Each '\0'
161// character in the buffer is replaced with "\\0".
162GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
163
164}  // namespace internal
165}  // namespace testing
166
167#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-tuple.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gtest-tuple.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2009 Google Inc.
6// All Rights Reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33//
34// Author: wan@google.com (Zhanyong Wan)
35
36// Implements a subset of TR1 tuple needed by Google Test and Google Mock.
37
38#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
39#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
40
41#include <utility>  // For ::std::pair.
42
43// The compiler used in Symbian has a bug that prevents us from declaring the
44// tuple template as a friend (it complains that tuple is redefined).  This
45// hack bypasses the bug by declaring the members that should otherwise be
46// private as public.
47// Sun Studio versions < 12 also have the above bug.
48#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
49# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public:
50#else
51# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \
52    template <GTEST_10_TYPENAMES_(U)> friend class tuple; \
53   private:
54#endif
55
56// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict
57// with our own definitions. Therefore using our own tuple does not work on
58// those compilers.
59#if defined(_MSC_VER) && _MSC_VER >= 1600  /* 1600 is Visual Studio 2010 */
60# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \
61GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers."
62#endif
63
64// GTEST_n_TUPLE_(T) is the type of an n-tuple.
65#define GTEST_0_TUPLE_(T) tuple<>
66#define GTEST_1_TUPLE_(T) tuple<T##0, void, void, void, void, void, void, \
67    void, void, void>
68#define GTEST_2_TUPLE_(T) tuple<T##0, T##1, void, void, void, void, void, \
69    void, void, void>
70#define GTEST_3_TUPLE_(T) tuple<T##0, T##1, T##2, void, void, void, void, \
71    void, void, void>
72#define GTEST_4_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, void, void, void, \
73    void, void, void>
74#define GTEST_5_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, void, void, \
75    void, void, void>
76#define GTEST_6_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, void, \
77    void, void, void>
78#define GTEST_7_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
79    void, void, void>
80#define GTEST_8_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
81    T##7, void, void>
82#define GTEST_9_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
83    T##7, T##8, void>
84#define GTEST_10_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
85    T##7, T##8, T##9>
86
87// GTEST_n_TYPENAMES_(T) declares a list of n typenames.
88#define GTEST_0_TYPENAMES_(T)
89#define GTEST_1_TYPENAMES_(T) typename T##0
90#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1
91#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2
92#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
93    typename T##3
94#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
95    typename T##3, typename T##4
96#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
97    typename T##3, typename T##4, typename T##5
98#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
99    typename T##3, typename T##4, typename T##5, typename T##6
100#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
101    typename T##3, typename T##4, typename T##5, typename T##6, typename T##7
102#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
103    typename T##3, typename T##4, typename T##5, typename T##6, \
104    typename T##7, typename T##8
105#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
106    typename T##3, typename T##4, typename T##5, typename T##6, \
107    typename T##7, typename T##8, typename T##9
108
109// In theory, defining stuff in the ::std namespace is undefined
110// behavior.  We can do this as we are playing the role of a standard
111// library vendor.
112namespace std {
113namespace tr1 {
114
115template <typename T0 = void, typename T1 = void, typename T2 = void,
116    typename T3 = void, typename T4 = void, typename T5 = void,
117    typename T6 = void, typename T7 = void, typename T8 = void,
118    typename T9 = void>
119class tuple;
120
121// Anything in namespace gtest_internal is Google Test's INTERNAL
122// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code.
123namespace gtest_internal {
124
125// ByRef<T>::type is T if T is a reference; otherwise it's const T&.
126template <typename T>
127struct ByRef { typedef const T& type; };  // NOLINT
128template <typename T>
129struct ByRef<T&> { typedef T& type; };  // NOLINT
130
131// A handy wrapper for ByRef.
132#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef<T>::type
133
134// AddRef<T>::type is T if T is a reference; otherwise it's T&.  This
135// is the same as tr1::add_reference<T>::type.
136template <typename T>
137struct AddRef { typedef T& type; };  // NOLINT
138template <typename T>
139struct AddRef<T&> { typedef T& type; };  // NOLINT
140
141// A handy wrapper for AddRef.
142#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef<T>::type
143
144// A helper for implementing get<k>().
145template <int k> class Get;
146
147// A helper for implementing tuple_element<k, T>.  kIndexValid is true
148// iff k < the number of fields in tuple type T.
149template <bool kIndexValid, int kIndex, class Tuple>
150struct TupleElement;
151
152template <GTEST_10_TYPENAMES_(T)>
153struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > {
154  typedef T0 type;
155};
156
157template <GTEST_10_TYPENAMES_(T)>
158struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > {
159  typedef T1 type;
160};
161
162template <GTEST_10_TYPENAMES_(T)>
163struct TupleElement<true, 2, GTEST_10_TUPLE_(T) > {
164  typedef T2 type;
165};
166
167template <GTEST_10_TYPENAMES_(T)>
168struct TupleElement<true, 3, GTEST_10_TUPLE_(T) > {
169  typedef T3 type;
170};
171
172template <GTEST_10_TYPENAMES_(T)>
173struct TupleElement<true, 4, GTEST_10_TUPLE_(T) > {
174  typedef T4 type;
175};
176
177template <GTEST_10_TYPENAMES_(T)>
178struct TupleElement<true, 5, GTEST_10_TUPLE_(T) > {
179  typedef T5 type;
180};
181
182template <GTEST_10_TYPENAMES_(T)>
183struct TupleElement<true, 6, GTEST_10_TUPLE_(T) > {
184  typedef T6 type;
185};
186
187template <GTEST_10_TYPENAMES_(T)>
188struct TupleElement<true, 7, GTEST_10_TUPLE_(T) > {
189  typedef T7 type;
190};
191
192template <GTEST_10_TYPENAMES_(T)>
193struct TupleElement<true, 8, GTEST_10_TUPLE_(T) > {
194  typedef T8 type;
195};
196
197template <GTEST_10_TYPENAMES_(T)>
198struct TupleElement<true, 9, GTEST_10_TUPLE_(T) > {
199  typedef T9 type;
200};
201
202}  // namespace gtest_internal
203
204template <>
205class tuple<> {
206 public:
207  tuple() {}
208  tuple(const tuple& /* t */)  {}
209  tuple& operator=(const tuple& /* t */) { return *this; }
210};
211
212template <GTEST_1_TYPENAMES_(T)>
213class GTEST_1_TUPLE_(T) {
214 public:
215  template <int k> friend class gtest_internal::Get;
216
217  tuple() : f0_() {}
218
219  explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {}
220
221  tuple(const tuple& t) : f0_(t.f0_) {}
222
223  template <GTEST_1_TYPENAMES_(U)>
224  tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {}
225
226  tuple& operator=(const tuple& t) { return CopyFrom(t); }
227
228  template <GTEST_1_TYPENAMES_(U)>
229  tuple& operator=(const GTEST_1_TUPLE_(U)& t) {
230    return CopyFrom(t);
231  }
232
233  GTEST_DECLARE_TUPLE_AS_FRIEND_
234
235  template <GTEST_1_TYPENAMES_(U)>
236  tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) {
237    f0_ = t.f0_;
238    return *this;
239  }
240
241  T0 f0_;
242};
243
244template <GTEST_2_TYPENAMES_(T)>
245class GTEST_2_TUPLE_(T) {
246 public:
247  template <int k> friend class gtest_internal::Get;
248
249  tuple() : f0_(), f1_() {}
250
251  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0),
252      f1_(f1) {}
253
254  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {}
255
256  template <GTEST_2_TYPENAMES_(U)>
257  tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {}
258  template <typename U0, typename U1>
259  tuple(const ::std::pair<U0, U1>& p) : f0_(p.first), f1_(p.second) {}
260
261  tuple& operator=(const tuple& t) { return CopyFrom(t); }
262
263  template <GTEST_2_TYPENAMES_(U)>
264  tuple& operator=(const GTEST_2_TUPLE_(U)& t) {
265    return CopyFrom(t);
266  }
267  template <typename U0, typename U1>
268  tuple& operator=(const ::std::pair<U0, U1>& p) {
269    f0_ = p.first;
270    f1_ = p.second;
271    return *this;
272  }
273
274  GTEST_DECLARE_TUPLE_AS_FRIEND_
275
276  template <GTEST_2_TYPENAMES_(U)>
277  tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) {
278    f0_ = t.f0_;
279    f1_ = t.f1_;
280    return *this;
281  }
282
283  T0 f0_;
284  T1 f1_;
285};
286
287template <GTEST_3_TYPENAMES_(T)>
288class GTEST_3_TUPLE_(T) {
289 public:
290  template <int k> friend class gtest_internal::Get;
291
292  tuple() : f0_(), f1_(), f2_() {}
293
294  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
295      GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {}
296
297  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {}
298
299  template <GTEST_3_TYPENAMES_(U)>
300  tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {}
301
302  tuple& operator=(const tuple& t) { return CopyFrom(t); }
303
304  template <GTEST_3_TYPENAMES_(U)>
305  tuple& operator=(const GTEST_3_TUPLE_(U)& t) {
306    return CopyFrom(t);
307  }
308
309  GTEST_DECLARE_TUPLE_AS_FRIEND_
310
311  template <GTEST_3_TYPENAMES_(U)>
312  tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) {
313    f0_ = t.f0_;
314    f1_ = t.f1_;
315    f2_ = t.f2_;
316    return *this;
317  }
318
319  T0 f0_;
320  T1 f1_;
321  T2 f2_;
322};
323
324template <GTEST_4_TYPENAMES_(T)>
325class GTEST_4_TUPLE_(T) {
326 public:
327  template <int k> friend class gtest_internal::Get;
328
329  tuple() : f0_(), f1_(), f2_(), f3_() {}
330
331  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
332      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2),
333      f3_(f3) {}
334
335  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {}
336
337  template <GTEST_4_TYPENAMES_(U)>
338  tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
339      f3_(t.f3_) {}
340
341  tuple& operator=(const tuple& t) { return CopyFrom(t); }
342
343  template <GTEST_4_TYPENAMES_(U)>
344  tuple& operator=(const GTEST_4_TUPLE_(U)& t) {
345    return CopyFrom(t);
346  }
347
348  GTEST_DECLARE_TUPLE_AS_FRIEND_
349
350  template <GTEST_4_TYPENAMES_(U)>
351  tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) {
352    f0_ = t.f0_;
353    f1_ = t.f1_;
354    f2_ = t.f2_;
355    f3_ = t.f3_;
356    return *this;
357  }
358
359  T0 f0_;
360  T1 f1_;
361  T2 f2_;
362  T3 f3_;
363};
364
365template <GTEST_5_TYPENAMES_(T)>
366class GTEST_5_TUPLE_(T) {
367 public:
368  template <int k> friend class gtest_internal::Get;
369
370  tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {}
371
372  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
373      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3,
374      GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {}
375
376  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
377      f4_(t.f4_) {}
378
379  template <GTEST_5_TYPENAMES_(U)>
380  tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
381      f3_(t.f3_), f4_(t.f4_) {}
382
383  tuple& operator=(const tuple& t) { return CopyFrom(t); }
384
385  template <GTEST_5_TYPENAMES_(U)>
386  tuple& operator=(const GTEST_5_TUPLE_(U)& t) {
387    return CopyFrom(t);
388  }
389
390  GTEST_DECLARE_TUPLE_AS_FRIEND_
391
392  template <GTEST_5_TYPENAMES_(U)>
393  tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) {
394    f0_ = t.f0_;
395    f1_ = t.f1_;
396    f2_ = t.f2_;
397    f3_ = t.f3_;
398    f4_ = t.f4_;
399    return *this;
400  }
401
402  T0 f0_;
403  T1 f1_;
404  T2 f2_;
405  T3 f3_;
406  T4 f4_;
407};
408
409template <GTEST_6_TYPENAMES_(T)>
410class GTEST_6_TUPLE_(T) {
411 public:
412  template <int k> friend class gtest_internal::Get;
413
414  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {}
415
416  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
417      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
418      GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
419      f5_(f5) {}
420
421  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
422      f4_(t.f4_), f5_(t.f5_) {}
423
424  template <GTEST_6_TYPENAMES_(U)>
425  tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
426      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {}
427
428  tuple& operator=(const tuple& t) { return CopyFrom(t); }
429
430  template <GTEST_6_TYPENAMES_(U)>
431  tuple& operator=(const GTEST_6_TUPLE_(U)& t) {
432    return CopyFrom(t);
433  }
434
435  GTEST_DECLARE_TUPLE_AS_FRIEND_
436
437  template <GTEST_6_TYPENAMES_(U)>
438  tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) {
439    f0_ = t.f0_;
440    f1_ = t.f1_;
441    f2_ = t.f2_;
442    f3_ = t.f3_;
443    f4_ = t.f4_;
444    f5_ = t.f5_;
445    return *this;
446  }
447
448  T0 f0_;
449  T1 f1_;
450  T2 f2_;
451  T3 f3_;
452  T4 f4_;
453  T5 f5_;
454};
455
456template <GTEST_7_TYPENAMES_(T)>
457class GTEST_7_TUPLE_(T) {
458 public:
459  template <int k> friend class gtest_internal::Get;
460
461  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {}
462
463  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
464      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
465      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2),
466      f3_(f3), f4_(f4), f5_(f5), f6_(f6) {}
467
468  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
469      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {}
470
471  template <GTEST_7_TYPENAMES_(U)>
472  tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
473      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {}
474
475  tuple& operator=(const tuple& t) { return CopyFrom(t); }
476
477  template <GTEST_7_TYPENAMES_(U)>
478  tuple& operator=(const GTEST_7_TUPLE_(U)& t) {
479    return CopyFrom(t);
480  }
481
482  GTEST_DECLARE_TUPLE_AS_FRIEND_
483
484  template <GTEST_7_TYPENAMES_(U)>
485  tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) {
486    f0_ = t.f0_;
487    f1_ = t.f1_;
488    f2_ = t.f2_;
489    f3_ = t.f3_;
490    f4_ = t.f4_;
491    f5_ = t.f5_;
492    f6_ = t.f6_;
493    return *this;
494  }
495
496  T0 f0_;
497  T1 f1_;
498  T2 f2_;
499  T3 f3_;
500  T4 f4_;
501  T5 f5_;
502  T6 f6_;
503};
504
505template <GTEST_8_TYPENAMES_(T)>
506class GTEST_8_TUPLE_(T) {
507 public:
508  template <int k> friend class gtest_internal::Get;
509
510  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {}
511
512  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
513      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
514      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6,
515      GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
516      f5_(f5), f6_(f6), f7_(f7) {}
517
518  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
519      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {}
520
521  template <GTEST_8_TYPENAMES_(U)>
522  tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
523      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {}
524
525  tuple& operator=(const tuple& t) { return CopyFrom(t); }
526
527  template <GTEST_8_TYPENAMES_(U)>
528  tuple& operator=(const GTEST_8_TUPLE_(U)& t) {
529    return CopyFrom(t);
530  }
531
532  GTEST_DECLARE_TUPLE_AS_FRIEND_
533
534  template <GTEST_8_TYPENAMES_(U)>
535  tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) {
536    f0_ = t.f0_;
537    f1_ = t.f1_;
538    f2_ = t.f2_;
539    f3_ = t.f3_;
540    f4_ = t.f4_;
541    f5_ = t.f5_;
542    f6_ = t.f6_;
543    f7_ = t.f7_;
544    return *this;
545  }
546
547  T0 f0_;
548  T1 f1_;
549  T2 f2_;
550  T3 f3_;
551  T4 f4_;
552  T5 f5_;
553  T6 f6_;
554  T7 f7_;
555};
556
557template <GTEST_9_TYPENAMES_(T)>
558class GTEST_9_TUPLE_(T) {
559 public:
560  template <int k> friend class gtest_internal::Get;
561
562  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {}
563
564  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
565      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
566      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7,
567      GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
568      f5_(f5), f6_(f6), f7_(f7), f8_(f8) {}
569
570  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
571      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {}
572
573  template <GTEST_9_TYPENAMES_(U)>
574  tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
575      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {}
576
577  tuple& operator=(const tuple& t) { return CopyFrom(t); }
578
579  template <GTEST_9_TYPENAMES_(U)>
580  tuple& operator=(const GTEST_9_TUPLE_(U)& t) {
581    return CopyFrom(t);
582  }
583
584  GTEST_DECLARE_TUPLE_AS_FRIEND_
585
586  template <GTEST_9_TYPENAMES_(U)>
587  tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) {
588    f0_ = t.f0_;
589    f1_ = t.f1_;
590    f2_ = t.f2_;
591    f3_ = t.f3_;
592    f4_ = t.f4_;
593    f5_ = t.f5_;
594    f6_ = t.f6_;
595    f7_ = t.f7_;
596    f8_ = t.f8_;
597    return *this;
598  }
599
600  T0 f0_;
601  T1 f1_;
602  T2 f2_;
603  T3 f3_;
604  T4 f4_;
605  T5 f5_;
606  T6 f6_;
607  T7 f7_;
608  T8 f8_;
609};
610
611template <GTEST_10_TYPENAMES_(T)>
612class tuple {
613 public:
614  template <int k> friend class gtest_internal::Get;
615
616  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(),
617      f9_() {}
618
619  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
620      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
621      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7,
622      GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2),
623      f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {}
624
625  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
626      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {}
627
628  template <GTEST_10_TYPENAMES_(U)>
629  tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
630      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_),
631      f9_(t.f9_) {}
632
633  tuple& operator=(const tuple& t) { return CopyFrom(t); }
634
635  template <GTEST_10_TYPENAMES_(U)>
636  tuple& operator=(const GTEST_10_TUPLE_(U)& t) {
637    return CopyFrom(t);
638  }
639
640  GTEST_DECLARE_TUPLE_AS_FRIEND_
641
642  template <GTEST_10_TYPENAMES_(U)>
643  tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) {
644    f0_ = t.f0_;
645    f1_ = t.f1_;
646    f2_ = t.f2_;
647    f3_ = t.f3_;
648    f4_ = t.f4_;
649    f5_ = t.f5_;
650    f6_ = t.f6_;
651    f7_ = t.f7_;
652    f8_ = t.f8_;
653    f9_ = t.f9_;
654    return *this;
655  }
656
657  T0 f0_;
658  T1 f1_;
659  T2 f2_;
660  T3 f3_;
661  T4 f4_;
662  T5 f5_;
663  T6 f6_;
664  T7 f7_;
665  T8 f8_;
666  T9 f9_;
667};
668
669// 6.1.3.2 Tuple creation functions.
670
671// Known limitations: we don't support passing an
672// std::tr1::reference_wrapper<T> to make_tuple().  And we don't
673// implement tie().
674
675inline tuple<> make_tuple() { return tuple<>(); }
676
677template <GTEST_1_TYPENAMES_(T)>
678inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) {
679  return GTEST_1_TUPLE_(T)(f0);
680}
681
682template <GTEST_2_TYPENAMES_(T)>
683inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) {
684  return GTEST_2_TUPLE_(T)(f0, f1);
685}
686
687template <GTEST_3_TYPENAMES_(T)>
688inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) {
689  return GTEST_3_TUPLE_(T)(f0, f1, f2);
690}
691
692template <GTEST_4_TYPENAMES_(T)>
693inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
694    const T3& f3) {
695  return GTEST_4_TUPLE_(T)(f0, f1, f2, f3);
696}
697
698template <GTEST_5_TYPENAMES_(T)>
699inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
700    const T3& f3, const T4& f4) {
701  return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4);
702}
703
704template <GTEST_6_TYPENAMES_(T)>
705inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
706    const T3& f3, const T4& f4, const T5& f5) {
707  return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5);
708}
709
710template <GTEST_7_TYPENAMES_(T)>
711inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
712    const T3& f3, const T4& f4, const T5& f5, const T6& f6) {
713  return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6);
714}
715
716template <GTEST_8_TYPENAMES_(T)>
717inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
718    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) {
719  return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7);
720}
721
722template <GTEST_9_TYPENAMES_(T)>
723inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
724    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7,
725    const T8& f8) {
726  return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8);
727}
728
729template <GTEST_10_TYPENAMES_(T)>
730inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
731    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7,
732    const T8& f8, const T9& f9) {
733  return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9);
734}
735
736// 6.1.3.3 Tuple helper classes.
737
738template <typename Tuple> struct tuple_size;
739
740template <GTEST_0_TYPENAMES_(T)>
741struct tuple_size<GTEST_0_TUPLE_(T) > {
742  static const int value = 0;
743};
744
745template <GTEST_1_TYPENAMES_(T)>
746struct tuple_size<GTEST_1_TUPLE_(T) > {
747  static const int value = 1;
748};
749
750template <GTEST_2_TYPENAMES_(T)>
751struct tuple_size<GTEST_2_TUPLE_(T) > {
752  static const int value = 2;
753};
754
755template <GTEST_3_TYPENAMES_(T)>
756struct tuple_size<GTEST_3_TUPLE_(T) > {
757  static const int value = 3;
758};
759
760template <GTEST_4_TYPENAMES_(T)>
761struct tuple_size<GTEST_4_TUPLE_(T) > {
762  static const int value = 4;
763};
764
765template <GTEST_5_TYPENAMES_(T)>
766struct tuple_size<GTEST_5_TUPLE_(T) > {
767  static const int value = 5;
768};
769
770template <GTEST_6_TYPENAMES_(T)>
771struct tuple_size<GTEST_6_TUPLE_(T) > {
772  static const int value = 6;
773};
774
775template <GTEST_7_TYPENAMES_(T)>
776struct tuple_size<GTEST_7_TUPLE_(T) > {
777  static const int value = 7;
778};
779
780template <GTEST_8_TYPENAMES_(T)>
781struct tuple_size<GTEST_8_TUPLE_(T) > {
782  static const int value = 8;
783};
784
785template <GTEST_9_TYPENAMES_(T)>
786struct tuple_size<GTEST_9_TUPLE_(T) > {
787  static const int value = 9;
788};
789
790template <GTEST_10_TYPENAMES_(T)>
791struct tuple_size<GTEST_10_TUPLE_(T) > {
792  static const int value = 10;
793};
794
795template <int k, class Tuple>
796struct tuple_element {
797  typedef typename gtest_internal::TupleElement<
798      k < (tuple_size<Tuple>::value), k, Tuple>::type type;
799};
800
801#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element<k, Tuple >::type
802
803// 6.1.3.4 Element access.
804
805namespace gtest_internal {
806
807template <>
808class Get<0> {
809 public:
810  template <class Tuple>
811  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple))
812  Field(Tuple& t) { return t.f0_; }  // NOLINT
813
814  template <class Tuple>
815  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple))
816  ConstField(const Tuple& t) { return t.f0_; }
817};
818
819template <>
820class Get<1> {
821 public:
822  template <class Tuple>
823  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple))
824  Field(Tuple& t) { return t.f1_; }  // NOLINT
825
826  template <class Tuple>
827  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple))
828  ConstField(const Tuple& t) { return t.f1_; }
829};
830
831template <>
832class Get<2> {
833 public:
834  template <class Tuple>
835  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple))
836  Field(Tuple& t) { return t.f2_; }  // NOLINT
837
838  template <class Tuple>
839  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple))
840  ConstField(const Tuple& t) { return t.f2_; }
841};
842
843template <>
844class Get<3> {
845 public:
846  template <class Tuple>
847  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple))
848  Field(Tuple& t) { return t.f3_; }  // NOLINT
849
850  template <class Tuple>
851  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple))
852  ConstField(const Tuple& t) { return t.f3_; }
853};
854
855template <>
856class Get<4> {
857 public:
858  template <class Tuple>
859  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple))
860  Field(Tuple& t) { return t.f4_; }  // NOLINT
861
862  template <class Tuple>
863  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple))
864  ConstField(const Tuple& t) { return t.f4_; }
865};
866
867template <>
868class Get<5> {
869 public:
870  template <class Tuple>
871  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple))
872  Field(Tuple& t) { return t.f5_; }  // NOLINT
873
874  template <class Tuple>
875  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple))
876  ConstField(const Tuple& t) { return t.f5_; }
877};
878
879template <>
880class Get<6> {
881 public:
882  template <class Tuple>
883  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple))
884  Field(Tuple& t) { return t.f6_; }  // NOLINT
885
886  template <class Tuple>
887  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple))
888  ConstField(const Tuple& t) { return t.f6_; }
889};
890
891template <>
892class Get<7> {
893 public:
894  template <class Tuple>
895  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple))
896  Field(Tuple& t) { return t.f7_; }  // NOLINT
897
898  template <class Tuple>
899  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple))
900  ConstField(const Tuple& t) { return t.f7_; }
901};
902
903template <>
904class Get<8> {
905 public:
906  template <class Tuple>
907  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple))
908  Field(Tuple& t) { return t.f8_; }  // NOLINT
909
910  template <class Tuple>
911  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple))
912  ConstField(const Tuple& t) { return t.f8_; }
913};
914
915template <>
916class Get<9> {
917 public:
918  template <class Tuple>
919  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple))
920  Field(Tuple& t) { return t.f9_; }  // NOLINT
921
922  template <class Tuple>
923  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple))
924  ConstField(const Tuple& t) { return t.f9_; }
925};
926
927}  // namespace gtest_internal
928
929template <int k, GTEST_10_TYPENAMES_(T)>
930GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T)))
931get(GTEST_10_TUPLE_(T)& t) {
932  return gtest_internal::Get<k>::Field(t);
933}
934
935template <int k, GTEST_10_TYPENAMES_(T)>
936GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k,  GTEST_10_TUPLE_(T)))
937get(const GTEST_10_TUPLE_(T)& t) {
938  return gtest_internal::Get<k>::ConstField(t);
939}
940
941// 6.1.3.5 Relational operators
942
943// We only implement == and !=, as we don't have a need for the rest yet.
944
945namespace gtest_internal {
946
947// SameSizeTuplePrefixComparator<k, k>::Eq(t1, t2) returns true if the
948// first k fields of t1 equals the first k fields of t2.
949// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if
950// k1 != k2.
951template <int kSize1, int kSize2>
952struct SameSizeTuplePrefixComparator;
953
954template <>
955struct SameSizeTuplePrefixComparator<0, 0> {
956  template <class Tuple1, class Tuple2>
957  static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) {
958    return true;
959  }
960};
961
962template <int k>
963struct SameSizeTuplePrefixComparator<k, k> {
964  template <class Tuple1, class Tuple2>
965  static bool Eq(const Tuple1& t1, const Tuple2& t2) {
966    return SameSizeTuplePrefixComparator<k - 1, k - 1>::Eq(t1, t2) &&
967        ::std::tr1::get<k - 1>(t1) == ::std::tr1::get<k - 1>(t2);
968  }
969};
970
971}  // namespace gtest_internal
972
973template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>
974inline bool operator==(const GTEST_10_TUPLE_(T)& t,
975                       const GTEST_10_TUPLE_(U)& u) {
976  return gtest_internal::SameSizeTuplePrefixComparator<
977      tuple_size<GTEST_10_TUPLE_(T) >::value,
978      tuple_size<GTEST_10_TUPLE_(U) >::value>::Eq(t, u);
979}
980
981template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>
982inline bool operator!=(const GTEST_10_TUPLE_(T)& t,
983                       const GTEST_10_TUPLE_(U)& u) { return !(t == u); }
984
985// 6.1.4 Pairs.
986// Unimplemented.
987
988}  // namespace tr1
989}  // namespace std
990
991#undef GTEST_0_TUPLE_
992#undef GTEST_1_TUPLE_
993#undef GTEST_2_TUPLE_
994#undef GTEST_3_TUPLE_
995#undef GTEST_4_TUPLE_
996#undef GTEST_5_TUPLE_
997#undef GTEST_6_TUPLE_
998#undef GTEST_7_TUPLE_
999#undef GTEST_8_TUPLE_
1000#undef GTEST_9_TUPLE_
1001#undef GTEST_10_TUPLE_
1002
1003#undef GTEST_0_TYPENAMES_
1004#undef GTEST_1_TYPENAMES_
1005#undef GTEST_2_TYPENAMES_
1006#undef GTEST_3_TYPENAMES_
1007#undef GTEST_4_TYPENAMES_
1008#undef GTEST_5_TYPENAMES_
1009#undef GTEST_6_TYPENAMES_
1010#undef GTEST_7_TYPENAMES_
1011#undef GTEST_8_TYPENAMES_
1012#undef GTEST_9_TYPENAMES_
1013#undef GTEST_10_TYPENAMES_
1014
1015#undef GTEST_DECLARE_TUPLE_AS_FRIEND_
1016#undef GTEST_BY_REF_
1017#undef GTEST_ADD_REF_
1018#undef GTEST_TUPLE_ELEMENT_
1019
1020#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-tuple.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$var n = 10  $$ Maximum number of tuple fields we want to support.
3$$ This meta comment fixes auto-indentation in Emacs. }}
4// Copyright 2009 Google Inc.
5// All Rights Reserved.
6//
7// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions are
9// met:
10//
11//     * Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//     * Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following disclaimer
15// in the documentation and/or other materials provided with the
16// distribution.
17//     * Neither the name of Google Inc. nor the names of its
18// contributors may be used to endorse or promote products derived from
19// this software without specific prior written permission.
20//
21// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32//
33// Author: wan@google.com (Zhanyong Wan)
34
35// Implements a subset of TR1 tuple needed by Google Test and Google Mock.
36
37#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
38#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
39
40#include <utility>  // For ::std::pair.
41
42// The compiler used in Symbian has a bug that prevents us from declaring the
43// tuple template as a friend (it complains that tuple is redefined).  This
44// hack bypasses the bug by declaring the members that should otherwise be
45// private as public.
46// Sun Studio versions < 12 also have the above bug.
47#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
48# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public:
49#else
50# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \
51    template <GTEST_$(n)_TYPENAMES_(U)> friend class tuple; \
52   private:
53#endif
54
55// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict
56// with our own definitions. Therefore using our own tuple does not work on
57// those compilers.
58#if defined(_MSC_VER) && _MSC_VER >= 1600  /* 1600 is Visual Studio 2010 */
59# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \
60GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers."
61#endif
62
63
64$range i 0..n-1
65$range j 0..n
66$range k 1..n
67// GTEST_n_TUPLE_(T) is the type of an n-tuple.
68#define GTEST_0_TUPLE_(T) tuple<>
69
70$for k [[
71$range m 0..k-1
72$range m2 k..n-1
73#define GTEST_$(k)_TUPLE_(T) tuple<$for m, [[T##$m]]$for m2 [[, void]]>
74
75]]
76
77// GTEST_n_TYPENAMES_(T) declares a list of n typenames.
78
79$for j [[
80$range m 0..j-1
81#define GTEST_$(j)_TYPENAMES_(T) $for m, [[typename T##$m]]
82
83
84]]
85
86// In theory, defining stuff in the ::std namespace is undefined
87// behavior.  We can do this as we are playing the role of a standard
88// library vendor.
89namespace std {
90namespace tr1 {
91
92template <$for i, [[typename T$i = void]]>
93class tuple;
94
95// Anything in namespace gtest_internal is Google Test's INTERNAL
96// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code.
97namespace gtest_internal {
98
99// ByRef<T>::type is T if T is a reference; otherwise it's const T&.
100template <typename T>
101struct ByRef { typedef const T& type; };  // NOLINT
102template <typename T>
103struct ByRef<T&> { typedef T& type; };  // NOLINT
104
105// A handy wrapper for ByRef.
106#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef<T>::type
107
108// AddRef<T>::type is T if T is a reference; otherwise it's T&.  This
109// is the same as tr1::add_reference<T>::type.
110template <typename T>
111struct AddRef { typedef T& type; };  // NOLINT
112template <typename T>
113struct AddRef<T&> { typedef T& type; };  // NOLINT
114
115// A handy wrapper for AddRef.
116#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef<T>::type
117
118// A helper for implementing get<k>().
119template <int k> class Get;
120
121// A helper for implementing tuple_element<k, T>.  kIndexValid is true
122// iff k < the number of fields in tuple type T.
123template <bool kIndexValid, int kIndex, class Tuple>
124struct TupleElement;
125
126
127$for i [[
128template <GTEST_$(n)_TYPENAMES_(T)>
129struct TupleElement<true, $i, GTEST_$(n)_TUPLE_(T) > {
130  typedef T$i type;
131};
132
133
134]]
135}  // namespace gtest_internal
136
137template <>
138class tuple<> {
139 public:
140  tuple() {}
141  tuple(const tuple& /* t */)  {}
142  tuple& operator=(const tuple& /* t */) { return *this; }
143};
144
145
146$for k [[
147$range m 0..k-1
148template <GTEST_$(k)_TYPENAMES_(T)>
149class $if k < n [[GTEST_$(k)_TUPLE_(T)]] $else [[tuple]] {
150 public:
151  template <int k> friend class gtest_internal::Get;
152
153  tuple() : $for m, [[f$(m)_()]] {}
154
155  explicit tuple($for m, [[GTEST_BY_REF_(T$m) f$m]]) : [[]]
156$for m, [[f$(m)_(f$m)]] {}
157
158  tuple(const tuple& t) : $for m, [[f$(m)_(t.f$(m)_)]] {}
159
160  template <GTEST_$(k)_TYPENAMES_(U)>
161  tuple(const GTEST_$(k)_TUPLE_(U)& t) : $for m, [[f$(m)_(t.f$(m)_)]] {}
162
163$if k == 2 [[
164  template <typename U0, typename U1>
165  tuple(const ::std::pair<U0, U1>& p) : f0_(p.first), f1_(p.second) {}
166
167]]
168
169  tuple& operator=(const tuple& t) { return CopyFrom(t); }
170
171  template <GTEST_$(k)_TYPENAMES_(U)>
172  tuple& operator=(const GTEST_$(k)_TUPLE_(U)& t) {
173    return CopyFrom(t);
174  }
175
176$if k == 2 [[
177  template <typename U0, typename U1>
178  tuple& operator=(const ::std::pair<U0, U1>& p) {
179    f0_ = p.first;
180    f1_ = p.second;
181    return *this;
182  }
183
184]]
185
186  GTEST_DECLARE_TUPLE_AS_FRIEND_
187
188  template <GTEST_$(k)_TYPENAMES_(U)>
189  tuple& CopyFrom(const GTEST_$(k)_TUPLE_(U)& t) {
190
191$for m [[
192    f$(m)_ = t.f$(m)_;
193
194]]
195    return *this;
196  }
197
198
199$for m [[
200  T$m f$(m)_;
201
202]]
203};
204
205
206]]
207// 6.1.3.2 Tuple creation functions.
208
209// Known limitations: we don't support passing an
210// std::tr1::reference_wrapper<T> to make_tuple().  And we don't
211// implement tie().
212
213inline tuple<> make_tuple() { return tuple<>(); }
214
215$for k [[
216$range m 0..k-1
217
218template <GTEST_$(k)_TYPENAMES_(T)>
219inline GTEST_$(k)_TUPLE_(T) make_tuple($for m, [[const T$m& f$m]]) {
220  return GTEST_$(k)_TUPLE_(T)($for m, [[f$m]]);
221}
222
223]]
224
225// 6.1.3.3 Tuple helper classes.
226
227template <typename Tuple> struct tuple_size;
228
229
230$for j [[
231template <GTEST_$(j)_TYPENAMES_(T)>
232struct tuple_size<GTEST_$(j)_TUPLE_(T) > {
233  static const int value = $j;
234};
235
236
237]]
238template <int k, class Tuple>
239struct tuple_element {
240  typedef typename gtest_internal::TupleElement<
241      k < (tuple_size<Tuple>::value), k, Tuple>::type type;
242};
243
244#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element<k, Tuple >::type
245
246// 6.1.3.4 Element access.
247
248namespace gtest_internal {
249
250
251$for i [[
252template <>
253class Get<$i> {
254 public:
255  template <class Tuple>
256  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple))
257  Field(Tuple& t) { return t.f$(i)_; }  // NOLINT
258
259  template <class Tuple>
260  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple))
261  ConstField(const Tuple& t) { return t.f$(i)_; }
262};
263
264
265]]
266}  // namespace gtest_internal
267
268template <int k, GTEST_$(n)_TYPENAMES_(T)>
269GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T)))
270get(GTEST_$(n)_TUPLE_(T)& t) {
271  return gtest_internal::Get<k>::Field(t);
272}
273
274template <int k, GTEST_$(n)_TYPENAMES_(T)>
275GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k,  GTEST_$(n)_TUPLE_(T)))
276get(const GTEST_$(n)_TUPLE_(T)& t) {
277  return gtest_internal::Get<k>::ConstField(t);
278}
279
280// 6.1.3.5 Relational operators
281
282// We only implement == and !=, as we don't have a need for the rest yet.
283
284namespace gtest_internal {
285
286// SameSizeTuplePrefixComparator<k, k>::Eq(t1, t2) returns true if the
287// first k fields of t1 equals the first k fields of t2.
288// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if
289// k1 != k2.
290template <int kSize1, int kSize2>
291struct SameSizeTuplePrefixComparator;
292
293template <>
294struct SameSizeTuplePrefixComparator<0, 0> {
295  template <class Tuple1, class Tuple2>
296  static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) {
297    return true;
298  }
299};
300
301template <int k>
302struct SameSizeTuplePrefixComparator<k, k> {
303  template <class Tuple1, class Tuple2>
304  static bool Eq(const Tuple1& t1, const Tuple2& t2) {
305    return SameSizeTuplePrefixComparator<k - 1, k - 1>::Eq(t1, t2) &&
306        ::std::tr1::get<k - 1>(t1) == ::std::tr1::get<k - 1>(t2);
307  }
308};
309
310}  // namespace gtest_internal
311
312template <GTEST_$(n)_TYPENAMES_(T), GTEST_$(n)_TYPENAMES_(U)>
313inline bool operator==(const GTEST_$(n)_TUPLE_(T)& t,
314                       const GTEST_$(n)_TUPLE_(U)& u) {
315  return gtest_internal::SameSizeTuplePrefixComparator<
316      tuple_size<GTEST_$(n)_TUPLE_(T) >::value,
317      tuple_size<GTEST_$(n)_TUPLE_(U) >::value>::Eq(t, u);
318}
319
320template <GTEST_$(n)_TYPENAMES_(T), GTEST_$(n)_TYPENAMES_(U)>
321inline bool operator!=(const GTEST_$(n)_TUPLE_(T)& t,
322                       const GTEST_$(n)_TUPLE_(U)& u) { return !(t == u); }
323
324// 6.1.4 Pairs.
325// Unimplemented.
326
327}  // namespace tr1
328}  // namespace std
329
330
331$for j [[
332#undef GTEST_$(j)_TUPLE_
333
334]]
335
336
337$for j [[
338#undef GTEST_$(j)_TYPENAMES_
339
340]]
341
342#undef GTEST_DECLARE_TUPLE_AS_FRIEND_
343#undef GTEST_BY_REF_
344#undef GTEST_ADD_REF_
345#undef GTEST_TUPLE_ELEMENT_
346
347#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-type-util.h
r0r249096
1// This file was GENERATED by command:
2//     pump.py gtest-type-util.h.pump
3// DO NOT EDIT BY HAND!!!
4
5// Copyright 2008 Google Inc.
6// All Rights Reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions are
10// met:
11//
12//     * Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//     * Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following disclaimer
16// in the documentation and/or other materials provided with the
17// distribution.
18//     * Neither the name of Google Inc. nor the names of its
19// contributors may be used to endorse or promote products derived from
20// this software without specific prior written permission.
21//
22// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33//
34// Author: wan@google.com (Zhanyong Wan)
35
36// Type utilities needed for implementing typed and type-parameterized
37// tests.  This file is generated by a SCRIPT.  DO NOT EDIT BY HAND!
38//
39// Currently we support at most 50 types in a list, and at most 50
40// type-parameterized tests in one type-parameterized test case.
41// Please contact googletestframework@googlegroups.com if you need
42// more.
43
44#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
45#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
46
47#include "gtest/internal/gtest-port.h"
48
49// #ifdef __GNUC__ is too general here.  It is possible to use gcc without using
50// libstdc++ (which is where cxxabi.h comes from).
51# if GTEST_HAS_CXXABI_H_
52#  include <cxxabi.h>
53# elif defined(__HP_aCC)
54#  include <acxx_demangle.h>
55# endif  // GTEST_HASH_CXXABI_H_
56
57namespace testing {
58namespace internal {
59
60// GetTypeName<T>() returns a human-readable name of type T.
61// NB: This function is also used in Google Mock, so don't move it inside of
62// the typed-test-only section below.
63template <typename T>
64std::string GetTypeName() {
65# if GTEST_HAS_RTTI
66
67  const char* const name = typeid(T).name();
68#  if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
69  int status = 0;
70  // gcc's implementation of typeid(T).name() mangles the type name,
71  // so we have to demangle it.
72#   if GTEST_HAS_CXXABI_H_
73  using abi::__cxa_demangle;
74#   endif  // GTEST_HAS_CXXABI_H_
75  char* const readable_name = __cxa_demangle(name, 0, 0, &status);
76  const std::string name_str(status == 0 ? readable_name : name);
77  free(readable_name);
78  return name_str;
79#  else
80  return name;
81#  endif  // GTEST_HAS_CXXABI_H_ || __HP_aCC
82
83# else
84
85  return "<type>";
86
87# endif  // GTEST_HAS_RTTI
88}
89
90#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
91
92// AssertyTypeEq<T1, T2>::type is defined iff T1 and T2 are the same
93// type.  This can be used as a compile-time assertion to ensure that
94// two types are equal.
95
96template <typename T1, typename T2>
97struct AssertTypeEq;
98
99template <typename T>
100struct AssertTypeEq<T, T> {
101  typedef bool type;
102};
103
104// A unique type used as the default value for the arguments of class
105// template Types.  This allows us to simulate variadic templates
106// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't
107// support directly.
108struct None {};
109
110// The following family of struct and struct templates are used to
111// represent type lists.  In particular, TypesN<T1, T2, ..., TN>
112// represents a type list with N types (T1, T2, ..., and TN) in it.
113// Except for Types0, every struct in the family has two member types:
114// Head for the first type in the list, and Tail for the rest of the
115// list.
116
117// The empty type list.
118struct Types0 {};
119
120// Type lists of length 1, 2, 3, and so on.
121
122template <typename T1>
123struct Types1 {
124  typedef T1 Head;
125  typedef Types0 Tail;
126};
127template <typename T1, typename T2>
128struct Types2 {
129  typedef T1 Head;
130  typedef Types1<T2> Tail;
131};
132
133template <typename T1, typename T2, typename T3>
134struct Types3 {
135  typedef T1 Head;
136  typedef Types2<T2, T3> Tail;
137};
138
139template <typename T1, typename T2, typename T3, typename T4>
140struct Types4 {
141  typedef T1 Head;
142  typedef Types3<T2, T3, T4> Tail;
143};
144
145template <typename T1, typename T2, typename T3, typename T4, typename T5>
146struct Types5 {
147  typedef T1 Head;
148  typedef Types4<T2, T3, T4, T5> Tail;
149};
150
151template <typename T1, typename T2, typename T3, typename T4, typename T5,
152    typename T6>
153struct Types6 {
154  typedef T1 Head;
155  typedef Types5<T2, T3, T4, T5, T6> Tail;
156};
157
158template <typename T1, typename T2, typename T3, typename T4, typename T5,
159    typename T6, typename T7>
160struct Types7 {
161  typedef T1 Head;
162  typedef Types6<T2, T3, T4, T5, T6, T7> Tail;
163};
164
165template <typename T1, typename T2, typename T3, typename T4, typename T5,
166    typename T6, typename T7, typename T8>
167struct Types8 {
168  typedef T1 Head;
169  typedef Types7<T2, T3, T4, T5, T6, T7, T8> Tail;
170};
171
172template <typename T1, typename T2, typename T3, typename T4, typename T5,
173    typename T6, typename T7, typename T8, typename T9>
174struct Types9 {
175  typedef T1 Head;
176  typedef Types8<T2, T3, T4, T5, T6, T7, T8, T9> Tail;
177};
178
179template <typename T1, typename T2, typename T3, typename T4, typename T5,
180    typename T6, typename T7, typename T8, typename T9, typename T10>
181struct Types10 {
182  typedef T1 Head;
183  typedef Types9<T2, T3, T4, T5, T6, T7, T8, T9, T10> Tail;
184};
185
186template <typename T1, typename T2, typename T3, typename T4, typename T5,
187    typename T6, typename T7, typename T8, typename T9, typename T10,
188    typename T11>
189struct Types11 {
190  typedef T1 Head;
191  typedef Types10<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tail;
192};
193
194template <typename T1, typename T2, typename T3, typename T4, typename T5,
195    typename T6, typename T7, typename T8, typename T9, typename T10,
196    typename T11, typename T12>
197struct Types12 {
198  typedef T1 Head;
199  typedef Types11<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Tail;
200};
201
202template <typename T1, typename T2, typename T3, typename T4, typename T5,
203    typename T6, typename T7, typename T8, typename T9, typename T10,
204    typename T11, typename T12, typename T13>
205struct Types13 {
206  typedef T1 Head;
207  typedef Types12<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Tail;
208};
209
210template <typename T1, typename T2, typename T3, typename T4, typename T5,
211    typename T6, typename T7, typename T8, typename T9, typename T10,
212    typename T11, typename T12, typename T13, typename T14>
213struct Types14 {
214  typedef T1 Head;
215  typedef Types13<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Tail;
216};
217
218template <typename T1, typename T2, typename T3, typename T4, typename T5,
219    typename T6, typename T7, typename T8, typename T9, typename T10,
220    typename T11, typename T12, typename T13, typename T14, typename T15>
221struct Types15 {
222  typedef T1 Head;
223  typedef Types14<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
224      T15> Tail;
225};
226
227template <typename T1, typename T2, typename T3, typename T4, typename T5,
228    typename T6, typename T7, typename T8, typename T9, typename T10,
229    typename T11, typename T12, typename T13, typename T14, typename T15,
230    typename T16>
231struct Types16 {
232  typedef T1 Head;
233  typedef Types15<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
234      T16> Tail;
235};
236
237template <typename T1, typename T2, typename T3, typename T4, typename T5,
238    typename T6, typename T7, typename T8, typename T9, typename T10,
239    typename T11, typename T12, typename T13, typename T14, typename T15,
240    typename T16, typename T17>
241struct Types17 {
242  typedef T1 Head;
243  typedef Types16<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
244      T16, T17> Tail;
245};
246
247template <typename T1, typename T2, typename T3, typename T4, typename T5,
248    typename T6, typename T7, typename T8, typename T9, typename T10,
249    typename T11, typename T12, typename T13, typename T14, typename T15,
250    typename T16, typename T17, typename T18>
251struct Types18 {
252  typedef T1 Head;
253  typedef Types17<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
254      T16, T17, T18> Tail;
255};
256
257template <typename T1, typename T2, typename T3, typename T4, typename T5,
258    typename T6, typename T7, typename T8, typename T9, typename T10,
259    typename T11, typename T12, typename T13, typename T14, typename T15,
260    typename T16, typename T17, typename T18, typename T19>
261struct Types19 {
262  typedef T1 Head;
263  typedef Types18<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
264      T16, T17, T18, T19> Tail;
265};
266
267template <typename T1, typename T2, typename T3, typename T4, typename T5,
268    typename T6, typename T7, typename T8, typename T9, typename T10,
269    typename T11, typename T12, typename T13, typename T14, typename T15,
270    typename T16, typename T17, typename T18, typename T19, typename T20>
271struct Types20 {
272  typedef T1 Head;
273  typedef Types19<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
274      T16, T17, T18, T19, T20> Tail;
275};
276
277template <typename T1, typename T2, typename T3, typename T4, typename T5,
278    typename T6, typename T7, typename T8, typename T9, typename T10,
279    typename T11, typename T12, typename T13, typename T14, typename T15,
280    typename T16, typename T17, typename T18, typename T19, typename T20,
281    typename T21>
282struct Types21 {
283  typedef T1 Head;
284  typedef Types20<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
285      T16, T17, T18, T19, T20, T21> Tail;
286};
287
288template <typename T1, typename T2, typename T3, typename T4, typename T5,
289    typename T6, typename T7, typename T8, typename T9, typename T10,
290    typename T11, typename T12, typename T13, typename T14, typename T15,
291    typename T16, typename T17, typename T18, typename T19, typename T20,
292    typename T21, typename T22>
293struct Types22 {
294  typedef T1 Head;
295  typedef Types21<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
296      T16, T17, T18, T19, T20, T21, T22> Tail;
297};
298
299template <typename T1, typename T2, typename T3, typename T4, typename T5,
300    typename T6, typename T7, typename T8, typename T9, typename T10,
301    typename T11, typename T12, typename T13, typename T14, typename T15,
302    typename T16, typename T17, typename T18, typename T19, typename T20,
303    typename T21, typename T22, typename T23>
304struct Types23 {
305  typedef T1 Head;
306  typedef Types22<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
307      T16, T17, T18, T19, T20, T21, T22, T23> Tail;
308};
309
310template <typename T1, typename T2, typename T3, typename T4, typename T5,
311    typename T6, typename T7, typename T8, typename T9, typename T10,
312    typename T11, typename T12, typename T13, typename T14, typename T15,
313    typename T16, typename T17, typename T18, typename T19, typename T20,
314    typename T21, typename T22, typename T23, typename T24>
315struct Types24 {
316  typedef T1 Head;
317  typedef Types23<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
318      T16, T17, T18, T19, T20, T21, T22, T23, T24> Tail;
319};
320
321template <typename T1, typename T2, typename T3, typename T4, typename T5,
322    typename T6, typename T7, typename T8, typename T9, typename T10,
323    typename T11, typename T12, typename T13, typename T14, typename T15,
324    typename T16, typename T17, typename T18, typename T19, typename T20,
325    typename T21, typename T22, typename T23, typename T24, typename T25>
326struct Types25 {
327  typedef T1 Head;
328  typedef Types24<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
329      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Tail;
330};
331
332template <typename T1, typename T2, typename T3, typename T4, typename T5,
333    typename T6, typename T7, typename T8, typename T9, typename T10,
334    typename T11, typename T12, typename T13, typename T14, typename T15,
335    typename T16, typename T17, typename T18, typename T19, typename T20,
336    typename T21, typename T22, typename T23, typename T24, typename T25,
337    typename T26>
338struct Types26 {
339  typedef T1 Head;
340  typedef Types25<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
341      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> Tail;
342};
343
344template <typename T1, typename T2, typename T3, typename T4, typename T5,
345    typename T6, typename T7, typename T8, typename T9, typename T10,
346    typename T11, typename T12, typename T13, typename T14, typename T15,
347    typename T16, typename T17, typename T18, typename T19, typename T20,
348    typename T21, typename T22, typename T23, typename T24, typename T25,
349    typename T26, typename T27>
350struct Types27 {
351  typedef T1 Head;
352  typedef Types26<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
353      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> Tail;
354};
355
356template <typename T1, typename T2, typename T3, typename T4, typename T5,
357    typename T6, typename T7, typename T8, typename T9, typename T10,
358    typename T11, typename T12, typename T13, typename T14, typename T15,
359    typename T16, typename T17, typename T18, typename T19, typename T20,
360    typename T21, typename T22, typename T23, typename T24, typename T25,
361    typename T26, typename T27, typename T28>
362struct Types28 {
363  typedef T1 Head;
364  typedef Types27<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
365      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> Tail;
366};
367
368template <typename T1, typename T2, typename T3, typename T4, typename T5,
369    typename T6, typename T7, typename T8, typename T9, typename T10,
370    typename T11, typename T12, typename T13, typename T14, typename T15,
371    typename T16, typename T17, typename T18, typename T19, typename T20,
372    typename T21, typename T22, typename T23, typename T24, typename T25,
373    typename T26, typename T27, typename T28, typename T29>
374struct Types29 {
375  typedef T1 Head;
376  typedef Types28<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
377      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
378      T29> Tail;
379};
380
381template <typename T1, typename T2, typename T3, typename T4, typename T5,
382    typename T6, typename T7, typename T8, typename T9, typename T10,
383    typename T11, typename T12, typename T13, typename T14, typename T15,
384    typename T16, typename T17, typename T18, typename T19, typename T20,
385    typename T21, typename T22, typename T23, typename T24, typename T25,
386    typename T26, typename T27, typename T28, typename T29, typename T30>
387struct Types30 {
388  typedef T1 Head;
389  typedef Types29<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
390      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
391      T30> Tail;
392};
393
394template <typename T1, typename T2, typename T3, typename T4, typename T5,
395    typename T6, typename T7, typename T8, typename T9, typename T10,
396    typename T11, typename T12, typename T13, typename T14, typename T15,
397    typename T16, typename T17, typename T18, typename T19, typename T20,
398    typename T21, typename T22, typename T23, typename T24, typename T25,
399    typename T26, typename T27, typename T28, typename T29, typename T30,
400    typename T31>
401struct Types31 {
402  typedef T1 Head;
403  typedef Types30<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
404      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
405      T30, T31> Tail;
406};
407
408template <typename T1, typename T2, typename T3, typename T4, typename T5,
409    typename T6, typename T7, typename T8, typename T9, typename T10,
410    typename T11, typename T12, typename T13, typename T14, typename T15,
411    typename T16, typename T17, typename T18, typename T19, typename T20,
412    typename T21, typename T22, typename T23, typename T24, typename T25,
413    typename T26, typename T27, typename T28, typename T29, typename T30,
414    typename T31, typename T32>
415struct Types32 {
416  typedef T1 Head;
417  typedef Types31<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
418      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
419      T30, T31, T32> Tail;
420};
421
422template <typename T1, typename T2, typename T3, typename T4, typename T5,
423    typename T6, typename T7, typename T8, typename T9, typename T10,
424    typename T11, typename T12, typename T13, typename T14, typename T15,
425    typename T16, typename T17, typename T18, typename T19, typename T20,
426    typename T21, typename T22, typename T23, typename T24, typename T25,
427    typename T26, typename T27, typename T28, typename T29, typename T30,
428    typename T31, typename T32, typename T33>
429struct Types33 {
430  typedef T1 Head;
431  typedef Types32<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
432      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
433      T30, T31, T32, T33> Tail;
434};
435
436template <typename T1, typename T2, typename T3, typename T4, typename T5,
437    typename T6, typename T7, typename T8, typename T9, typename T10,
438    typename T11, typename T12, typename T13, typename T14, typename T15,
439    typename T16, typename T17, typename T18, typename T19, typename T20,
440    typename T21, typename T22, typename T23, typename T24, typename T25,
441    typename T26, typename T27, typename T28, typename T29, typename T30,
442    typename T31, typename T32, typename T33, typename T34>
443struct Types34 {
444  typedef T1 Head;
445  typedef Types33<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
446      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
447      T30, T31, T32, T33, T34> Tail;
448};
449
450template <typename T1, typename T2, typename T3, typename T4, typename T5,
451    typename T6, typename T7, typename T8, typename T9, typename T10,
452    typename T11, typename T12, typename T13, typename T14, typename T15,
453    typename T16, typename T17, typename T18, typename T19, typename T20,
454    typename T21, typename T22, typename T23, typename T24, typename T25,
455    typename T26, typename T27, typename T28, typename T29, typename T30,
456    typename T31, typename T32, typename T33, typename T34, typename T35>
457struct Types35 {
458  typedef T1 Head;
459  typedef Types34<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
460      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
461      T30, T31, T32, T33, T34, T35> Tail;
462};
463
464template <typename T1, typename T2, typename T3, typename T4, typename T5,
465    typename T6, typename T7, typename T8, typename T9, typename T10,
466    typename T11, typename T12, typename T13, typename T14, typename T15,
467    typename T16, typename T17, typename T18, typename T19, typename T20,
468    typename T21, typename T22, typename T23, typename T24, typename T25,
469    typename T26, typename T27, typename T28, typename T29, typename T30,
470    typename T31, typename T32, typename T33, typename T34, typename T35,
471    typename T36>
472struct Types36 {
473  typedef T1 Head;
474  typedef Types35<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
475      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
476      T30, T31, T32, T33, T34, T35, T36> Tail;
477};
478
479template <typename T1, typename T2, typename T3, typename T4, typename T5,
480    typename T6, typename T7, typename T8, typename T9, typename T10,
481    typename T11, typename T12, typename T13, typename T14, typename T15,
482    typename T16, typename T17, typename T18, typename T19, typename T20,
483    typename T21, typename T22, typename T23, typename T24, typename T25,
484    typename T26, typename T27, typename T28, typename T29, typename T30,
485    typename T31, typename T32, typename T33, typename T34, typename T35,
486    typename T36, typename T37>
487struct Types37 {
488  typedef T1 Head;
489  typedef Types36<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
490      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
491      T30, T31, T32, T33, T34, T35, T36, T37> Tail;
492};
493
494template <typename T1, typename T2, typename T3, typename T4, typename T5,
495    typename T6, typename T7, typename T8, typename T9, typename T10,
496    typename T11, typename T12, typename T13, typename T14, typename T15,
497    typename T16, typename T17, typename T18, typename T19, typename T20,
498    typename T21, typename T22, typename T23, typename T24, typename T25,
499    typename T26, typename T27, typename T28, typename T29, typename T30,
500    typename T31, typename T32, typename T33, typename T34, typename T35,
501    typename T36, typename T37, typename T38>
502struct Types38 {
503  typedef T1 Head;
504  typedef Types37<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
505      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
506      T30, T31, T32, T33, T34, T35, T36, T37, T38> Tail;
507};
508
509template <typename T1, typename T2, typename T3, typename T4, typename T5,
510    typename T6, typename T7, typename T8, typename T9, typename T10,
511    typename T11, typename T12, typename T13, typename T14, typename T15,
512    typename T16, typename T17, typename T18, typename T19, typename T20,
513    typename T21, typename T22, typename T23, typename T24, typename T25,
514    typename T26, typename T27, typename T28, typename T29, typename T30,
515    typename T31, typename T32, typename T33, typename T34, typename T35,
516    typename T36, typename T37, typename T38, typename T39>
517struct Types39 {
518  typedef T1 Head;
519  typedef Types38<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
520      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
521      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Tail;
522};
523
524template <typename T1, typename T2, typename T3, typename T4, typename T5,
525    typename T6, typename T7, typename T8, typename T9, typename T10,
526    typename T11, typename T12, typename T13, typename T14, typename T15,
527    typename T16, typename T17, typename T18, typename T19, typename T20,
528    typename T21, typename T22, typename T23, typename T24, typename T25,
529    typename T26, typename T27, typename T28, typename T29, typename T30,
530    typename T31, typename T32, typename T33, typename T34, typename T35,
531    typename T36, typename T37, typename T38, typename T39, typename T40>
532struct Types40 {
533  typedef T1 Head;
534  typedef Types39<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
535      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
536      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Tail;
537};
538
539template <typename T1, typename T2, typename T3, typename T4, typename T5,
540    typename T6, typename T7, typename T8, typename T9, typename T10,
541    typename T11, typename T12, typename T13, typename T14, typename T15,
542    typename T16, typename T17, typename T18, typename T19, typename T20,
543    typename T21, typename T22, typename T23, typename T24, typename T25,
544    typename T26, typename T27, typename T28, typename T29, typename T30,
545    typename T31, typename T32, typename T33, typename T34, typename T35,
546    typename T36, typename T37, typename T38, typename T39, typename T40,
547    typename T41>
548struct Types41 {
549  typedef T1 Head;
550  typedef Types40<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
551      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
552      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> Tail;
553};
554
555template <typename T1, typename T2, typename T3, typename T4, typename T5,
556    typename T6, typename T7, typename T8, typename T9, typename T10,
557    typename T11, typename T12, typename T13, typename T14, typename T15,
558    typename T16, typename T17, typename T18, typename T19, typename T20,
559    typename T21, typename T22, typename T23, typename T24, typename T25,
560    typename T26, typename T27, typename T28, typename T29, typename T30,
561    typename T31, typename T32, typename T33, typename T34, typename T35,
562    typename T36, typename T37, typename T38, typename T39, typename T40,
563    typename T41, typename T42>
564struct Types42 {
565  typedef T1 Head;
566  typedef Types41<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
567      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
568      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42> Tail;
569};
570
571template <typename T1, typename T2, typename T3, typename T4, typename T5,
572    typename T6, typename T7, typename T8, typename T9, typename T10,
573    typename T11, typename T12, typename T13, typename T14, typename T15,
574    typename T16, typename T17, typename T18, typename T19, typename T20,
575    typename T21, typename T22, typename T23, typename T24, typename T25,
576    typename T26, typename T27, typename T28, typename T29, typename T30,
577    typename T31, typename T32, typename T33, typename T34, typename T35,
578    typename T36, typename T37, typename T38, typename T39, typename T40,
579    typename T41, typename T42, typename T43>
580struct Types43 {
581  typedef T1 Head;
582  typedef Types42<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
583      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
584      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
585      T43> Tail;
586};
587
588template <typename T1, typename T2, typename T3, typename T4, typename T5,
589    typename T6, typename T7, typename T8, typename T9, typename T10,
590    typename T11, typename T12, typename T13, typename T14, typename T15,
591    typename T16, typename T17, typename T18, typename T19, typename T20,
592    typename T21, typename T22, typename T23, typename T24, typename T25,
593    typename T26, typename T27, typename T28, typename T29, typename T30,
594    typename T31, typename T32, typename T33, typename T34, typename T35,
595    typename T36, typename T37, typename T38, typename T39, typename T40,
596    typename T41, typename T42, typename T43, typename T44>
597struct Types44 {
598  typedef T1 Head;
599  typedef Types43<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
600      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
601      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
602      T44> Tail;
603};
604
605template <typename T1, typename T2, typename T3, typename T4, typename T5,
606    typename T6, typename T7, typename T8, typename T9, typename T10,
607    typename T11, typename T12, typename T13, typename T14, typename T15,
608    typename T16, typename T17, typename T18, typename T19, typename T20,
609    typename T21, typename T22, typename T23, typename T24, typename T25,
610    typename T26, typename T27, typename T28, typename T29, typename T30,
611    typename T31, typename T32, typename T33, typename T34, typename T35,
612    typename T36, typename T37, typename T38, typename T39, typename T40,
613    typename T41, typename T42, typename T43, typename T44, typename T45>
614struct Types45 {
615  typedef T1 Head;
616  typedef Types44<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
617      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
618      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
619      T44, T45> Tail;
620};
621
622template <typename T1, typename T2, typename T3, typename T4, typename T5,
623    typename T6, typename T7, typename T8, typename T9, typename T10,
624    typename T11, typename T12, typename T13, typename T14, typename T15,
625    typename T16, typename T17, typename T18, typename T19, typename T20,
626    typename T21, typename T22, typename T23, typename T24, typename T25,
627    typename T26, typename T27, typename T28, typename T29, typename T30,
628    typename T31, typename T32, typename T33, typename T34, typename T35,
629    typename T36, typename T37, typename T38, typename T39, typename T40,
630    typename T41, typename T42, typename T43, typename T44, typename T45,
631    typename T46>
632struct Types46 {
633  typedef T1 Head;
634  typedef Types45<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
635      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
636      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
637      T44, T45, T46> Tail;
638};
639
640template <typename T1, typename T2, typename T3, typename T4, typename T5,
641    typename T6, typename T7, typename T8, typename T9, typename T10,
642    typename T11, typename T12, typename T13, typename T14, typename T15,
643    typename T16, typename T17, typename T18, typename T19, typename T20,
644    typename T21, typename T22, typename T23, typename T24, typename T25,
645    typename T26, typename T27, typename T28, typename T29, typename T30,
646    typename T31, typename T32, typename T33, typename T34, typename T35,
647    typename T36, typename T37, typename T38, typename T39, typename T40,
648    typename T41, typename T42, typename T43, typename T44, typename T45,
649    typename T46, typename T47>
650struct Types47 {
651  typedef T1 Head;
652  typedef Types46<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
653      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
654      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
655      T44, T45, T46, T47> Tail;
656};
657
658template <typename T1, typename T2, typename T3, typename T4, typename T5,
659    typename T6, typename T7, typename T8, typename T9, typename T10,
660    typename T11, typename T12, typename T13, typename T14, typename T15,
661    typename T16, typename T17, typename T18, typename T19, typename T20,
662    typename T21, typename T22, typename T23, typename T24, typename T25,
663    typename T26, typename T27, typename T28, typename T29, typename T30,
664    typename T31, typename T32, typename T33, typename T34, typename T35,
665    typename T36, typename T37, typename T38, typename T39, typename T40,
666    typename T41, typename T42, typename T43, typename T44, typename T45,
667    typename T46, typename T47, typename T48>
668struct Types48 {
669  typedef T1 Head;
670  typedef Types47<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
671      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
672      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
673      T44, T45, T46, T47, T48> Tail;
674};
675
676template <typename T1, typename T2, typename T3, typename T4, typename T5,
677    typename T6, typename T7, typename T8, typename T9, typename T10,
678    typename T11, typename T12, typename T13, typename T14, typename T15,
679    typename T16, typename T17, typename T18, typename T19, typename T20,
680    typename T21, typename T22, typename T23, typename T24, typename T25,
681    typename T26, typename T27, typename T28, typename T29, typename T30,
682    typename T31, typename T32, typename T33, typename T34, typename T35,
683    typename T36, typename T37, typename T38, typename T39, typename T40,
684    typename T41, typename T42, typename T43, typename T44, typename T45,
685    typename T46, typename T47, typename T48, typename T49>
686struct Types49 {
687  typedef T1 Head;
688  typedef Types48<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
689      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
690      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
691      T44, T45, T46, T47, T48, T49> Tail;
692};
693
694template <typename T1, typename T2, typename T3, typename T4, typename T5,
695    typename T6, typename T7, typename T8, typename T9, typename T10,
696    typename T11, typename T12, typename T13, typename T14, typename T15,
697    typename T16, typename T17, typename T18, typename T19, typename T20,
698    typename T21, typename T22, typename T23, typename T24, typename T25,
699    typename T26, typename T27, typename T28, typename T29, typename T30,
700    typename T31, typename T32, typename T33, typename T34, typename T35,
701    typename T36, typename T37, typename T38, typename T39, typename T40,
702    typename T41, typename T42, typename T43, typename T44, typename T45,
703    typename T46, typename T47, typename T48, typename T49, typename T50>
704struct Types50 {
705  typedef T1 Head;
706  typedef Types49<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
707      T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
708      T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
709      T44, T45, T46, T47, T48, T49, T50> Tail;
710};
711
712
713}  // namespace internal
714
715// We don't want to require the users to write TypesN<...> directly,
716// as that would require them to count the length.  Types<...> is much
717// easier to write, but generates horrible messages when there is a
718// compiler error, as gcc insists on printing out each template
719// argument, even if it has the default value (this means Types<int>
720// will appear as Types<int, None, None, ..., None> in the compiler
721// errors).
722//
723// Our solution is to combine the best part of the two approaches: a
724// user would write Types<T1, ..., TN>, and Google Test will translate
725// that to TypesN<T1, ..., TN> internally to make error messages
726// readable.  The translation is done by the 'type' member of the
727// Types template.
728template <typename T1 = internal::None, typename T2 = internal::None,
729    typename T3 = internal::None, typename T4 = internal::None,
730    typename T5 = internal::None, typename T6 = internal::None,
731    typename T7 = internal::None, typename T8 = internal::None,
732    typename T9 = internal::None, typename T10 = internal::None,
733    typename T11 = internal::None, typename T12 = internal::None,
734    typename T13 = internal::None, typename T14 = internal::None,
735    typename T15 = internal::None, typename T16 = internal::None,
736    typename T17 = internal::None, typename T18 = internal::None,
737    typename T19 = internal::None, typename T20 = internal::None,
738    typename T21 = internal::None, typename T22 = internal::None,
739    typename T23 = internal::None, typename T24 = internal::None,
740    typename T25 = internal::None, typename T26 = internal::None,
741    typename T27 = internal::None, typename T28 = internal::None,
742    typename T29 = internal::None, typename T30 = internal::None,
743    typename T31 = internal::None, typename T32 = internal::None,
744    typename T33 = internal::None, typename T34 = internal::None,
745    typename T35 = internal::None, typename T36 = internal::None,
746    typename T37 = internal::None, typename T38 = internal::None,
747    typename T39 = internal::None, typename T40 = internal::None,
748    typename T41 = internal::None, typename T42 = internal::None,
749    typename T43 = internal::None, typename T44 = internal::None,
750    typename T45 = internal::None, typename T46 = internal::None,
751    typename T47 = internal::None, typename T48 = internal::None,
752    typename T49 = internal::None, typename T50 = internal::None>
753struct Types {
754  typedef internal::Types50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
755      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
756      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
757      T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> type;
758};
759
760template <>
761struct Types<internal::None, internal::None, internal::None, internal::None,
762    internal::None, internal::None, internal::None, internal::None,
763    internal::None, internal::None, internal::None, internal::None,
764    internal::None, internal::None, internal::None, internal::None,
765    internal::None, internal::None, internal::None, internal::None,
766    internal::None, internal::None, internal::None, internal::None,
767    internal::None, internal::None, internal::None, internal::None,
768    internal::None, internal::None, internal::None, internal::None,
769    internal::None, internal::None, internal::None, internal::None,
770    internal::None, internal::None, internal::None, internal::None,
771    internal::None, internal::None, internal::None, internal::None,
772    internal::None, internal::None, internal::None, internal::None,
773    internal::None, internal::None> {
774  typedef internal::Types0 type;
775};
776template <typename T1>
777struct Types<T1, internal::None, internal::None, internal::None,
778    internal::None, internal::None, internal::None, internal::None,
779    internal::None, internal::None, internal::None, internal::None,
780    internal::None, internal::None, internal::None, internal::None,
781    internal::None, internal::None, internal::None, internal::None,
782    internal::None, internal::None, internal::None, internal::None,
783    internal::None, internal::None, internal::None, internal::None,
784    internal::None, internal::None, internal::None, internal::None,
785    internal::None, internal::None, internal::None, internal::None,
786    internal::None, internal::None, internal::None, internal::None,
787    internal::None, internal::None, internal::None, internal::None,
788    internal::None, internal::None, internal::None, internal::None,
789    internal::None, internal::None> {
790  typedef internal::Types1<T1> type;
791};
792template <typename T1, typename T2>
793struct Types<T1, T2, internal::None, internal::None, internal::None,
794    internal::None, internal::None, internal::None, internal::None,
795    internal::None, internal::None, internal::None, internal::None,
796    internal::None, internal::None, internal::None, internal::None,
797    internal::None, internal::None, internal::None, internal::None,
798    internal::None, internal::None, internal::None, internal::None,
799    internal::None, internal::None, internal::None, internal::None,
800    internal::None, internal::None, internal::None, internal::None,
801    internal::None, internal::None, internal::None, internal::None,
802    internal::None, internal::None, internal::None, internal::None,
803    internal::None, internal::None, internal::None, internal::None,
804    internal::None, internal::None, internal::None, internal::None,
805    internal::None> {
806  typedef internal::Types2<T1, T2> type;
807};
808template <typename T1, typename T2, typename T3>
809struct Types<T1, T2, T3, internal::None, internal::None, internal::None,
810    internal::None, internal::None, internal::None, internal::None,
811    internal::None, internal::None, internal::None, internal::None,
812    internal::None, internal::None, internal::None, internal::None,
813    internal::None, internal::None, internal::None, internal::None,
814    internal::None, internal::None, internal::None, internal::None,
815    internal::None, internal::None, internal::None, internal::None,
816    internal::None, internal::None, internal::None, internal::None,
817    internal::None, internal::None, internal::None, internal::None,
818    internal::None, internal::None, internal::None, internal::None,
819    internal::None, internal::None, internal::None, internal::None,
820    internal::None, internal::None, internal::None, internal::None> {
821  typedef internal::Types3<T1, T2, T3> type;
822};
823template <typename T1, typename T2, typename T3, typename T4>
824struct Types<T1, T2, T3, T4, internal::None, internal::None, internal::None,
825    internal::None, internal::None, internal::None, internal::None,
826    internal::None, internal::None, internal::None, internal::None,
827    internal::None, internal::None, internal::None, internal::None,
828    internal::None, internal::None, internal::None, internal::None,
829    internal::None, internal::None, internal::None, internal::None,
830    internal::None, internal::None, internal::None, internal::None,
831    internal::None, internal::None, internal::None, internal::None,
832    internal::None, internal::None, internal::None, internal::None,
833    internal::None, internal::None, internal::None, internal::None,
834    internal::None, internal::None, internal::None, internal::None,
835    internal::None, internal::None, internal::None> {
836  typedef internal::Types4<T1, T2, T3, T4> type;
837};
838template <typename T1, typename T2, typename T3, typename T4, typename T5>
839struct Types<T1, T2, T3, T4, T5, internal::None, internal::None,
840    internal::None, internal::None, internal::None, internal::None,
841    internal::None, internal::None, internal::None, internal::None,
842    internal::None, internal::None, internal::None, internal::None,
843    internal::None, internal::None, internal::None, internal::None,
844    internal::None, internal::None, internal::None, internal::None,
845    internal::None, internal::None, internal::None, internal::None,
846    internal::None, internal::None, internal::None, internal::None,
847    internal::None, internal::None, internal::None, internal::None,
848    internal::None, internal::None, internal::None, internal::None,
849    internal::None, internal::None, internal::None, internal::None,
850    internal::None, internal::None, internal::None> {
851  typedef internal::Types5<T1, T2, T3, T4, T5> type;
852};
853template <typename T1, typename T2, typename T3, typename T4, typename T5,
854    typename T6>
855struct Types<T1, T2, T3, T4, T5, T6, internal::None, internal::None,
856    internal::None, internal::None, internal::None, internal::None,
857    internal::None, internal::None, internal::None, internal::None,
858    internal::None, internal::None, internal::None, internal::None,
859    internal::None, internal::None, internal::None, internal::None,
860    internal::None, internal::None, internal::None, internal::None,
861    internal::None, internal::None, internal::None, internal::None,
862    internal::None, internal::None, internal::None, internal::None,
863    internal::None, internal::None, internal::None, internal::None,
864    internal::None, internal::None, internal::None, internal::None,
865    internal::None, internal::None, internal::None, internal::None,
866    internal::None, internal::None> {
867  typedef internal::Types6<T1, T2, T3, T4, T5, T6> type;
868};
869template <typename T1, typename T2, typename T3, typename T4, typename T5,
870    typename T6, typename T7>
871struct Types<T1, T2, T3, T4, T5, T6, T7, internal::None, internal::None,
872    internal::None, internal::None, internal::None, internal::None,
873    internal::None, internal::None, internal::None, internal::None,
874    internal::None, internal::None, internal::None, internal::None,
875    internal::None, internal::None, internal::None, internal::None,
876    internal::None, internal::None, internal::None, internal::None,
877    internal::None, internal::None, internal::None, internal::None,
878    internal::None, internal::None, internal::None, internal::None,
879    internal::None, internal::None, internal::None, internal::None,
880    internal::None, internal::None, internal::None, internal::None,
881    internal::None, internal::None, internal::None, internal::None,
882    internal::None> {
883  typedef internal::Types7<T1, T2, T3, T4, T5, T6, T7> type;
884};
885template <typename T1, typename T2, typename T3, typename T4, typename T5,
886    typename T6, typename T7, typename T8>
887struct Types<T1, T2, T3, T4, T5, T6, T7, T8, internal::None, internal::None,
888    internal::None, internal::None, internal::None, internal::None,
889    internal::None, internal::None, internal::None, internal::None,
890    internal::None, internal::None, internal::None, internal::None,
891    internal::None, internal::None, internal::None, internal::None,
892    internal::None, internal::None, internal::None, internal::None,
893    internal::None, internal::None, internal::None, internal::None,
894    internal::None, internal::None, internal::None, internal::None,
895    internal::None, internal::None, internal::None, internal::None,
896    internal::None, internal::None, internal::None, internal::None,
897    internal::None, internal::None, internal::None, internal::None> {
898  typedef internal::Types8<T1, T2, T3, T4, T5, T6, T7, T8> type;
899};
900template <typename T1, typename T2, typename T3, typename T4, typename T5,
901    typename T6, typename T7, typename T8, typename T9>
902struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, internal::None,
903    internal::None, internal::None, internal::None, internal::None,
904    internal::None, internal::None, internal::None, internal::None,
905    internal::None, internal::None, internal::None, internal::None,
906    internal::None, internal::None, internal::None, internal::None,
907    internal::None, internal::None, internal::None, internal::None,
908    internal::None, internal::None, internal::None, internal::None,
909    internal::None, internal::None, internal::None, internal::None,
910    internal::None, internal::None, internal::None, internal::None,
911    internal::None, internal::None, internal::None, internal::None,
912    internal::None, internal::None, internal::None, internal::None> {
913  typedef internal::Types9<T1, T2, T3, T4, T5, T6, T7, T8, T9> type;
914};
915template <typename T1, typename T2, typename T3, typename T4, typename T5,
916    typename T6, typename T7, typename T8, typename T9, typename T10>
917struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, internal::None,
918    internal::None, internal::None, internal::None, internal::None,
919    internal::None, internal::None, internal::None, internal::None,
920    internal::None, internal::None, internal::None, internal::None,
921    internal::None, internal::None, internal::None, internal::None,
922    internal::None, internal::None, internal::None, internal::None,
923    internal::None, internal::None, internal::None, internal::None,
924    internal::None, internal::None, internal::None, internal::None,
925    internal::None, internal::None, internal::None, internal::None,
926    internal::None, internal::None, internal::None, internal::None,
927    internal::None, internal::None, internal::None> {
928  typedef internal::Types10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> type;
929};
930template <typename T1, typename T2, typename T3, typename T4, typename T5,
931    typename T6, typename T7, typename T8, typename T9, typename T10,
932    typename T11>
933struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, internal::None,
934    internal::None, internal::None, internal::None, internal::None,
935    internal::None, internal::None, internal::None, internal::None,
936    internal::None, internal::None, internal::None, internal::None,
937    internal::None, internal::None, internal::None, internal::None,
938    internal::None, internal::None, internal::None, internal::None,
939    internal::None, internal::None, internal::None, internal::None,
940    internal::None, internal::None, internal::None, internal::None,
941    internal::None, internal::None, internal::None, internal::None,
942    internal::None, internal::None, internal::None, internal::None,
943    internal::None, internal::None> {
944  typedef internal::Types11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> type;
945};
946template <typename T1, typename T2, typename T3, typename T4, typename T5,
947    typename T6, typename T7, typename T8, typename T9, typename T10,
948    typename T11, typename T12>
949struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, internal::None,
950    internal::None, internal::None, internal::None, internal::None,
951    internal::None, internal::None, internal::None, internal::None,
952    internal::None, internal::None, internal::None, internal::None,
953    internal::None, internal::None, internal::None, internal::None,
954    internal::None, internal::None, internal::None, internal::None,
955    internal::None, internal::None, internal::None, internal::None,
956    internal::None, internal::None, internal::None, internal::None,
957    internal::None, internal::None, internal::None, internal::None,
958    internal::None, internal::None, internal::None, internal::None,
959    internal::None> {
960  typedef internal::Types12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
961      T12> type;
962};
963template <typename T1, typename T2, typename T3, typename T4, typename T5,
964    typename T6, typename T7, typename T8, typename T9, typename T10,
965    typename T11, typename T12, typename T13>
966struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
967    internal::None, internal::None, internal::None, internal::None,
968    internal::None, internal::None, internal::None, internal::None,
969    internal::None, internal::None, internal::None, internal::None,
970    internal::None, internal::None, internal::None, internal::None,
971    internal::None, internal::None, internal::None, internal::None,
972    internal::None, internal::None, internal::None, internal::None,
973    internal::None, internal::None, internal::None, internal::None,
974    internal::None, internal::None, internal::None, internal::None,
975    internal::None, internal::None, internal::None, internal::None,
976    internal::None> {
977  typedef internal::Types13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
978      T13> type;
979};
980template <typename T1, typename T2, typename T3, typename T4, typename T5,
981    typename T6, typename T7, typename T8, typename T9, typename T10,
982    typename T11, typename T12, typename T13, typename T14>
983struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
984    internal::None, internal::None, internal::None, internal::None,
985    internal::None, internal::None, internal::None, internal::None,
986    internal::None, internal::None, internal::None, internal::None,
987    internal::None, internal::None, internal::None, internal::None,
988    internal::None, internal::None, internal::None, internal::None,
989    internal::None, internal::None, internal::None, internal::None,
990    internal::None, internal::None, internal::None, internal::None,
991    internal::None, internal::None, internal::None, internal::None,
992    internal::None, internal::None, internal::None, internal::None> {
993  typedef internal::Types14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
994      T13, T14> type;
995};
996template <typename T1, typename T2, typename T3, typename T4, typename T5,
997    typename T6, typename T7, typename T8, typename T9, typename T10,
998    typename T11, typename T12, typename T13, typename T14, typename T15>
999struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1000    internal::None, internal::None, internal::None, internal::None,
1001    internal::None, internal::None, internal::None, internal::None,
1002    internal::None, internal::None, internal::None, internal::None,
1003    internal::None, internal::None, internal::None, internal::None,
1004    internal::None, internal::None, internal::None, internal::None,
1005    internal::None, internal::None, internal::None, internal::None,
1006    internal::None, internal::None, internal::None, internal::None,
1007    internal::None, internal::None, internal::None, internal::None,
1008    internal::None, internal::None, internal::None> {
1009  typedef internal::Types15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1010      T13, T14, T15> type;
1011};
1012template <typename T1, typename T2, typename T3, typename T4, typename T5,
1013    typename T6, typename T7, typename T8, typename T9, typename T10,
1014    typename T11, typename T12, typename T13, typename T14, typename T15,
1015    typename T16>
1016struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1017    T16, internal::None, internal::None, internal::None, internal::None,
1018    internal::None, internal::None, internal::None, internal::None,
1019    internal::None, internal::None, internal::None, internal::None,
1020    internal::None, internal::None, internal::None, internal::None,
1021    internal::None, internal::None, internal::None, internal::None,
1022    internal::None, internal::None, internal::None, internal::None,
1023    internal::None, internal::None, internal::None, internal::None,
1024    internal::None, internal::None, internal::None, internal::None,
1025    internal::None, internal::None> {
1026  typedef internal::Types16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1027      T13, T14, T15, T16> type;
1028};
1029template <typename T1, typename T2, typename T3, typename T4, typename T5,
1030    typename T6, typename T7, typename T8, typename T9, typename T10,
1031    typename T11, typename T12, typename T13, typename T14, typename T15,
1032    typename T16, typename T17>
1033struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1034    T16, T17, internal::None, internal::None, internal::None, internal::None,
1035    internal::None, internal::None, internal::None, internal::None,
1036    internal::None, internal::None, internal::None, internal::None,
1037    internal::None, internal::None, internal::None, internal::None,
1038    internal::None, internal::None, internal::None, internal::None,
1039    internal::None, internal::None, internal::None, internal::None,
1040    internal::None, internal::None, internal::None, internal::None,
1041    internal::None, internal::None, internal::None, internal::None,
1042    internal::None> {
1043  typedef internal::Types17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1044      T13, T14, T15, T16, T17> type;
1045};
1046template <typename T1, typename T2, typename T3, typename T4, typename T5,
1047    typename T6, typename T7, typename T8, typename T9, typename T10,
1048    typename T11, typename T12, typename T13, typename T14, typename T15,
1049    typename T16, typename T17, typename T18>
1050struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1051    T16, T17, T18, internal::None, internal::None, internal::None,
1052    internal::None, internal::None, internal::None, internal::None,
1053    internal::None, internal::None, internal::None, internal::None,
1054    internal::None, internal::None, internal::None, internal::None,
1055    internal::None, internal::None, internal::None, internal::None,
1056    internal::None, internal::None, internal::None, internal::None,
1057    internal::None, internal::None, internal::None, internal::None,
1058    internal::None, internal::None, internal::None, internal::None,
1059    internal::None> {
1060  typedef internal::Types18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1061      T13, T14, T15, T16, T17, T18> type;
1062};
1063template <typename T1, typename T2, typename T3, typename T4, typename T5,
1064    typename T6, typename T7, typename T8, typename T9, typename T10,
1065    typename T11, typename T12, typename T13, typename T14, typename T15,
1066    typename T16, typename T17, typename T18, typename T19>
1067struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1068    T16, T17, T18, T19, internal::None, internal::None, internal::None,
1069    internal::None, internal::None, internal::None, internal::None,
1070    internal::None, internal::None, internal::None, internal::None,
1071    internal::None, internal::None, internal::None, internal::None,
1072    internal::None, internal::None, internal::None, internal::None,
1073    internal::None, internal::None, internal::None, internal::None,
1074    internal::None, internal::None, internal::None, internal::None,
1075    internal::None, internal::None, internal::None, internal::None> {
1076  typedef internal::Types19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1077      T13, T14, T15, T16, T17, T18, T19> type;
1078};
1079template <typename T1, typename T2, typename T3, typename T4, typename T5,
1080    typename T6, typename T7, typename T8, typename T9, typename T10,
1081    typename T11, typename T12, typename T13, typename T14, typename T15,
1082    typename T16, typename T17, typename T18, typename T19, typename T20>
1083struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1084    T16, T17, T18, T19, T20, internal::None, internal::None, internal::None,
1085    internal::None, internal::None, internal::None, internal::None,
1086    internal::None, internal::None, internal::None, internal::None,
1087    internal::None, internal::None, internal::None, internal::None,
1088    internal::None, internal::None, internal::None, internal::None,
1089    internal::None, internal::None, internal::None, internal::None,
1090    internal::None, internal::None, internal::None, internal::None,
1091    internal::None, internal::None, internal::None> {
1092  typedef internal::Types20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1093      T13, T14, T15, T16, T17, T18, T19, T20> type;
1094};
1095template <typename T1, typename T2, typename T3, typename T4, typename T5,
1096    typename T6, typename T7, typename T8, typename T9, typename T10,
1097    typename T11, typename T12, typename T13, typename T14, typename T15,
1098    typename T16, typename T17, typename T18, typename T19, typename T20,
1099    typename T21>
1100struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1101    T16, T17, T18, T19, T20, T21, internal::None, internal::None,
1102    internal::None, internal::None, internal::None, internal::None,
1103    internal::None, internal::None, internal::None, internal::None,
1104    internal::None, internal::None, internal::None, internal::None,
1105    internal::None, internal::None, internal::None, internal::None,
1106    internal::None, internal::None, internal::None, internal::None,
1107    internal::None, internal::None, internal::None, internal::None,
1108    internal::None, internal::None, internal::None> {
1109  typedef internal::Types21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1110      T13, T14, T15, T16, T17, T18, T19, T20, T21> type;
1111};
1112template <typename T1, typename T2, typename T3, typename T4, typename T5,
1113    typename T6, typename T7, typename T8, typename T9, typename T10,
1114    typename T11, typename T12, typename T13, typename T14, typename T15,
1115    typename T16, typename T17, typename T18, typename T19, typename T20,
1116    typename T21, typename T22>
1117struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1118    T16, T17, T18, T19, T20, T21, T22, internal::None, internal::None,
1119    internal::None, internal::None, internal::None, internal::None,
1120    internal::None, internal::None, internal::None, internal::None,
1121    internal::None, internal::None, internal::None, internal::None,
1122    internal::None, internal::None, internal::None, internal::None,
1123    internal::None, internal::None, internal::None, internal::None,
1124    internal::None, internal::None, internal::None, internal::None,
1125    internal::None, internal::None> {
1126  typedef internal::Types22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1127      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> type;
1128};
1129template <typename T1, typename T2, typename T3, typename T4, typename T5,
1130    typename T6, typename T7, typename T8, typename T9, typename T10,
1131    typename T11, typename T12, typename T13, typename T14, typename T15,
1132    typename T16, typename T17, typename T18, typename T19, typename T20,
1133    typename T21, typename T22, typename T23>
1134struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1135    T16, T17, T18, T19, T20, T21, T22, T23, internal::None, internal::None,
1136    internal::None, internal::None, internal::None, internal::None,
1137    internal::None, internal::None, internal::None, internal::None,
1138    internal::None, internal::None, internal::None, internal::None,
1139    internal::None, internal::None, internal::None, internal::None,
1140    internal::None, internal::None, internal::None, internal::None,
1141    internal::None, internal::None, internal::None, internal::None,
1142    internal::None> {
1143  typedef internal::Types23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1144      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> type;
1145};
1146template <typename T1, typename T2, typename T3, typename T4, typename T5,
1147    typename T6, typename T7, typename T8, typename T9, typename T10,
1148    typename T11, typename T12, typename T13, typename T14, typename T15,
1149    typename T16, typename T17, typename T18, typename T19, typename T20,
1150    typename T21, typename T22, typename T23, typename T24>
1151struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1152    T16, T17, T18, T19, T20, T21, T22, T23, T24, internal::None,
1153    internal::None, internal::None, internal::None, internal::None,
1154    internal::None, internal::None, internal::None, internal::None,
1155    internal::None, internal::None, internal::None, internal::None,
1156    internal::None, internal::None, internal::None, internal::None,
1157    internal::None, internal::None, internal::None, internal::None,
1158    internal::None, internal::None, internal::None, internal::None,
1159    internal::None> {
1160  typedef internal::Types24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1161      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> type;
1162};
1163template <typename T1, typename T2, typename T3, typename T4, typename T5,
1164    typename T6, typename T7, typename T8, typename T9, typename T10,
1165    typename T11, typename T12, typename T13, typename T14, typename T15,
1166    typename T16, typename T17, typename T18, typename T19, typename T20,
1167    typename T21, typename T22, typename T23, typename T24, typename T25>
1168struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1169    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, internal::None,
1170    internal::None, internal::None, internal::None, internal::None,
1171    internal::None, internal::None, internal::None, internal::None,
1172    internal::None, internal::None, internal::None, internal::None,
1173    internal::None, internal::None, internal::None, internal::None,
1174    internal::None, internal::None, internal::None, internal::None,
1175    internal::None, internal::None, internal::None, internal::None> {
1176  typedef internal::Types25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1177      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> type;
1178};
1179template <typename T1, typename T2, typename T3, typename T4, typename T5,
1180    typename T6, typename T7, typename T8, typename T9, typename T10,
1181    typename T11, typename T12, typename T13, typename T14, typename T15,
1182    typename T16, typename T17, typename T18, typename T19, typename T20,
1183    typename T21, typename T22, typename T23, typename T24, typename T25,
1184    typename T26>
1185struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1186    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, internal::None,
1187    internal::None, internal::None, internal::None, internal::None,
1188    internal::None, internal::None, internal::None, internal::None,
1189    internal::None, internal::None, internal::None, internal::None,
1190    internal::None, internal::None, internal::None, internal::None,
1191    internal::None, internal::None, internal::None, internal::None,
1192    internal::None, internal::None, internal::None> {
1193  typedef internal::Types26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1194      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
1195      T26> type;
1196};
1197template <typename T1, typename T2, typename T3, typename T4, typename T5,
1198    typename T6, typename T7, typename T8, typename T9, typename T10,
1199    typename T11, typename T12, typename T13, typename T14, typename T15,
1200    typename T16, typename T17, typename T18, typename T19, typename T20,
1201    typename T21, typename T22, typename T23, typename T24, typename T25,
1202    typename T26, typename T27>
1203struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1204    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, internal::None,
1205    internal::None, internal::None, internal::None, internal::None,
1206    internal::None, internal::None, internal::None, internal::None,
1207    internal::None, internal::None, internal::None, internal::None,
1208    internal::None, internal::None, internal::None, internal::None,
1209    internal::None, internal::None, internal::None, internal::None,
1210    internal::None, internal::None> {
1211  typedef internal::Types27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1212      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1213      T27> type;
1214};
1215template <typename T1, typename T2, typename T3, typename T4, typename T5,
1216    typename T6, typename T7, typename T8, typename T9, typename T10,
1217    typename T11, typename T12, typename T13, typename T14, typename T15,
1218    typename T16, typename T17, typename T18, typename T19, typename T20,
1219    typename T21, typename T22, typename T23, typename T24, typename T25,
1220    typename T26, typename T27, typename T28>
1221struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1222    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1223    internal::None, internal::None, internal::None, internal::None,
1224    internal::None, internal::None, internal::None, internal::None,
1225    internal::None, internal::None, internal::None, internal::None,
1226    internal::None, internal::None, internal::None, internal::None,
1227    internal::None, internal::None, internal::None, internal::None,
1228    internal::None, internal::None> {
1229  typedef internal::Types28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1230      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1231      T27, T28> type;
1232};
1233template <typename T1, typename T2, typename T3, typename T4, typename T5,
1234    typename T6, typename T7, typename T8, typename T9, typename T10,
1235    typename T11, typename T12, typename T13, typename T14, typename T15,
1236    typename T16, typename T17, typename T18, typename T19, typename T20,
1237    typename T21, typename T22, typename T23, typename T24, typename T25,
1238    typename T26, typename T27, typename T28, typename T29>
1239struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1240    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
1241    internal::None, internal::None, internal::None, internal::None,
1242    internal::None, internal::None, internal::None, internal::None,
1243    internal::None, internal::None, internal::None, internal::None,
1244    internal::None, internal::None, internal::None, internal::None,
1245    internal::None, internal::None, internal::None, internal::None,
1246    internal::None> {
1247  typedef internal::Types29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1248      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1249      T27, T28, T29> type;
1250};
1251template <typename T1, typename T2, typename T3, typename T4, typename T5,
1252    typename T6, typename T7, typename T8, typename T9, typename T10,
1253    typename T11, typename T12, typename T13, typename T14, typename T15,
1254    typename T16, typename T17, typename T18, typename T19, typename T20,
1255    typename T21, typename T22, typename T23, typename T24, typename T25,
1256    typename T26, typename T27, typename T28, typename T29, typename T30>
1257struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1258    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1259    internal::None, internal::None, internal::None, internal::None,
1260    internal::None, internal::None, internal::None, internal::None,
1261    internal::None, internal::None, internal::None, internal::None,
1262    internal::None, internal::None, internal::None, internal::None,
1263    internal::None, internal::None, internal::None, internal::None> {
1264  typedef internal::Types30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1265      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1266      T27, T28, T29, T30> type;
1267};
1268template <typename T1, typename T2, typename T3, typename T4, typename T5,
1269    typename T6, typename T7, typename T8, typename T9, typename T10,
1270    typename T11, typename T12, typename T13, typename T14, typename T15,
1271    typename T16, typename T17, typename T18, typename T19, typename T20,
1272    typename T21, typename T22, typename T23, typename T24, typename T25,
1273    typename T26, typename T27, typename T28, typename T29, typename T30,
1274    typename T31>
1275struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1276    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1277    T31, internal::None, internal::None, internal::None, internal::None,
1278    internal::None, internal::None, internal::None, internal::None,
1279    internal::None, internal::None, internal::None, internal::None,
1280    internal::None, internal::None, internal::None, internal::None,
1281    internal::None, internal::None, internal::None> {
1282  typedef internal::Types31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1283      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1284      T27, T28, T29, T30, T31> type;
1285};
1286template <typename T1, typename T2, typename T3, typename T4, typename T5,
1287    typename T6, typename T7, typename T8, typename T9, typename T10,
1288    typename T11, typename T12, typename T13, typename T14, typename T15,
1289    typename T16, typename T17, typename T18, typename T19, typename T20,
1290    typename T21, typename T22, typename T23, typename T24, typename T25,
1291    typename T26, typename T27, typename T28, typename T29, typename T30,
1292    typename T31, typename T32>
1293struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1294    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1295    T31, T32, internal::None, internal::None, internal::None, internal::None,
1296    internal::None, internal::None, internal::None, internal::None,
1297    internal::None, internal::None, internal::None, internal::None,
1298    internal::None, internal::None, internal::None, internal::None,
1299    internal::None, internal::None> {
1300  typedef internal::Types32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1301      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1302      T27, T28, T29, T30, T31, T32> type;
1303};
1304template <typename T1, typename T2, typename T3, typename T4, typename T5,
1305    typename T6, typename T7, typename T8, typename T9, typename T10,
1306    typename T11, typename T12, typename T13, typename T14, typename T15,
1307    typename T16, typename T17, typename T18, typename T19, typename T20,
1308    typename T21, typename T22, typename T23, typename T24, typename T25,
1309    typename T26, typename T27, typename T28, typename T29, typename T30,
1310    typename T31, typename T32, typename T33>
1311struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1312    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1313    T31, T32, T33, internal::None, internal::None, internal::None,
1314    internal::None, internal::None, internal::None, internal::None,
1315    internal::None, internal::None, internal::None, internal::None,
1316    internal::None, internal::None, internal::None, internal::None,
1317    internal::None, internal::None> {
1318  typedef internal::Types33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1319      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1320      T27, T28, T29, T30, T31, T32, T33> type;
1321};
1322template <typename T1, typename T2, typename T3, typename T4, typename T5,
1323    typename T6, typename T7, typename T8, typename T9, typename T10,
1324    typename T11, typename T12, typename T13, typename T14, typename T15,
1325    typename T16, typename T17, typename T18, typename T19, typename T20,
1326    typename T21, typename T22, typename T23, typename T24, typename T25,
1327    typename T26, typename T27, typename T28, typename T29, typename T30,
1328    typename T31, typename T32, typename T33, typename T34>
1329struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1330    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1331    T31, T32, T33, T34, internal::None, internal::None, internal::None,
1332    internal::None, internal::None, internal::None, internal::None,
1333    internal::None, internal::None, internal::None, internal::None,
1334    internal::None, internal::None, internal::None, internal::None,
1335    internal::None> {
1336  typedef internal::Types34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1337      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1338      T27, T28, T29, T30, T31, T32, T33, T34> type;
1339};
1340template <typename T1, typename T2, typename T3, typename T4, typename T5,
1341    typename T6, typename T7, typename T8, typename T9, typename T10,
1342    typename T11, typename T12, typename T13, typename T14, typename T15,
1343    typename T16, typename T17, typename T18, typename T19, typename T20,
1344    typename T21, typename T22, typename T23, typename T24, typename T25,
1345    typename T26, typename T27, typename T28, typename T29, typename T30,
1346    typename T31, typename T32, typename T33, typename T34, typename T35>
1347struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1348    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1349    T31, T32, T33, T34, T35, internal::None, internal::None, internal::None,
1350    internal::None, internal::None, internal::None, internal::None,
1351    internal::None, internal::None, internal::None, internal::None,
1352    internal::None, internal::None, internal::None, internal::None> {
1353  typedef internal::Types35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1354      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1355      T27, T28, T29, T30, T31, T32, T33, T34, T35> type;
1356};
1357template <typename T1, typename T2, typename T3, typename T4, typename T5,
1358    typename T6, typename T7, typename T8, typename T9, typename T10,
1359    typename T11, typename T12, typename T13, typename T14, typename T15,
1360    typename T16, typename T17, typename T18, typename T19, typename T20,
1361    typename T21, typename T22, typename T23, typename T24, typename T25,
1362    typename T26, typename T27, typename T28, typename T29, typename T30,
1363    typename T31, typename T32, typename T33, typename T34, typename T35,
1364    typename T36>
1365struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1366    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1367    T31, T32, T33, T34, T35, T36, internal::None, internal::None,
1368    internal::None, internal::None, internal::None, internal::None,
1369    internal::None, internal::None, internal::None, internal::None,
1370    internal::None, internal::None, internal::None, internal::None> {
1371  typedef internal::Types36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1372      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1373      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36> type;
1374};
1375template <typename T1, typename T2, typename T3, typename T4, typename T5,
1376    typename T6, typename T7, typename T8, typename T9, typename T10,
1377    typename T11, typename T12, typename T13, typename T14, typename T15,
1378    typename T16, typename T17, typename T18, typename T19, typename T20,
1379    typename T21, typename T22, typename T23, typename T24, typename T25,
1380    typename T26, typename T27, typename T28, typename T29, typename T30,
1381    typename T31, typename T32, typename T33, typename T34, typename T35,
1382    typename T36, typename T37>
1383struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1384    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1385    T31, T32, T33, T34, T35, T36, T37, internal::None, internal::None,
1386    internal::None, internal::None, internal::None, internal::None,
1387    internal::None, internal::None, internal::None, internal::None,
1388    internal::None, internal::None, internal::None> {
1389  typedef internal::Types37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1390      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1391      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> type;
1392};
1393template <typename T1, typename T2, typename T3, typename T4, typename T5,
1394    typename T6, typename T7, typename T8, typename T9, typename T10,
1395    typename T11, typename T12, typename T13, typename T14, typename T15,
1396    typename T16, typename T17, typename T18, typename T19, typename T20,
1397    typename T21, typename T22, typename T23, typename T24, typename T25,
1398    typename T26, typename T27, typename T28, typename T29, typename T30,
1399    typename T31, typename T32, typename T33, typename T34, typename T35,
1400    typename T36, typename T37, typename T38>
1401struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1402    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1403    T31, T32, T33, T34, T35, T36, T37, T38, internal::None, internal::None,
1404    internal::None, internal::None, internal::None, internal::None,
1405    internal::None, internal::None, internal::None, internal::None,
1406    internal::None, internal::None> {
1407  typedef internal::Types38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1408      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1409      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> type;
1410};
1411template <typename T1, typename T2, typename T3, typename T4, typename T5,
1412    typename T6, typename T7, typename T8, typename T9, typename T10,
1413    typename T11, typename T12, typename T13, typename T14, typename T15,
1414    typename T16, typename T17, typename T18, typename T19, typename T20,
1415    typename T21, typename T22, typename T23, typename T24, typename T25,
1416    typename T26, typename T27, typename T28, typename T29, typename T30,
1417    typename T31, typename T32, typename T33, typename T34, typename T35,
1418    typename T36, typename T37, typename T38, typename T39>
1419struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1420    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1421    T31, T32, T33, T34, T35, T36, T37, T38, T39, internal::None,
1422    internal::None, internal::None, internal::None, internal::None,
1423    internal::None, internal::None, internal::None, internal::None,
1424    internal::None, internal::None> {
1425  typedef internal::Types39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1426      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1427      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> type;
1428};
1429template <typename T1, typename T2, typename T3, typename T4, typename T5,
1430    typename T6, typename T7, typename T8, typename T9, typename T10,
1431    typename T11, typename T12, typename T13, typename T14, typename T15,
1432    typename T16, typename T17, typename T18, typename T19, typename T20,
1433    typename T21, typename T22, typename T23, typename T24, typename T25,
1434    typename T26, typename T27, typename T28, typename T29, typename T30,
1435    typename T31, typename T32, typename T33, typename T34, typename T35,
1436    typename T36, typename T37, typename T38, typename T39, typename T40>
1437struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1438    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1439    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, internal::None,
1440    internal::None, internal::None, internal::None, internal::None,
1441    internal::None, internal::None, internal::None, internal::None,
1442    internal::None> {
1443  typedef internal::Types40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1444      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1445      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
1446      T40> type;
1447};
1448template <typename T1, typename T2, typename T3, typename T4, typename T5,
1449    typename T6, typename T7, typename T8, typename T9, typename T10,
1450    typename T11, typename T12, typename T13, typename T14, typename T15,
1451    typename T16, typename T17, typename T18, typename T19, typename T20,
1452    typename T21, typename T22, typename T23, typename T24, typename T25,
1453    typename T26, typename T27, typename T28, typename T29, typename T30,
1454    typename T31, typename T32, typename T33, typename T34, typename T35,
1455    typename T36, typename T37, typename T38, typename T39, typename T40,
1456    typename T41>
1457struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1458    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1459    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, internal::None,
1460    internal::None, internal::None, internal::None, internal::None,
1461    internal::None, internal::None, internal::None, internal::None> {
1462  typedef internal::Types41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1463      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1464      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1465      T41> type;
1466};
1467template <typename T1, typename T2, typename T3, typename T4, typename T5,
1468    typename T6, typename T7, typename T8, typename T9, typename T10,
1469    typename T11, typename T12, typename T13, typename T14, typename T15,
1470    typename T16, typename T17, typename T18, typename T19, typename T20,
1471    typename T21, typename T22, typename T23, typename T24, typename T25,
1472    typename T26, typename T27, typename T28, typename T29, typename T30,
1473    typename T31, typename T32, typename T33, typename T34, typename T35,
1474    typename T36, typename T37, typename T38, typename T39, typename T40,
1475    typename T41, typename T42>
1476struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1477    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1478    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, internal::None,
1479    internal::None, internal::None, internal::None, internal::None,
1480    internal::None, internal::None, internal::None> {
1481  typedef internal::Types42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1482      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1483      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1484      T41, T42> type;
1485};
1486template <typename T1, typename T2, typename T3, typename T4, typename T5,
1487    typename T6, typename T7, typename T8, typename T9, typename T10,
1488    typename T11, typename T12, typename T13, typename T14, typename T15,
1489    typename T16, typename T17, typename T18, typename T19, typename T20,
1490    typename T21, typename T22, typename T23, typename T24, typename T25,
1491    typename T26, typename T27, typename T28, typename T29, typename T30,
1492    typename T31, typename T32, typename T33, typename T34, typename T35,
1493    typename T36, typename T37, typename T38, typename T39, typename T40,
1494    typename T41, typename T42, typename T43>
1495struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1496    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1497    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
1498    internal::None, internal::None, internal::None, internal::None,
1499    internal::None, internal::None, internal::None> {
1500  typedef internal::Types43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1501      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1502      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1503      T41, T42, T43> type;
1504};
1505template <typename T1, typename T2, typename T3, typename T4, typename T5,
1506    typename T6, typename T7, typename T8, typename T9, typename T10,
1507    typename T11, typename T12, typename T13, typename T14, typename T15,
1508    typename T16, typename T17, typename T18, typename T19, typename T20,
1509    typename T21, typename T22, typename T23, typename T24, typename T25,
1510    typename T26, typename T27, typename T28, typename T29, typename T30,
1511    typename T31, typename T32, typename T33, typename T34, typename T35,
1512    typename T36, typename T37, typename T38, typename T39, typename T40,
1513    typename T41, typename T42, typename T43, typename T44>
1514struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1515    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1516    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
1517    internal::None, internal::None, internal::None, internal::None,
1518    internal::None, internal::None> {
1519  typedef internal::Types44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1520      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1521      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1522      T41, T42, T43, T44> type;
1523};
1524template <typename T1, typename T2, typename T3, typename T4, typename T5,
1525    typename T6, typename T7, typename T8, typename T9, typename T10,
1526    typename T11, typename T12, typename T13, typename T14, typename T15,
1527    typename T16, typename T17, typename T18, typename T19, typename T20,
1528    typename T21, typename T22, typename T23, typename T24, typename T25,
1529    typename T26, typename T27, typename T28, typename T29, typename T30,
1530    typename T31, typename T32, typename T33, typename T34, typename T35,
1531    typename T36, typename T37, typename T38, typename T39, typename T40,
1532    typename T41, typename T42, typename T43, typename T44, typename T45>
1533struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1534    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1535    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
1536    internal::None, internal::None, internal::None, internal::None,
1537    internal::None> {
1538  typedef internal::Types45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1539      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1540      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1541      T41, T42, T43, T44, T45> type;
1542};
1543template <typename T1, typename T2, typename T3, typename T4, typename T5,
1544    typename T6, typename T7, typename T8, typename T9, typename T10,
1545    typename T11, typename T12, typename T13, typename T14, typename T15,
1546    typename T16, typename T17, typename T18, typename T19, typename T20,
1547    typename T21, typename T22, typename T23, typename T24, typename T25,
1548    typename T26, typename T27, typename T28, typename T29, typename T30,
1549    typename T31, typename T32, typename T33, typename T34, typename T35,
1550    typename T36, typename T37, typename T38, typename T39, typename T40,
1551    typename T41, typename T42, typename T43, typename T44, typename T45,
1552    typename T46>
1553struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1554    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1555    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
1556    T46, internal::None, internal::None, internal::None, internal::None> {
1557  typedef internal::Types46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1558      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1559      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1560      T41, T42, T43, T44, T45, T46> type;
1561};
1562template <typename T1, typename T2, typename T3, typename T4, typename T5,
1563    typename T6, typename T7, typename T8, typename T9, typename T10,
1564    typename T11, typename T12, typename T13, typename T14, typename T15,
1565    typename T16, typename T17, typename T18, typename T19, typename T20,
1566    typename T21, typename T22, typename T23, typename T24, typename T25,
1567    typename T26, typename T27, typename T28, typename T29, typename T30,
1568    typename T31, typename T32, typename T33, typename T34, typename T35,
1569    typename T36, typename T37, typename T38, typename T39, typename T40,
1570    typename T41, typename T42, typename T43, typename T44, typename T45,
1571    typename T46, typename T47>
1572struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1573    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1574    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
1575    T46, T47, internal::None, internal::None, internal::None> {
1576  typedef internal::Types47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1577      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1578      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1579      T41, T42, T43, T44, T45, T46, T47> type;
1580};
1581template <typename T1, typename T2, typename T3, typename T4, typename T5,
1582    typename T6, typename T7, typename T8, typename T9, typename T10,
1583    typename T11, typename T12, typename T13, typename T14, typename T15,
1584    typename T16, typename T17, typename T18, typename T19, typename T20,
1585    typename T21, typename T22, typename T23, typename T24, typename T25,
1586    typename T26, typename T27, typename T28, typename T29, typename T30,
1587    typename T31, typename T32, typename T33, typename T34, typename T35,
1588    typename T36, typename T37, typename T38, typename T39, typename T40,
1589    typename T41, typename T42, typename T43, typename T44, typename T45,
1590    typename T46, typename T47, typename T48>
1591struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1592    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1593    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
1594    T46, T47, T48, internal::None, internal::None> {
1595  typedef internal::Types48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1596      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1597      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1598      T41, T42, T43, T44, T45, T46, T47, T48> type;
1599};
1600template <typename T1, typename T2, typename T3, typename T4, typename T5,
1601    typename T6, typename T7, typename T8, typename T9, typename T10,
1602    typename T11, typename T12, typename T13, typename T14, typename T15,
1603    typename T16, typename T17, typename T18, typename T19, typename T20,
1604    typename T21, typename T22, typename T23, typename T24, typename T25,
1605    typename T26, typename T27, typename T28, typename T29, typename T30,
1606    typename T31, typename T32, typename T33, typename T34, typename T35,
1607    typename T36, typename T37, typename T38, typename T39, typename T40,
1608    typename T41, typename T42, typename T43, typename T44, typename T45,
1609    typename T46, typename T47, typename T48, typename T49>
1610struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
1611    T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
1612    T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
1613    T46, T47, T48, T49, internal::None> {
1614  typedef internal::Types49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
1615      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
1616      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
1617      T41, T42, T43, T44, T45, T46, T47, T48, T49> type;
1618};
1619
1620namespace internal {
1621
1622# define GTEST_TEMPLATE_ template <typename T> class
1623
1624// The template "selector" struct TemplateSel<Tmpl> is used to
1625// represent Tmpl, which must be a class template with one type
1626// parameter, as a type.  TemplateSel<Tmpl>::Bind<T>::type is defined
1627// as the type Tmpl<T>.  This allows us to actually instantiate the
1628// template "selected" by TemplateSel<Tmpl>.
1629//
1630// This trick is necessary for simulating typedef for class templates,
1631// which C++ doesn't support directly.
1632template <GTEST_TEMPLATE_ Tmpl>
1633struct TemplateSel {
1634  template <typename T>
1635  struct Bind {
1636    typedef Tmpl<T> type;
1637  };
1638};
1639
1640# define GTEST_BIND_(TmplSel, T) \
1641  TmplSel::template Bind<T>::type
1642
1643// A unique struct template used as the default value for the
1644// arguments of class template Templates.  This allows us to simulate
1645// variadic templates (e.g. Templates<int>, Templates<int, double>,
1646// and etc), which C++ doesn't support directly.
1647template <typename T>
1648struct NoneT {};
1649
1650// The following family of struct and struct templates are used to
1651// represent template lists.  In particular, TemplatesN<T1, T2, ...,
1652// TN> represents a list of N templates (T1, T2, ..., and TN).  Except
1653// for Templates0, every struct in the family has two member types:
1654// Head for the selector of the first template in the list, and Tail
1655// for the rest of the list.
1656
1657// The empty template list.
1658struct Templates0 {};
1659
1660// Template lists of length 1, 2, 3, and so on.
1661
1662template <GTEST_TEMPLATE_ T1>
1663struct Templates1 {
1664  typedef TemplateSel<T1> Head;
1665  typedef Templates0 Tail;
1666};
1667template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2>
1668struct Templates2 {
1669  typedef TemplateSel<T1> Head;
1670  typedef Templates1<T2> Tail;
1671};
1672
1673template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3>
1674struct Templates3 {
1675  typedef TemplateSel<T1> Head;
1676  typedef Templates2<T2, T3> Tail;
1677};
1678
1679template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1680    GTEST_TEMPLATE_ T4>
1681struct Templates4 {
1682  typedef TemplateSel<T1> Head;
1683  typedef Templates3<T2, T3, T4> Tail;
1684};
1685
1686template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1687    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5>
1688struct Templates5 {
1689  typedef TemplateSel<T1> Head;
1690  typedef Templates4<T2, T3, T4, T5> Tail;
1691};
1692
1693template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1694    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6>
1695struct Templates6 {
1696  typedef TemplateSel<T1> Head;
1697  typedef Templates5<T2, T3, T4, T5, T6> Tail;
1698};
1699
1700template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1701    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1702    GTEST_TEMPLATE_ T7>
1703struct Templates7 {
1704  typedef TemplateSel<T1> Head;
1705  typedef Templates6<T2, T3, T4, T5, T6, T7> Tail;
1706};
1707
1708template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1709    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1710    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8>
1711struct Templates8 {
1712  typedef TemplateSel<T1> Head;
1713  typedef Templates7<T2, T3, T4, T5, T6, T7, T8> Tail;
1714};
1715
1716template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1717    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1718    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9>
1719struct Templates9 {
1720  typedef TemplateSel<T1> Head;
1721  typedef Templates8<T2, T3, T4, T5, T6, T7, T8, T9> Tail;
1722};
1723
1724template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1725    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1726    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1727    GTEST_TEMPLATE_ T10>
1728struct Templates10 {
1729  typedef TemplateSel<T1> Head;
1730  typedef Templates9<T2, T3, T4, T5, T6, T7, T8, T9, T10> Tail;
1731};
1732
1733template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1734    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1735    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1736    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11>
1737struct Templates11 {
1738  typedef TemplateSel<T1> Head;
1739  typedef Templates10<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tail;
1740};
1741
1742template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1743    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1744    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1745    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12>
1746struct Templates12 {
1747  typedef TemplateSel<T1> Head;
1748  typedef Templates11<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Tail;
1749};
1750
1751template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1752    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1753    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1754    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1755    GTEST_TEMPLATE_ T13>
1756struct Templates13 {
1757  typedef TemplateSel<T1> Head;
1758  typedef Templates12<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Tail;
1759};
1760
1761template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1762    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1763    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1764    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1765    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14>
1766struct Templates14 {
1767  typedef TemplateSel<T1> Head;
1768  typedef Templates13<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
1769      T14> Tail;
1770};
1771
1772template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1773    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1774    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1775    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1776    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15>
1777struct Templates15 {
1778  typedef TemplateSel<T1> Head;
1779  typedef Templates14<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1780      T15> Tail;
1781};
1782
1783template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1784    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1785    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1786    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1787    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1788    GTEST_TEMPLATE_ T16>
1789struct Templates16 {
1790  typedef TemplateSel<T1> Head;
1791  typedef Templates15<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1792      T15, T16> Tail;
1793};
1794
1795template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1796    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1797    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1798    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1799    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1800    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17>
1801struct Templates17 {
1802  typedef TemplateSel<T1> Head;
1803  typedef Templates16<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1804      T15, T16, T17> Tail;
1805};
1806
1807template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1808    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1809    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1810    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1811    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1812    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18>
1813struct Templates18 {
1814  typedef TemplateSel<T1> Head;
1815  typedef Templates17<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1816      T15, T16, T17, T18> Tail;
1817};
1818
1819template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1820    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1821    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1822    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1823    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1824    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1825    GTEST_TEMPLATE_ T19>
1826struct Templates19 {
1827  typedef TemplateSel<T1> Head;
1828  typedef Templates18<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1829      T15, T16, T17, T18, T19> Tail;
1830};
1831
1832template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1833    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1834    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1835    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1836    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1837    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1838    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20>
1839struct Templates20 {
1840  typedef TemplateSel<T1> Head;
1841  typedef Templates19<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1842      T15, T16, T17, T18, T19, T20> Tail;
1843};
1844
1845template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1846    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1847    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1848    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1849    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1850    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1851    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21>
1852struct Templates21 {
1853  typedef TemplateSel<T1> Head;
1854  typedef Templates20<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1855      T15, T16, T17, T18, T19, T20, T21> Tail;
1856};
1857
1858template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1859    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1860    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1861    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1862    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1863    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1864    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1865    GTEST_TEMPLATE_ T22>
1866struct Templates22 {
1867  typedef TemplateSel<T1> Head;
1868  typedef Templates21<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1869      T15, T16, T17, T18, T19, T20, T21, T22> Tail;
1870};
1871
1872template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1873    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1874    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1875    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1876    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1877    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1878    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1879    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23>
1880struct Templates23 {
1881  typedef TemplateSel<T1> Head;
1882  typedef Templates22<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1883      T15, T16, T17, T18, T19, T20, T21, T22, T23> Tail;
1884};
1885
1886template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1887    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1888    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1889    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1890    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1891    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1892    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1893    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24>
1894struct Templates24 {
1895  typedef TemplateSel<T1> Head;
1896  typedef Templates23<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1897      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> Tail;
1898};
1899
1900template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1901    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1902    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1903    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1904    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1905    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1906    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1907    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
1908    GTEST_TEMPLATE_ T25>
1909struct Templates25 {
1910  typedef TemplateSel<T1> Head;
1911  typedef Templates24<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1912      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Tail;
1913};
1914
1915template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1916    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1917    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1918    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1919    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1920    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1921    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1922    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
1923    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26>
1924struct Templates26 {
1925  typedef TemplateSel<T1> Head;
1926  typedef Templates25<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1927      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> Tail;
1928};
1929
1930template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1931    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1932    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1933    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1934    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1935    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1936    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1937    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
1938    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27>
1939struct Templates27 {
1940  typedef TemplateSel<T1> Head;
1941  typedef Templates26<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1942      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> Tail;
1943};
1944
1945template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1946    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1947    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1948    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1949    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1950    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1951    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1952    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
1953    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
1954    GTEST_TEMPLATE_ T28>
1955struct Templates28 {
1956  typedef TemplateSel<T1> Head;
1957  typedef Templates27<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1958      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
1959      T28> Tail;
1960};
1961
1962template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1963    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1964    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1965    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1966    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1967    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1968    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1969    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
1970    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
1971    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29>
1972struct Templates29 {
1973  typedef TemplateSel<T1> Head;
1974  typedef Templates28<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1975      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1976      T29> Tail;
1977};
1978
1979template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1980    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1981    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1982    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
1983    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
1984    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
1985    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
1986    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
1987    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
1988    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30>
1989struct Templates30 {
1990  typedef TemplateSel<T1> Head;
1991  typedef Templates29<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
1992      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
1993      T29, T30> Tail;
1994};
1995
1996template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
1997    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
1998    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
1999    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2000    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2001    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2002    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2003    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2004    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2005    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2006    GTEST_TEMPLATE_ T31>
2007struct Templates31 {
2008  typedef TemplateSel<T1> Head;
2009  typedef Templates30<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2010      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2011      T29, T30, T31> Tail;
2012};
2013
2014template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2015    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2016    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2017    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2018    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2019    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2020    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2021    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2022    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2023    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2024    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32>
2025struct Templates32 {
2026  typedef TemplateSel<T1> Head;
2027  typedef Templates31<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2028      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2029      T29, T30, T31, T32> Tail;
2030};
2031
2032template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2033    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2034    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2035    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2036    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2037    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2038    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2039    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2040    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2041    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2042    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33>
2043struct Templates33 {
2044  typedef TemplateSel<T1> Head;
2045  typedef Templates32<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2046      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2047      T29, T30, T31, T32, T33> Tail;
2048};
2049
2050template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2051    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2052    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2053    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2054    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2055    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2056    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2057    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2058    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2059    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2060    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2061    GTEST_TEMPLATE_ T34>
2062struct Templates34 {
2063  typedef TemplateSel<T1> Head;
2064  typedef Templates33<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2065      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2066      T29, T30, T31, T32, T33, T34> Tail;
2067};
2068
2069template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2070    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2071    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2072    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2073    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2074    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2075    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2076    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2077    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2078    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2079    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2080    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35>
2081struct Templates35 {
2082  typedef TemplateSel<T1> Head;
2083  typedef Templates34<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2084      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2085      T29, T30, T31, T32, T33, T34, T35> Tail;
2086};
2087
2088template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2089    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2090    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2091    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2092    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2093    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2094    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2095    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2096    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2097    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2098    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2099    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36>
2100struct Templates36 {
2101  typedef TemplateSel<T1> Head;
2102  typedef Templates35<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2103      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2104      T29, T30, T31, T32, T33, T34, T35, T36> Tail;
2105};
2106
2107template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2108    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2109    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2110    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2111    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2112    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2113    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2114    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2115    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2116    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2117    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2118    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2119    GTEST_TEMPLATE_ T37>
2120struct Templates37 {
2121  typedef TemplateSel<T1> Head;
2122  typedef Templates36<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2123      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2124      T29, T30, T31, T32, T33, T34, T35, T36, T37> Tail;
2125};
2126
2127template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2128    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2129    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2130    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2131    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2132    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2133    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2134    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2135    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2136    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2137    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2138    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2139    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38>
2140struct Templates38 {
2141  typedef TemplateSel<T1> Head;
2142  typedef Templates37<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2143      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2144      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> Tail;
2145};
2146
2147template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2148    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2149    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2150    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2151    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2152    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2153    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2154    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2155    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2156    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2157    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2158    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2159    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39>
2160struct Templates39 {
2161  typedef TemplateSel<T1> Head;
2162  typedef Templates38<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2163      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2164      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Tail;
2165};
2166
2167template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2168    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2169    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2170    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2171    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2172    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2173    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2174    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2175    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2176    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2177    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2178    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2179    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2180    GTEST_TEMPLATE_ T40>
2181struct Templates40 {
2182  typedef TemplateSel<T1> Head;
2183  typedef Templates39<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2184      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2185      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Tail;
2186};
2187
2188template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2189    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2190    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2191    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2192    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2193    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2194    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2195    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2196    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2197    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2198    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2199    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2200    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2201    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41>
2202struct Templates41 {
2203  typedef TemplateSel<T1> Head;
2204  typedef Templates40<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2205      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2206      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> Tail;
2207};
2208
2209template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2210    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2211    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2212    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2213    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2214    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2215    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2216    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2217    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2218    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2219    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2220    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2221    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2222    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42>
2223struct Templates42 {
2224  typedef TemplateSel<T1> Head;
2225  typedef Templates41<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2226      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2227      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
2228      T42> Tail;
2229};
2230
2231template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2232    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2233    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2234    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2235    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2236    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2237    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2238    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2239    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2240    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2241    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2242    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2243    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2244    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2245    GTEST_TEMPLATE_ T43>
2246struct Templates43 {
2247  typedef TemplateSel<T1> Head;
2248  typedef Templates42<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2249      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2250      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2251      T43> Tail;
2252};
2253
2254template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2255    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2256    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2257    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2258    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2259    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2260    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2261    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2262    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2263    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2264    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2265    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2266    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2267    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2268    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44>
2269struct Templates44 {
2270  typedef TemplateSel<T1> Head;
2271  typedef Templates43<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2272      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2273      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2274      T43, T44> Tail;
2275};
2276
2277template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2278    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2279    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2280    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2281    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2282    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2283    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2284    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2285    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2286    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2287    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2288    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2289    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2290    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2291    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45>
2292struct Templates45 {
2293  typedef TemplateSel<T1> Head;
2294  typedef Templates44<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2295      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2296      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2297      T43, T44, T45> Tail;
2298};
2299
2300template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2301    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2302    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2303    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2304    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2305    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2306    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2307    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2308    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2309    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2310    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2311    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2312    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2313    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2314    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
2315    GTEST_TEMPLATE_ T46>
2316struct Templates46 {
2317  typedef TemplateSel<T1> Head;
2318  typedef Templates45<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2319      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2320      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2321      T43, T44, T45, T46> Tail;
2322};
2323
2324template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2325    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2326    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2327    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2328    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2329    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2330    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2331    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2332    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2333    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2334    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2335    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2336    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2337    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2338    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
2339    GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47>
2340struct Templates47 {
2341  typedef TemplateSel<T1> Head;
2342  typedef Templates46<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2343      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2344      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2345      T43, T44, T45, T46, T47> Tail;
2346};
2347
2348template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2349    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2350    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2351    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2352    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2353    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2354    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2355    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2356    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2357    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2358    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2359    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2360    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2361    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2362    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
2363    GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48>
2364struct Templates48 {
2365  typedef TemplateSel<T1> Head;
2366  typedef Templates47<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2367      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2368      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2369      T43, T44, T45, T46, T47, T48> Tail;
2370};
2371
2372template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2373    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2374    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2375    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2376    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2377    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2378    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2379    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2380    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2381    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2382    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2383    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2384    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2385    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2386    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
2387    GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48,
2388    GTEST_TEMPLATE_ T49>
2389struct Templates49 {
2390  typedef TemplateSel<T1> Head;
2391  typedef Templates48<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2392      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2393      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2394      T43, T44, T45, T46, T47, T48, T49> Tail;
2395};
2396
2397template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2398    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2399    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2400    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2401    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2402    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2403    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2404    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2405    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2406    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2407    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2408    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
2409    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
2410    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
2411    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
2412    GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48,
2413    GTEST_TEMPLATE_ T49, GTEST_TEMPLATE_ T50>
2414struct Templates50 {
2415  typedef TemplateSel<T1> Head;
2416  typedef Templates49<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2417      T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2418      T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
2419      T43, T44, T45, T46, T47, T48, T49, T50> Tail;
2420};
2421
2422
2423// We don't want to require the users to write TemplatesN<...> directly,
2424// as that would require them to count the length.  Templates<...> is much
2425// easier to write, but generates horrible messages when there is a
2426// compiler error, as gcc insists on printing out each template
2427// argument, even if it has the default value (this means Templates<list>
2428// will appear as Templates<list, NoneT, NoneT, ..., NoneT> in the compiler
2429// errors).
2430//
2431// Our solution is to combine the best part of the two approaches: a
2432// user would write Templates<T1, ..., TN>, and Google Test will translate
2433// that to TemplatesN<T1, ..., TN> internally to make error messages
2434// readable.  The translation is done by the 'type' member of the
2435// Templates template.
2436template <GTEST_TEMPLATE_ T1 = NoneT, GTEST_TEMPLATE_ T2 = NoneT,
2437    GTEST_TEMPLATE_ T3 = NoneT, GTEST_TEMPLATE_ T4 = NoneT,
2438    GTEST_TEMPLATE_ T5 = NoneT, GTEST_TEMPLATE_ T6 = NoneT,
2439    GTEST_TEMPLATE_ T7 = NoneT, GTEST_TEMPLATE_ T8 = NoneT,
2440    GTEST_TEMPLATE_ T9 = NoneT, GTEST_TEMPLATE_ T10 = NoneT,
2441    GTEST_TEMPLATE_ T11 = NoneT, GTEST_TEMPLATE_ T12 = NoneT,
2442    GTEST_TEMPLATE_ T13 = NoneT, GTEST_TEMPLATE_ T14 = NoneT,
2443    GTEST_TEMPLATE_ T15 = NoneT, GTEST_TEMPLATE_ T16 = NoneT,
2444    GTEST_TEMPLATE_ T17 = NoneT, GTEST_TEMPLATE_ T18 = NoneT,
2445    GTEST_TEMPLATE_ T19 = NoneT, GTEST_TEMPLATE_ T20 = NoneT,
2446    GTEST_TEMPLATE_ T21 = NoneT, GTEST_TEMPLATE_ T22 = NoneT,
2447    GTEST_TEMPLATE_ T23 = NoneT, GTEST_TEMPLATE_ T24 = NoneT,
2448    GTEST_TEMPLATE_ T25 = NoneT, GTEST_TEMPLATE_ T26 = NoneT,
2449    GTEST_TEMPLATE_ T27 = NoneT, GTEST_TEMPLATE_ T28 = NoneT,
2450    GTEST_TEMPLATE_ T29 = NoneT, GTEST_TEMPLATE_ T30 = NoneT,
2451    GTEST_TEMPLATE_ T31 = NoneT, GTEST_TEMPLATE_ T32 = NoneT,
2452    GTEST_TEMPLATE_ T33 = NoneT, GTEST_TEMPLATE_ T34 = NoneT,
2453    GTEST_TEMPLATE_ T35 = NoneT, GTEST_TEMPLATE_ T36 = NoneT,
2454    GTEST_TEMPLATE_ T37 = NoneT, GTEST_TEMPLATE_ T38 = NoneT,
2455    GTEST_TEMPLATE_ T39 = NoneT, GTEST_TEMPLATE_ T40 = NoneT,
2456    GTEST_TEMPLATE_ T41 = NoneT, GTEST_TEMPLATE_ T42 = NoneT,
2457    GTEST_TEMPLATE_ T43 = NoneT, GTEST_TEMPLATE_ T44 = NoneT,
2458    GTEST_TEMPLATE_ T45 = NoneT, GTEST_TEMPLATE_ T46 = NoneT,
2459    GTEST_TEMPLATE_ T47 = NoneT, GTEST_TEMPLATE_ T48 = NoneT,
2460    GTEST_TEMPLATE_ T49 = NoneT, GTEST_TEMPLATE_ T50 = NoneT>
2461struct Templates {
2462  typedef Templates50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2463      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2464      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
2465      T42, T43, T44, T45, T46, T47, T48, T49, T50> type;
2466};
2467
2468template <>
2469struct Templates<NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2470    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2471    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2472    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2473    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2474    NoneT> {
2475  typedef Templates0 type;
2476};
2477template <GTEST_TEMPLATE_ T1>
2478struct Templates<T1, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2479    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2480    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2481    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2482    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2483    NoneT> {
2484  typedef Templates1<T1> type;
2485};
2486template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2>
2487struct Templates<T1, T2, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2488    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2489    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2490    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2491    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2492    NoneT> {
2493  typedef Templates2<T1, T2> type;
2494};
2495template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3>
2496struct Templates<T1, T2, T3, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2497    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2498    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2499    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2500    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2501  typedef Templates3<T1, T2, T3> type;
2502};
2503template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2504    GTEST_TEMPLATE_ T4>
2505struct Templates<T1, T2, T3, T4, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2506    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2507    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2508    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2509    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2510  typedef Templates4<T1, T2, T3, T4> type;
2511};
2512template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2513    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5>
2514struct Templates<T1, T2, T3, T4, T5, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2515    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2516    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2517    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2518    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2519  typedef Templates5<T1, T2, T3, T4, T5> type;
2520};
2521template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2522    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6>
2523struct Templates<T1, T2, T3, T4, T5, T6, NoneT, NoneT, NoneT, NoneT, NoneT,
2524    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2525    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2526    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2527    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2528  typedef Templates6<T1, T2, T3, T4, T5, T6> type;
2529};
2530template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2531    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2532    GTEST_TEMPLATE_ T7>
2533struct Templates<T1, T2, T3, T4, T5, T6, T7, NoneT, NoneT, NoneT, NoneT, NoneT,
2534    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2535    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2536    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2537    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2538  typedef Templates7<T1, T2, T3, T4, T5, T6, T7> type;
2539};
2540template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2541    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2542    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8>
2543struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, NoneT, NoneT, NoneT, NoneT,
2544    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2545    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2546    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2547    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2548  typedef Templates8<T1, T2, T3, T4, T5, T6, T7, T8> type;
2549};
2550template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2551    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2552    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9>
2553struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, NoneT, NoneT, NoneT,
2554    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2555    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2556    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2557    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2558  typedef Templates9<T1, T2, T3, T4, T5, T6, T7, T8, T9> type;
2559};
2560template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2561    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2562    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2563    GTEST_TEMPLATE_ T10>
2564struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, NoneT, NoneT, NoneT,
2565    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2566    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2567    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2568    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2569  typedef Templates10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> type;
2570};
2571template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2572    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2573    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2574    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11>
2575struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, NoneT, NoneT,
2576    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2577    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2578    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2579    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2580  typedef Templates11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> type;
2581};
2582template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2583    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2584    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2585    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12>
2586struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, NoneT,
2587    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2588    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2589    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2590    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2591  typedef Templates12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> type;
2592};
2593template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2594    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2595    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2596    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2597    GTEST_TEMPLATE_ T13>
2598struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, NoneT,
2599    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2600    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2601    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2602    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2603  typedef Templates13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
2604      T13> type;
2605};
2606template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2607    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2608    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2609    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2610    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14>
2611struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2612    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2613    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2614    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2615    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2616  typedef Templates14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2617      T14> type;
2618};
2619template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2620    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2621    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2622    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2623    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15>
2624struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2625    T15, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2626    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2627    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2628    NoneT, NoneT, NoneT, NoneT, NoneT> {
2629  typedef Templates15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2630      T14, T15> type;
2631};
2632template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2633    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2634    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2635    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2636    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2637    GTEST_TEMPLATE_ T16>
2638struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2639    T15, T16, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2640    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2641    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2642    NoneT, NoneT, NoneT, NoneT, NoneT> {
2643  typedef Templates16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2644      T14, T15, T16> type;
2645};
2646template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2647    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2648    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2649    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2650    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2651    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17>
2652struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2653    T15, T16, T17, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2654    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2655    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2656    NoneT, NoneT, NoneT, NoneT, NoneT> {
2657  typedef Templates17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2658      T14, T15, T16, T17> type;
2659};
2660template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2661    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2662    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2663    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2664    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2665    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18>
2666struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2667    T15, T16, T17, T18, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2668    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2669    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2670    NoneT, NoneT, NoneT, NoneT> {
2671  typedef Templates18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2672      T14, T15, T16, T17, T18> type;
2673};
2674template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2675    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2676    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2677    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2678    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2679    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2680    GTEST_TEMPLATE_ T19>
2681struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2682    T15, T16, T17, T18, T19, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2683    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2684    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2685    NoneT, NoneT, NoneT, NoneT> {
2686  typedef Templates19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2687      T14, T15, T16, T17, T18, T19> type;
2688};
2689template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2690    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2691    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2692    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2693    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2694    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2695    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20>
2696struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2697    T15, T16, T17, T18, T19, T20, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2698    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2699    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2700    NoneT, NoneT, NoneT, NoneT> {
2701  typedef Templates20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2702      T14, T15, T16, T17, T18, T19, T20> type;
2703};
2704template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2705    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2706    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2707    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2708    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2709    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2710    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21>
2711struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2712    T15, T16, T17, T18, T19, T20, T21, NoneT, NoneT, NoneT, NoneT, NoneT,
2713    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2714    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2715    NoneT, NoneT, NoneT, NoneT> {
2716  typedef Templates21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2717      T14, T15, T16, T17, T18, T19, T20, T21> type;
2718};
2719template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2720    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2721    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2722    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2723    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2724    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2725    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2726    GTEST_TEMPLATE_ T22>
2727struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2728    T15, T16, T17, T18, T19, T20, T21, T22, NoneT, NoneT, NoneT, NoneT, NoneT,
2729    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2730    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2731    NoneT, NoneT, NoneT> {
2732  typedef Templates22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2733      T14, T15, T16, T17, T18, T19, T20, T21, T22> type;
2734};
2735template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2736    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2737    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2738    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2739    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2740    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2741    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2742    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23>
2743struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2744    T15, T16, T17, T18, T19, T20, T21, T22, T23, NoneT, NoneT, NoneT, NoneT,
2745    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2746    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2747    NoneT, NoneT, NoneT> {
2748  typedef Templates23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2749      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> type;
2750};
2751template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2752    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2753    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2754    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2755    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2756    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2757    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2758    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24>
2759struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2760    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, NoneT, NoneT, NoneT,
2761    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2762    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2763    NoneT, NoneT, NoneT> {
2764  typedef Templates24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2765      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> type;
2766};
2767template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2768    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2769    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2770    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2771    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2772    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2773    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2774    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2775    GTEST_TEMPLATE_ T25>
2776struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2777    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, NoneT, NoneT, NoneT,
2778    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2779    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2780    NoneT, NoneT> {
2781  typedef Templates25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2782      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> type;
2783};
2784template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2785    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2786    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2787    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2788    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2789    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2790    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2791    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2792    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26>
2793struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2794    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, NoneT, NoneT,
2795    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2796    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2797    NoneT, NoneT> {
2798  typedef Templates26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2799      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> type;
2800};
2801template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2802    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2803    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2804    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2805    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2806    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2807    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2808    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2809    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27>
2810struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2811    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, NoneT,
2812    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2813    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2814    NoneT, NoneT> {
2815  typedef Templates27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2816      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
2817      T27> type;
2818};
2819template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2820    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2821    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2822    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2823    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2824    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2825    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2826    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2827    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2828    GTEST_TEMPLATE_ T28>
2829struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2830    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
2831    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2832    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2833    NoneT, NoneT> {
2834  typedef Templates28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2835      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2836      T28> type;
2837};
2838template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2839    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2840    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2841    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2842    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2843    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2844    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2845    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2846    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2847    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29>
2848struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2849    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2850    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2851    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2852    NoneT> {
2853  typedef Templates29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2854      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2855      T28, T29> type;
2856};
2857template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2858    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2859    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2860    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2861    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2862    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2863    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2864    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2865    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2866    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30>
2867struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2868    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2869    T30, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2870    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2871  typedef Templates30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2872      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2873      T28, T29, T30> type;
2874};
2875template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2876    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2877    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2878    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2879    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2880    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2881    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2882    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2883    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2884    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2885    GTEST_TEMPLATE_ T31>
2886struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2887    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2888    T30, T31, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2889    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2890  typedef Templates31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2891      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2892      T28, T29, T30, T31> type;
2893};
2894template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2895    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2896    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2897    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2898    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2899    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2900    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2901    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2902    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2903    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2904    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32>
2905struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2906    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2907    T30, T31, T32, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2908    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2909  typedef Templates32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2910      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2911      T28, T29, T30, T31, T32> type;
2912};
2913template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2914    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2915    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2916    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2917    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2918    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2919    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2920    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2921    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2922    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2923    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33>
2924struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2925    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2926    T30, T31, T32, T33, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2927    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2928  typedef Templates33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2929      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2930      T28, T29, T30, T31, T32, T33> type;
2931};
2932template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2933    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2934    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2935    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2936    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2937    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2938    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2939    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2940    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2941    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2942    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2943    GTEST_TEMPLATE_ T34>
2944struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2945    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2946    T30, T31, T32, T33, T34, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2947    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2948  typedef Templates34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2949      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2950      T28, T29, T30, T31, T32, T33, T34> type;
2951};
2952template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2953    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2954    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2955    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2956    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2957    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2958    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2959    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2960    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2961    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2962    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2963    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35>
2964struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2965    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2966    T30, T31, T32, T33, T34, T35, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
2967    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2968  typedef Templates35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2969      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2970      T28, T29, T30, T31, T32, T33, T34, T35> type;
2971};
2972template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2973    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2974    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2975    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2976    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2977    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2978    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2979    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
2980    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
2981    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
2982    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
2983    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36>
2984struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
2985    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
2986    T30, T31, T32, T33, T34, T35, T36, NoneT, NoneT, NoneT, NoneT, NoneT,
2987    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
2988  typedef Templates36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
2989      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
2990      T28, T29, T30, T31, T32, T33, T34, T35, T36> type;
2991};
2992template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
2993    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
2994    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
2995    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
2996    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
2997    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
2998    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
2999    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3000    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3001    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3002    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3003    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3004    GTEST_TEMPLATE_ T37>
3005struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3006    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3007    T30, T31, T32, T33, T34, T35, T36, T37, NoneT, NoneT, NoneT, NoneT, NoneT,
3008    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3009  typedef Templates37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3010      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3011      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> type;
3012};
3013template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3014    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3015    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3016    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3017    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3018    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3019    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3020    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3021    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3022    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3023    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3024    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3025    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38>
3026struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3027    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3028    T30, T31, T32, T33, T34, T35, T36, T37, T38, NoneT, NoneT, NoneT, NoneT,
3029    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3030  typedef Templates38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3031      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3032      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> type;
3033};
3034template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3035    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3036    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3037    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3038    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3039    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3040    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3041    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3042    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3043    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3044    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3045    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3046    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39>
3047struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3048    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3049    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, NoneT, NoneT, NoneT,
3050    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3051  typedef Templates39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3052      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3053      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> type;
3054};
3055template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3056    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3057    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3058    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3059    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3060    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3061    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3062    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3063    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3064    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3065    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3066    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3067    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3068    GTEST_TEMPLATE_ T40>
3069struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3070    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3071    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, NoneT, NoneT, NoneT,
3072    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3073  typedef Templates40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3074      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3075      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> type;
3076};
3077template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3078    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3079    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3080    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3081    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3082    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3083    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3084    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3085    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3086    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3087    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3088    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3089    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3090    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41>
3091struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3092    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3093    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, NoneT, NoneT,
3094    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3095  typedef Templates41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3096      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3097      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
3098      T41> type;
3099};
3100template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3101    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3102    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3103    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3104    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3105    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3106    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3107    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3108    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3109    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3110    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3111    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3112    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3113    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42>
3114struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3115    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3116    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, NoneT,
3117    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3118  typedef Templates42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3119      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3120      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3121      T42> type;
3122};
3123template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3124    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3125    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3126    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3127    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3128    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3129    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3130    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3131    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3132    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3133    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3134    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3135    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3136    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
3137    GTEST_TEMPLATE_ T43>
3138struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3139    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3140    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
3141    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3142  typedef Templates43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3143      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3144      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3145      T42, T43> type;
3146};
3147template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3148    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3149    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3150    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3151    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3152    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3153    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3154    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3155    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3156    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3157    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3158    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3159    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3160    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
3161    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44>
3162struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3163    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3164    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
3165    NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
3166  typedef Templates44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3167      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3168      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3169      T42, T43, T44> type;
3170};
3171template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3172    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3173    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3174    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3175    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3176    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3177    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3178    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3179    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3180    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3181    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3182    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3183    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3184    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
3185    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45>
3186struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3187    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3188    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
3189    T45, NoneT, NoneT, NoneT, NoneT, NoneT> {
3190  typedef Templates45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3191      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3192      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3193      T42, T43, T44, T45> type;
3194};
3195template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3196    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3197    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3198    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3199    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3200    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3201    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3202    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3203    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3204    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3205    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3206    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3207    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3208    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
3209    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
3210    GTEST_TEMPLATE_ T46>
3211struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3212    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3213    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
3214    T45, T46, NoneT, NoneT, NoneT, NoneT> {
3215  typedef Templates46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3216      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3217      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3218      T42, T43, T44, T45, T46> type;
3219};
3220template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3221    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3222    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3223    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3224    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3225    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3226    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3227    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3228    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3229    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3230    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3231    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3232    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3233    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
3234    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
3235    GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47>
3236struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3237    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3238    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
3239    T45, T46, T47, NoneT, NoneT, NoneT> {
3240  typedef Templates47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3241      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3242      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3243      T42, T43, T44, T45, T46, T47> type;
3244};
3245template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3246    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3247    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3248    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3249    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3250    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3251    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3252    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3253    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3254    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3255    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3256    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3257    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3258    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
3259    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
3260    GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48>
3261struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3262    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3263    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
3264    T45, T46, T47, T48, NoneT, NoneT> {
3265  typedef Templates48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3266      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3267      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3268      T42, T43, T44, T45, T46, T47, T48> type;
3269};
3270template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
3271    GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
3272    GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
3273    GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
3274    GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
3275    GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
3276    GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
3277    GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
3278    GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
3279    GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
3280    GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
3281    GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
3282    GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
3283    GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
3284    GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
3285    GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48,
3286    GTEST_TEMPLATE_ T49>
3287struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
3288    T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
3289    T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
3290    T45, T46, T47, T48, T49, NoneT> {
3291  typedef Templates49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3292      T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
3293      T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
3294      T42, T43, T44, T45, T46, T47, T48, T49> type;
3295};
3296
3297// The TypeList template makes it possible to use either a single type
3298// or a Types<...> list in TYPED_TEST_CASE() and
3299// INSTANTIATE_TYPED_TEST_CASE_P().
3300
3301template <typename T>
3302struct TypeList {
3303  typedef Types1<T> type;
3304};
3305
3306template <typename T1, typename T2, typename T3, typename T4, typename T5,
3307    typename T6, typename T7, typename T8, typename T9, typename T10,
3308    typename T11, typename T12, typename T13, typename T14, typename T15,
3309    typename T16, typename T17, typename T18, typename T19, typename T20,
3310    typename T21, typename T22, typename T23, typename T24, typename T25,
3311    typename T26, typename T27, typename T28, typename T29, typename T30,
3312    typename T31, typename T32, typename T33, typename T34, typename T35,
3313    typename T36, typename T37, typename T38, typename T39, typename T40,
3314    typename T41, typename T42, typename T43, typename T44, typename T45,
3315    typename T46, typename T47, typename T48, typename T49, typename T50>
3316struct TypeList<Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
3317    T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
3318    T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
3319    T44, T45, T46, T47, T48, T49, T50> > {
3320  typedef typename Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
3321      T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
3322      T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
3323      T41, T42, T43, T44, T45, T46, T47, T48, T49, T50>::type type;
3324};
3325
3326#endif  // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
3327
3328}  // namespace internal
3329}  // namespace testing
3330
3331#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
trunk/3rdparty/googletest/googletest/include/gtest/internal/gtest-type-util.h.pump
r0r249096
1$$ -*- mode: c++; -*-
2$var n = 50  $$ Maximum length of type lists we want to support.
3// Copyright 2008 Google Inc.
4// All Rights Reserved.
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
10//     * Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//     * Redistributions in binary form must reproduce the above
13// copyright notice, this list of conditions and the following disclaimer
14// in the documentation and/or other materials provided with the
15// distribution.
16//     * Neither the name of Google Inc. nor the names of its
17// contributors may be used to endorse or promote products derived from
18// this software without specific prior written permission.
19//
20// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34// Type utilities needed for implementing typed and type-parameterized
35// tests.  This file is generated by a SCRIPT.  DO NOT EDIT BY HAND!
36//
37// Currently we support at most $n types in a list, and at most $n
38// type-parameterized tests in one type-parameterized test case.
39// Please contact googletestframework@googlegroups.com if you need
40// more.
41
42#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
43#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
44
45#include "gtest/internal/gtest-port.h"
46
47// #ifdef __GNUC__ is too general here.  It is possible to use gcc without using
48// libstdc++ (which is where cxxabi.h comes from).
49# if GTEST_HAS_CXXABI_H_
50#  include <cxxabi.h>
51# elif defined(__HP_aCC)
52#  include <acxx_demangle.h>
53# endif  // GTEST_HASH_CXXABI_H_
54
55namespace testing {
56namespace internal {
57
58// GetTypeName<T>() returns a human-readable name of type T.
59// NB: This function is also used in Google Mock, so don't move it inside of
60// the typed-test-only section below.
61template <typename T>
62std::string GetTypeName() {
63# if GTEST_HAS_RTTI
64
65  const char* const name = typeid(T).name();
66#  if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
67  int status = 0;
68  // gcc's implementation of typeid(T).name() mangles the type name,
69  // so we have to demangle it.
70#   if GTEST_HAS_CXXABI_H_
71  using abi::__cxa_demangle;
72#   endif  // GTEST_HAS_CXXABI_H_
73  char* const readable_name = __cxa_demangle(name, 0, 0, &status);
74  const std::string name_str(status == 0 ? readable_name : name);
75  free(readable_name);
76  return name_str;
77#  else
78  return name;
79#  endif  // GTEST_HAS_CXXABI_H_ || __HP_aCC
80
81# else
82
83  return "<type>";
84
85# endif  // GTEST_HAS_RTTI
86}
87
88#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
89
90// AssertyTypeEq<T1, T2>::type is defined iff T1 and T2 are the same
91// type.  This can be used as a compile-time assertion to ensure that
92// two types are equal.
93
94template <typename T1, typename T2>
95struct AssertTypeEq;
96
97template <typename T>
98struct AssertTypeEq<T, T> {
99  typedef bool type;
100};
101
102// A unique type used as the default value for the arguments of class
103// template Types.  This allows us to simulate variadic templates
104// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't
105// support directly.
106struct None {};
107
108// The following family of struct and struct templates are used to
109// represent type lists.  In particular, TypesN<T1, T2, ..., TN>
110// represents a type list with N types (T1, T2, ..., and TN) in it.
111// Except for Types0, every struct in the family has two member types:
112// Head for the first type in the list, and Tail for the rest of the
113// list.
114
115// The empty type list.
116struct Types0 {};
117
118// Type lists of length 1, 2, 3, and so on.
119
120template <typename T1>
121struct Types1 {
122  typedef T1 Head;
123  typedef Types0 Tail;
124};
125
126$range i 2..n
127
128$for i [[
129$range j 1..i
130$range k 2..i
131template <$for j, [[typename T$j]]>
132struct Types$i {
133  typedef T1 Head;
134  typedef Types$(i-1)<$for k, [[T$k]]> Tail;
135};
136
137
138]]
139
140}  // namespace internal
141
142// We don't want to require the users to write TypesN<...> directly,
143// as that would require them to count the length.  Types<...> is much
144// easier to write, but generates horrible messages when there is a
145// compiler error, as gcc insists on printing out each template
146// argument, even if it has the default value (this means Types<int>
147// will appear as Types<int, None, None, ..., None> in the compiler
148// errors).
149//
150// Our solution is to combine the best part of the two approaches: a
151// user would write Types<T1, ..., TN>, and Google Test will translate
152// that to TypesN<T1, ..., TN> internally to make error messages
153// readable.  The translation is done by the 'type' member of the
154// Types template.
155
156$range i 1..n
157template <$for i, [[typename T$i = internal::None]]>
158struct Types {
159  typedef internal::Types$n<$for i, [[T$i]]> type;
160};
161
162template <>
163struct Types<$for i, [[internal::None]]> {
164  typedef internal::Types0 type;
165};
166
167$range i 1..n-1
168$for i [[
169$range j 1..i
170$range k i+1..n
171template <$for j, [[typename T$j]]>
172struct Types<$for j, [[T$j]]$for k[[, internal::None]]> {
173  typedef internal::Types$i<$for j, [[T$j]]> type;
174};
175
176]]
177
178namespace internal {
179
180# define GTEST_TEMPLATE_ template <typename T> class
181
182// The template "selector" struct TemplateSel<Tmpl> is used to
183// represent Tmpl, which must be a class template with one type
184// parameter, as a type.  TemplateSel<Tmpl>::Bind<T>::type is defined
185// as the type Tmpl<T>.  This allows us to actually instantiate the
186// template "selected" by TemplateSel<Tmpl>.
187//
188// This trick is necessary for simulating typedef for class templates,
189// which C++ doesn't support directly.
190template <GTEST_TEMPLATE_ Tmpl>
191struct TemplateSel {
192  template <typename T>
193  struct Bind {
194    typedef Tmpl<T> type;
195  };
196};
197
198# define GTEST_BIND_(TmplSel, T) \
199  TmplSel::template Bind<T>::type
200
201// A unique struct template used as the default value for the
202// arguments of class template Templates.  This allows us to simulate
203// variadic templates (e.g. Templates<int>, Templates<int, double>,
204// and etc), which C++ doesn't support directly.
205template <typename T>
206struct NoneT {};
207
208// The following family of struct and struct templates are used to
209// represent template lists.  In particular, TemplatesN<T1, T2, ...,
210// TN> represents a list of N templates (T1, T2, ..., and TN).  Except
211// for Templates0, every struct in the family has two member types:
212// Head for the selector of the first template in the list, and Tail
213// for the rest of the list.
214
215// The empty template list.
216struct Templates0 {};
217
218// Template lists of length 1, 2, 3, and so on.
219
220template <GTEST_TEMPLATE_ T1>
221struct Templates1 {
222  typedef TemplateSel<T1> Head;
223  typedef Templates0 Tail;
224};
225
226$range i 2..n
227
228$for i [[
229$range j 1..i
230$range k 2..i
231template <$for j, [[GTEST_TEMPLATE_ T$j]]>
232struct Templates$i {
233  typedef TemplateSel<T1> Head;
234  typedef Templates$(i-1)<$for k, [[T$k]]> Tail;
235};
236
237
238]]
239
240// We don't want to require the users to write TemplatesN<...> directly,
241// as that would require them to count the length.  Templates<...> is much
242// easier to write, but generates horrible messages when there is a
243// compiler error, as gcc insists on printing out each template
244// argument, even if it has the default value (this means Templates<list>
245// will appear as Templates<list, NoneT, NoneT, ..., NoneT> in the compiler
246// errors).
247//
248// Our solution is to combine the best part of the two approaches: a
249// user would write Templates<T1, ..., TN>, and Google Test will translate
250// that to TemplatesN<T1, ..., TN> internally to make error messages
251// readable.  The translation is done by the 'type' member of the
252// Templates template.
253
254$range i 1..n
255template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]>
256struct Templates {
257  typedef Templates$n<$for i, [[T$i]]> type;
258};
259
260template <>
261struct Templates<$for i, [[NoneT]]> {
262  typedef Templates0 type;
263};
264
265$range i 1..n-1
266$for i [[
267$range j 1..i
268$range k i+1..n
269template <$for j, [[GTEST_TEMPLATE_ T$j]]>
270struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> {
271  typedef Templates$i<$for j, [[T$j]]> type;
272};
273
274]]
275
276// The TypeList template makes it possible to use either a single type
277// or a Types<...> list in TYPED_TEST_CASE() and
278// INSTANTIATE_TYPED_TEST_CASE_P().
279
280template <typename T>
281struct TypeList {
282  typedef Types1<T> type;
283};
284
285
286$range i 1..n
287template <$for i, [[typename T$i]]>
288struct TypeList<Types<$for i, [[T$i]]> > {
289  typedef typename Types<$for i, [[T$i]]>::type type;
290};
291
292#endif  // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
293
294}  // namespace internal
295}  // namespace testing
296
297#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
trunk/3rdparty/googletest/googletest/m4/acx_pthread.m4
r0r249096
1# This was retrieved from
2#    http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?revision=1277&root=avahi
3# See also (perhaps for new versions?)
4#    http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?root=avahi
5#
6# We've rewritten the inconsistency check code (from avahi), to work
7# more broadly.  In particular, it no longer assumes ld accepts -zdefs.
8# This caused a restructing of the code, but the functionality has only
9# changed a little.
10
11dnl @synopsis ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
12dnl
13dnl @summary figure out how to build C programs using POSIX threads
14dnl
15dnl This macro figures out how to build C programs using POSIX threads.
16dnl It sets the PTHREAD_LIBS output variable to the threads library and
17dnl linker flags, and the PTHREAD_CFLAGS output variable to any special
18dnl C compiler flags that are needed. (The user can also force certain
19dnl compiler flags/libs to be tested by setting these environment
20dnl variables.)
21dnl
22dnl Also sets PTHREAD_CC to any special C compiler that is needed for
23dnl multi-threaded programs (defaults to the value of CC otherwise).
24dnl (This is necessary on AIX to use the special cc_r compiler alias.)
25dnl
26dnl NOTE: You are assumed to not only compile your program with these
27dnl flags, but also link it with them as well. e.g. you should link
28dnl with $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS
29dnl $LIBS
30dnl
31dnl If you are only building threads programs, you may wish to use
32dnl these variables in your default LIBS, CFLAGS, and CC:
33dnl
34dnl        LIBS="$PTHREAD_LIBS $LIBS"
35dnl        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
36dnl        CC="$PTHREAD_CC"
37dnl
38dnl In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute
39dnl constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to
40dnl that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
41dnl
42dnl ACTION-IF-FOUND is a list of shell commands to run if a threads
43dnl library is found, and ACTION-IF-NOT-FOUND is a list of commands to
44dnl run it if it is not found. If ACTION-IF-FOUND is not specified, the
45dnl default action will define HAVE_PTHREAD.
46dnl
47dnl Please let the authors know if this macro fails on any platform, or
48dnl if you have any other suggestions or comments. This macro was based
49dnl on work by SGJ on autoconf scripts for FFTW (www.fftw.org) (with
50dnl help from M. Frigo), as well as ac_pthread and hb_pthread macros
51dnl posted by Alejandro Forero Cuervo to the autoconf macro repository.
52dnl We are also grateful for the helpful feedback of numerous users.
53dnl
54dnl @category InstalledPackages
55dnl @author Steven G. Johnson <stevenj@alum.mit.edu>
56dnl @version 2006-05-29
57dnl @license GPLWithACException
58dnl
59dnl Checks for GCC shared/pthread inconsistency based on work by
60dnl Marcin Owsiany <marcin@owsiany.pl>
61
62
63AC_DEFUN([ACX_PTHREAD], [
64AC_REQUIRE([AC_CANONICAL_HOST])
65AC_LANG_SAVE
66AC_LANG_C
67acx_pthread_ok=no
68
69# We used to check for pthread.h first, but this fails if pthread.h
70# requires special compiler flags (e.g. on True64 or Sequent).
71# It gets checked for in the link test anyway.
72
73# First of all, check if the user has set any of the PTHREAD_LIBS,
74# etcetera environment variables, and if threads linking works using
75# them:
76if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
77        save_CFLAGS="$CFLAGS"
78        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
79        save_LIBS="$LIBS"
80        LIBS="$PTHREAD_LIBS $LIBS"
81        AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
82        AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes)
83        AC_MSG_RESULT($acx_pthread_ok)
84        if test x"$acx_pthread_ok" = xno; then
85                PTHREAD_LIBS=""
86                PTHREAD_CFLAGS=""
87        fi
88        LIBS="$save_LIBS"
89        CFLAGS="$save_CFLAGS"
90fi
91
92# We must check for the threads library under a number of different
93# names; the ordering is very important because some systems
94# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
95# libraries is broken (non-POSIX).
96
97# Create a list of thread flags to try.  Items starting with a "-" are
98# C compiler flags, and other items are library names, except for "none"
99# which indicates that we try without any flags at all, and "pthread-config"
100# which is a program returning the flags for the Pth emulation library.
101
102acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
103
104# The ordering *is* (sometimes) important.  Some notes on the
105# individual items follow:
106
107# pthreads: AIX (must check this before -lpthread)
108# none: in case threads are in libc; should be tried before -Kthread and
109#       other compiler flags to prevent continual compiler warnings
110# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
111# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
112# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
113# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
114# -pthreads: Solaris/gcc
115# -mthreads: Mingw32/gcc, Lynx/gcc
116# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
117#      doesn't hurt to check since this sometimes defines pthreads too;
118#      also defines -D_REENTRANT)
119#      ... -mt is also the pthreads flag for HP/aCC
120# pthread: Linux, etcetera
121# --thread-safe: KAI C++
122# pthread-config: use pthread-config program (for GNU Pth library)
123
124case "${host_cpu}-${host_os}" in
125        *solaris*)
126
127        # On Solaris (at least, for some versions), libc contains stubbed
128        # (non-functional) versions of the pthreads routines, so link-based
129        # tests will erroneously succeed.  (We need to link with -pthreads/-mt/
130        # -lpthread.)  (The stubs are missing pthread_cleanup_push, or rather
131        # a function called by this macro, so we could check for that, but
132        # who knows whether they'll stub that too in a future libc.)  So,
133        # we'll just look for -pthreads and -lpthread first:
134
135        acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags"
136        ;;
137esac
138
139if test x"$acx_pthread_ok" = xno; then
140for flag in $acx_pthread_flags; do
141
142        case $flag in
143                none)
144                AC_MSG_CHECKING([whether pthreads work without any flags])
145                ;;
146
147                -*)
148                AC_MSG_CHECKING([whether pthreads work with $flag])
149                PTHREAD_CFLAGS="$flag"
150                ;;
151
152      pthread-config)
153      AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no)
154      if test x"$acx_pthread_config" = xno; then continue; fi
155      PTHREAD_CFLAGS="`pthread-config --cflags`"
156      PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
157      ;;
158
159                *)
160                AC_MSG_CHECKING([for the pthreads library -l$flag])
161                PTHREAD_LIBS="-l$flag"
162                ;;
163        esac
164
165        save_LIBS="$LIBS"
166        save_CFLAGS="$CFLAGS"
167        LIBS="$PTHREAD_LIBS $LIBS"
168        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
169
170        # Check for various functions.  We must include pthread.h,
171        # since some functions may be macros.  (On the Sequent, we
172        # need a special flag -Kthread to make this header compile.)
173        # We check for pthread_join because it is in -lpthread on IRIX
174        # while pthread_create is in libc.  We check for pthread_attr_init
175        # due to DEC craziness with -lpthreads.  We check for
176        # pthread_cleanup_push because it is one of the few pthread
177        # functions on Solaris that doesn't have a non-functional libc stub.
178        # We try pthread_create on general principles.
179        AC_TRY_LINK([#include <pthread.h>],
180                    [pthread_t th; pthread_join(th, 0);
181                     pthread_attr_init(0); pthread_cleanup_push(0, 0);
182                     pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
183                    [acx_pthread_ok=yes])
184
185        LIBS="$save_LIBS"
186        CFLAGS="$save_CFLAGS"
187
188        AC_MSG_RESULT($acx_pthread_ok)
189        if test "x$acx_pthread_ok" = xyes; then
190                break;
191        fi
192
193        PTHREAD_LIBS=""
194        PTHREAD_CFLAGS=""
195done
196fi
197
198# Various other checks:
199if test "x$acx_pthread_ok" = xyes; then
200        save_LIBS="$LIBS"
201        LIBS="$PTHREAD_LIBS $LIBS"
202        save_CFLAGS="$CFLAGS"
203        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
204
205        # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
206   AC_MSG_CHECKING([for joinable pthread attribute])
207   attr_name=unknown
208   for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
209       AC_TRY_LINK([#include <pthread.h>], [int attr=$attr; return attr;],
210                        [attr_name=$attr; break])
211   done
212        AC_MSG_RESULT($attr_name)
213        if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
214            AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
215                               [Define to necessary symbol if this constant
216                                uses a non-standard name on your system.])
217        fi
218
219        AC_MSG_CHECKING([if more special flags are required for pthreads])
220        flag=no
221        case "${host_cpu}-${host_os}" in
222            *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";;
223            *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";;
224        esac
225        AC_MSG_RESULT(${flag})
226        if test "x$flag" != xno; then
227            PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
228        fi
229
230        LIBS="$save_LIBS"
231        CFLAGS="$save_CFLAGS"
232        # More AIX lossage: must compile with xlc_r or cc_r
233   if test x"$GCC" != xyes; then
234          AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC})
235        else
236          PTHREAD_CC=$CC
237   fi
238
239   # The next part tries to detect GCC inconsistency with -shared on some
240   # architectures and systems. The problem is that in certain
241   # configurations, when -shared is specified, GCC "forgets" to
242   # internally use various flags which are still necessary.
243   
244   #
245   # Prepare the flags
246   #
247   save_CFLAGS="$CFLAGS"
248   save_LIBS="$LIBS"
249   save_CC="$CC"
250   
251   # Try with the flags determined by the earlier checks.
252   #
253   # -Wl,-z,defs forces link-time symbol resolution, so that the
254   # linking checks with -shared actually have any value
255   #
256   # FIXME: -fPIC is required for -shared on many architectures,
257   # so we specify it here, but the right way would probably be to
258   # properly detect whether it is actually required.
259   CFLAGS="-shared -fPIC -Wl,-z,defs $CFLAGS $PTHREAD_CFLAGS"
260   LIBS="$PTHREAD_LIBS $LIBS"
261   CC="$PTHREAD_CC"
262   
263   # In order not to create several levels of indentation, we test
264   # the value of "$done" until we find the cure or run out of ideas.
265   done="no"
266   
267   # First, make sure the CFLAGS we added are actually accepted by our
268   # compiler.  If not (and OS X's ld, for instance, does not accept -z),
269   # then we can't do this test.
270   if test x"$done" = xno; then
271      AC_MSG_CHECKING([whether to check for GCC pthread/shared inconsistencies])
272      AC_TRY_LINK(,, , [done=yes])
273   
274      if test "x$done" = xyes ; then
275         AC_MSG_RESULT([no])
276      else
277         AC_MSG_RESULT([yes])
278      fi
279   fi
280   
281   if test x"$done" = xno; then
282      AC_MSG_CHECKING([whether -pthread is sufficient with -shared])
283      AC_TRY_LINK([#include <pthread.h>],
284         [pthread_t th; pthread_join(th, 0);
285         pthread_attr_init(0); pthread_cleanup_push(0, 0);
286         pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
287         [done=yes])
288     
289      if test "x$done" = xyes; then
290         AC_MSG_RESULT([yes])
291      else
292         AC_MSG_RESULT([no])
293      fi
294   fi
295   
296   #
297   # Linux gcc on some architectures such as mips/mipsel forgets
298   # about -lpthread
299   #
300   if test x"$done" = xno; then
301      AC_MSG_CHECKING([whether -lpthread fixes that])
302      LIBS="-lpthread $PTHREAD_LIBS $save_LIBS"
303      AC_TRY_LINK([#include <pthread.h>],
304         [pthread_t th; pthread_join(th, 0);
305         pthread_attr_init(0); pthread_cleanup_push(0, 0);
306         pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
307         [done=yes])
308   
309      if test "x$done" = xyes; then
310         AC_MSG_RESULT([yes])
311         PTHREAD_LIBS="-lpthread $PTHREAD_LIBS"
312      else
313         AC_MSG_RESULT([no])
314      fi
315   fi
316   #
317   # FreeBSD 4.10 gcc forgets to use -lc_r instead of -lc
318   #
319   if test x"$done" = xno; then
320      AC_MSG_CHECKING([whether -lc_r fixes that])
321      LIBS="-lc_r $PTHREAD_LIBS $save_LIBS"
322      AC_TRY_LINK([#include <pthread.h>],
323          [pthread_t th; pthread_join(th, 0);
324           pthread_attr_init(0); pthread_cleanup_push(0, 0);
325           pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
326          [done=yes])
327   
328      if test "x$done" = xyes; then
329         AC_MSG_RESULT([yes])
330         PTHREAD_LIBS="-lc_r $PTHREAD_LIBS"
331      else
332         AC_MSG_RESULT([no])
333      fi
334   fi
335   if test x"$done" = xno; then
336      # OK, we have run out of ideas
337      AC_MSG_WARN([Impossible to determine how to use pthreads with shared libraries])
338   
339      # so it's not safe to assume that we may use pthreads
340      acx_pthread_ok=no
341   fi
342   
343   CFLAGS="$save_CFLAGS"
344   LIBS="$save_LIBS"
345   CC="$save_CC"
346else
347        PTHREAD_CC="$CC"
348fi
349
350AC_SUBST(PTHREAD_LIBS)
351AC_SUBST(PTHREAD_CFLAGS)
352AC_SUBST(PTHREAD_CC)
353
354# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
355if test x"$acx_pthread_ok" = xyes; then
356        ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
357        :
358else
359        acx_pthread_ok=no
360        $2
361fi
362AC_LANG_RESTORE
363])dnl ACX_PTHREAD
trunk/3rdparty/googletest/googletest/m4/gtest.m4
r0r249096
1dnl GTEST_LIB_CHECK([minimum version [,
2dnl                  action if found [,action if not found]]])
3dnl
4dnl Check for the presence of the Google Test library, optionally at a minimum
5dnl version, and indicate a viable version with the HAVE_GTEST flag. It defines
6dnl standard variables for substitution including GTEST_CPPFLAGS,
7dnl GTEST_CXXFLAGS, GTEST_LDFLAGS, and GTEST_LIBS. It also defines
8dnl GTEST_VERSION as the version of Google Test found. Finally, it provides
9dnl optional custom action slots in the event GTEST is found or not.
10AC_DEFUN([GTEST_LIB_CHECK],
11[
12dnl Provide a flag to enable or disable Google Test usage.
13AC_ARG_ENABLE([gtest],
14  [AS_HELP_STRING([--enable-gtest],
15                  [Enable tests using the Google C++ Testing Framework.
16                  (Default is enabled.)])],
17  [],
18  [enable_gtest=])
19AC_ARG_VAR([GTEST_CONFIG],
20           [The exact path of Google Test's 'gtest-config' script.])
21AC_ARG_VAR([GTEST_CPPFLAGS],
22           [C-like preprocessor flags for Google Test.])
23AC_ARG_VAR([GTEST_CXXFLAGS],
24           [C++ compile flags for Google Test.])
25AC_ARG_VAR([GTEST_LDFLAGS],
26           [Linker path and option flags for Google Test.])
27AC_ARG_VAR([GTEST_LIBS],
28           [Library linking flags for Google Test.])
29AC_ARG_VAR([GTEST_VERSION],
30           [The version of Google Test available.])
31HAVE_GTEST="no"
32AS_IF([test "x${enable_gtest}" != "xno"],
33  [AC_MSG_CHECKING([for 'gtest-config'])
34   AS_IF([test "x${enable_gtest}" != "xyes"],
35     [AS_IF([test -x "${enable_gtest}/scripts/gtest-config"],
36        [GTEST_CONFIG="${enable_gtest}/scripts/gtest-config"],
37        [GTEST_CONFIG="${enable_gtest}/bin/gtest-config"])
38      AS_IF([test -x "${GTEST_CONFIG}"], [],
39        [AC_MSG_RESULT([no])
40         AC_MSG_ERROR([dnl
41Unable to locate either a built or installed Google Test.
42The specific location '${enable_gtest}' was provided for a built or installed
43Google Test, but no 'gtest-config' script could be found at this location.])
44         ])],
45     [AC_PATH_PROG([GTEST_CONFIG], [gtest-config])])
46   AS_IF([test -x "${GTEST_CONFIG}"],
47     [AC_MSG_RESULT([${GTEST_CONFIG}])
48      m4_ifval([$1],
49        [_gtest_min_version="--min-version=$1"
50         AC_MSG_CHECKING([for Google Test at least version >= $1])],
51        [_gtest_min_version="--min-version=0"
52         AC_MSG_CHECKING([for Google Test])])
53      AS_IF([${GTEST_CONFIG} ${_gtest_min_version}],
54        [AC_MSG_RESULT([yes])
55         HAVE_GTEST='yes'],
56        [AC_MSG_RESULT([no])])],
57     [AC_MSG_RESULT([no])])
58   AS_IF([test "x${HAVE_GTEST}" = "xyes"],
59     [GTEST_CPPFLAGS=`${GTEST_CONFIG} --cppflags`
60      GTEST_CXXFLAGS=`${GTEST_CONFIG} --cxxflags`
61      GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags`
62      GTEST_LIBS=`${GTEST_CONFIG} --libs`
63      GTEST_VERSION=`${GTEST_CONFIG} --version`
64      AC_DEFINE([HAVE_GTEST],[1],[Defined when Google Test is available.])],
65     [AS_IF([test "x${enable_gtest}" = "xyes"],
66        [AC_MSG_ERROR([dnl
67Google Test was enabled, but no viable version could be found.])
68         ])])])
69AC_SUBST([HAVE_GTEST])
70AM_CONDITIONAL([HAVE_GTEST],[test "x$HAVE_GTEST" = "xyes"])
71AS_IF([test "x$HAVE_GTEST" = "xyes"],
72  [m4_ifval([$2], [$2])],
73  [m4_ifval([$3], [$3])])
74])
trunk/3rdparty/googletest/googletest/make/Makefile
r0r249096
1# A sample Makefile for building Google Test and using it in user
2# tests.  Please tweak it to suit your environment and project.  You
3# may want to move it to your project's root directory.
4#
5# SYNOPSIS:
6#
7#   make [all]  - makes everything.
8#   make TARGET - makes the given target.
9#   make clean  - removes all files generated by make.
10
11# Please tweak the following variable definitions as needed by your
12# project, except GTEST_HEADERS, which you can use in your own targets
13# but shouldn't modify.
14
15# Points to the root of Google Test, relative to where this file is.
16# Remember to tweak this if you move this file.
17GTEST_DIR = ..
18
19# Where to find user code.
20USER_DIR = ../samples
21
22# Flags passed to the preprocessor.
23# Set Google Test's header directory as a system directory, such that
24# the compiler doesn't generate warnings in Google Test headers.
25CPPFLAGS += -isystem $(GTEST_DIR)/include
26
27# Flags passed to the C++ compiler.
28CXXFLAGS += -g -Wall -Wextra -pthread
29
30# All tests produced by this Makefile.  Remember to add new tests you
31# created to the list.
32TESTS = sample1_unittest
33
34# All Google Test headers.  Usually you shouldn't change this
35# definition.
36GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \
37                $(GTEST_DIR)/include/gtest/internal/*.h
38
39# House-keeping build targets.
40
41all : $(TESTS)
42
43clean :
44   rm -f $(TESTS) gtest.a gtest_main.a *.o
45
46# Builds gtest.a and gtest_main.a.
47
48# Usually you shouldn't tweak such internal variables, indicated by a
49# trailing _.
50GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)
51
52# For simplicity and to avoid depending on Google Test's
53# implementation details, the dependencies specified below are
54# conservative and not optimized.  This is fine as Google Test
55# compiles fast and for ordinary users its source rarely changes.
56gtest-all.o : $(GTEST_SRCS_)
57   $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
58            $(GTEST_DIR)/src/gtest-all.cc
59
60gtest_main.o : $(GTEST_SRCS_)
61   $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
62            $(GTEST_DIR)/src/gtest_main.cc
63
64gtest.a : gtest-all.o
65   $(AR) $(ARFLAGS) $@ $^
66
67gtest_main.a : gtest-all.o gtest_main.o
68   $(AR) $(ARFLAGS) $@ $^
69
70# Builds a sample test.  A test should link with either gtest.a or
71# gtest_main.a, depending on whether it defines its own main()
72# function.
73
74sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS)
75   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc
76
77sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \
78                     $(USER_DIR)/sample1.h $(GTEST_HEADERS)
79   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc
80
81sample1_unittest : sample1.o sample1_unittest.o gtest_main.a
82   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@
trunk/3rdparty/googletest/googletest/msvc/gtest-md.sln
r0r249096
1Microsoft Visual Studio Solution File, Format Version 8.00
2Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest-md", "gtest-md.vcproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}"
3   ProjectSection(ProjectDependencies) = postProject
4   EndProjectSection
5EndProject
6Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main-md", "gtest_main-md.vcproj", "{3AF54C8A-10BF-4332-9147-F68ED9862033}"
7   ProjectSection(ProjectDependencies) = postProject
8   EndProjectSection
9EndProject
10Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test-md", "gtest_prod_test-md.vcproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}"
11   ProjectSection(ProjectDependencies) = postProject
12   EndProjectSection
13EndProject
14Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest-md", "gtest_unittest-md.vcproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}"
15   ProjectSection(ProjectDependencies) = postProject
16   EndProjectSection
17EndProject
18Global
19   GlobalSection(SolutionConfiguration) = preSolution
20      Debug = Debug
21      Release = Release
22   EndGlobalSection
23   GlobalSection(ProjectConfiguration) = postSolution
24      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug.ActiveCfg = Debug|Win32
25      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug.Build.0 = Debug|Win32
26      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release.ActiveCfg = Release|Win32
27      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release.Build.0 = Release|Win32
28      {3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug.ActiveCfg = Debug|Win32
29      {3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug.Build.0 = Debug|Win32
30      {3AF54C8A-10BF-4332-9147-F68ED9862033}.Release.ActiveCfg = Release|Win32
31      {3AF54C8A-10BF-4332-9147-F68ED9862033}.Release.Build.0 = Release|Win32
32      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug.ActiveCfg = Debug|Win32
33      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug.Build.0 = Debug|Win32
34      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release.ActiveCfg = Release|Win32
35      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release.Build.0 = Release|Win32
36      {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug.ActiveCfg = Debug|Win32
37      {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug.Build.0 = Debug|Win32
38      {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release.ActiveCfg = Release|Win32
39      {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release.Build.0 = Release|Win32
40   EndGlobalSection
41   GlobalSection(ExtensibilityGlobals) = postSolution
42   EndGlobalSection
43   GlobalSection(ExtensibilityAddIns) = postSolution
44   EndGlobalSection
45EndGlobal
trunk/3rdparty/googletest/googletest/msvc/gtest-md.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest-md"
6   ProjectGUID="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="4"
18         CharacterSet="2"
19         ReferencesPath="">
20         <Tool
21            Name="VCCLCompilerTool"
22            Optimization="0"
23            PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
24            MinimalRebuild="TRUE"
25            BasicRuntimeChecks="3"
26            RuntimeLibrary="3"
27            UsePrecompiledHeader="0"
28            WarningLevel="3"
29            Detect64BitPortabilityProblems="FALSE"
30            DebugInformationFormat="4"/>
31         <Tool
32            Name="VCCustomBuildTool"/>
33         <Tool
34            Name="VCLibrarianTool"
35            OutputFile="$(OutDir)/gtestd.lib"/>
36         <Tool
37            Name="VCMIDLTool"/>
38         <Tool
39            Name="VCPostBuildEventTool"/>
40         <Tool
41            Name="VCPreBuildEventTool"/>
42         <Tool
43            Name="VCPreLinkEventTool"/>
44         <Tool
45            Name="VCResourceCompilerTool"/>
46         <Tool
47            Name="VCWebServiceProxyGeneratorTool"/>
48         <Tool
49            Name="VCXMLDataGeneratorTool"/>
50         <Tool
51            Name="VCManagedWrapperGeneratorTool"/>
52         <Tool
53            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
54      </Configuration>
55      <Configuration
56         Name="Release|Win32"
57         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
58         IntermediateDirectory="$(OutDir)/$(ProjectName)"
59         ConfigurationType="4"
60         CharacterSet="2"
61         ReferencesPath="&quot;..\include&quot;;&quot;..&quot;">
62         <Tool
63            Name="VCCLCompilerTool"
64            PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
65            RuntimeLibrary="2"
66            UsePrecompiledHeader="0"
67            WarningLevel="3"
68            Detect64BitPortabilityProblems="FALSE"
69            DebugInformationFormat="3"/>
70         <Tool
71            Name="VCCustomBuildTool"/>
72         <Tool
73            Name="VCLibrarianTool"
74            OutputFile="$(OutDir)/gtest.lib"/>
75         <Tool
76            Name="VCMIDLTool"/>
77         <Tool
78            Name="VCPostBuildEventTool"/>
79         <Tool
80            Name="VCPreBuildEventTool"/>
81         <Tool
82            Name="VCPreLinkEventTool"/>
83         <Tool
84            Name="VCResourceCompilerTool"/>
85         <Tool
86            Name="VCWebServiceProxyGeneratorTool"/>
87         <Tool
88            Name="VCXMLDataGeneratorTool"/>
89         <Tool
90            Name="VCManagedWrapperGeneratorTool"/>
91         <Tool
92            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
93      </Configuration>
94   </Configurations>
95   <References>
96   </References>
97   <Files>
98      <Filter
99         Name="Source Files"
100         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
101         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
102         <File
103            RelativePath="..\src\gtest-all.cc">
104            <FileConfiguration
105               Name="Debug|Win32">
106               <Tool
107                  Name="VCCLCompilerTool"
108                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
109            </FileConfiguration>
110            <FileConfiguration
111               Name="Release|Win32">
112               <Tool
113                  Name="VCCLCompilerTool"
114                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
115            </FileConfiguration>
116         </File>
117      </Filter>
118      <Filter
119         Name="Header Files"
120         Filter="h;hpp;hxx;hm;inl;inc;xsd"
121         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
122      </Filter>
123   </Files>
124   <Globals>
125   </Globals>
126</VisualStudioProject>
trunk/3rdparty/googletest/googletest/msvc/gtest.sln
r0r249096
1Microsoft Visual Studio Solution File, Format Version 8.00
2Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest", "gtest.vcproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}"
3   ProjectSection(ProjectDependencies) = postProject
4   EndProjectSection
5EndProject
6Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main", "gtest_main.vcproj", "{3AF54C8A-10BF-4332-9147-F68ED9862032}"
7   ProjectSection(ProjectDependencies) = postProject
8   EndProjectSection
9EndProject
10Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest", "gtest_unittest.vcproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}"
11   ProjectSection(ProjectDependencies) = postProject
12   EndProjectSection
13EndProject
14Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test", "gtest_prod_test.vcproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}"
15   ProjectSection(ProjectDependencies) = postProject
16   EndProjectSection
17EndProject
18Global
19   GlobalSection(SolutionConfiguration) = preSolution
20      Debug = Debug
21      Release = Release
22   EndGlobalSection
23   GlobalSection(ProjectConfiguration) = postSolution
24      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug.ActiveCfg = Debug|Win32
25      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug.Build.0 = Debug|Win32
26      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release.ActiveCfg = Release|Win32
27      {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release.Build.0 = Release|Win32
28      {3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug.ActiveCfg = Debug|Win32
29      {3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug.Build.0 = Debug|Win32
30      {3AF54C8A-10BF-4332-9147-F68ED9862032}.Release.ActiveCfg = Release|Win32
31      {3AF54C8A-10BF-4332-9147-F68ED9862032}.Release.Build.0 = Release|Win32
32      {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug.ActiveCfg = Debug|Win32
33      {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug.Build.0 = Debug|Win32
34      {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release.ActiveCfg = Release|Win32
35      {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release.Build.0 = Release|Win32
36      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug.ActiveCfg = Debug|Win32
37      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug.Build.0 = Debug|Win32
38      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release.ActiveCfg = Release|Win32
39      {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release.Build.0 = Release|Win32
40   EndGlobalSection
41   GlobalSection(ExtensibilityGlobals) = postSolution
42   EndGlobalSection
43   GlobalSection(ExtensibilityAddIns) = postSolution
44   EndGlobalSection
45EndGlobal
trunk/3rdparty/googletest/googletest/msvc/gtest.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest"
6   ProjectGUID="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="4"
18         CharacterSet="2"
19         ReferencesPath="">
20         <Tool
21            Name="VCCLCompilerTool"
22            Optimization="0"
23            PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
24            MinimalRebuild="TRUE"
25            BasicRuntimeChecks="3"
26            RuntimeLibrary="5"
27            UsePrecompiledHeader="0"
28            WarningLevel="3"
29            Detect64BitPortabilityProblems="FALSE"
30            DebugInformationFormat="4"/>
31         <Tool
32            Name="VCCustomBuildTool"/>
33         <Tool
34            Name="VCLibrarianTool"
35            OutputFile="$(OutDir)/gtestd.lib"/>
36         <Tool
37            Name="VCMIDLTool"/>
38         <Tool
39            Name="VCPostBuildEventTool"/>
40         <Tool
41            Name="VCPreBuildEventTool"/>
42         <Tool
43            Name="VCPreLinkEventTool"/>
44         <Tool
45            Name="VCResourceCompilerTool"/>
46         <Tool
47            Name="VCWebServiceProxyGeneratorTool"/>
48         <Tool
49            Name="VCXMLDataGeneratorTool"/>
50         <Tool
51            Name="VCManagedWrapperGeneratorTool"/>
52         <Tool
53            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
54      </Configuration>
55      <Configuration
56         Name="Release|Win32"
57         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
58         IntermediateDirectory="$(OutDir)/$(ProjectName)"
59         ConfigurationType="4"
60         CharacterSet="2"
61         ReferencesPath="&quot;..\include&quot;;&quot;..&quot;">
62         <Tool
63            Name="VCCLCompilerTool"
64            PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
65            RuntimeLibrary="4"
66            UsePrecompiledHeader="0"
67            WarningLevel="3"
68            Detect64BitPortabilityProblems="FALSE"
69            DebugInformationFormat="3"/>
70         <Tool
71            Name="VCCustomBuildTool"/>
72         <Tool
73            Name="VCLibrarianTool"
74            OutputFile="$(OutDir)/gtest.lib"/>
75         <Tool
76            Name="VCMIDLTool"/>
77         <Tool
78            Name="VCPostBuildEventTool"/>
79         <Tool
80            Name="VCPreBuildEventTool"/>
81         <Tool
82            Name="VCPreLinkEventTool"/>
83         <Tool
84            Name="VCResourceCompilerTool"/>
85         <Tool
86            Name="VCWebServiceProxyGeneratorTool"/>
87         <Tool
88            Name="VCXMLDataGeneratorTool"/>
89         <Tool
90            Name="VCManagedWrapperGeneratorTool"/>
91         <Tool
92            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
93      </Configuration>
94   </Configurations>
95   <References>
96   </References>
97   <Files>
98      <Filter
99         Name="Source Files"
100         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
101         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
102         <File
103            RelativePath="..\src\gtest-all.cc">
104            <FileConfiguration
105               Name="Debug|Win32">
106               <Tool
107                  Name="VCCLCompilerTool"
108                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
109            </FileConfiguration>
110            <FileConfiguration
111               Name="Release|Win32">
112               <Tool
113                  Name="VCCLCompilerTool"
114                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
115            </FileConfiguration>
116         </File>
117      </Filter>
118      <Filter
119         Name="Header Files"
120         Filter="h;hpp;hxx;hm;inl;inc;xsd"
121         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
122      </Filter>
123   </Files>
124   <Globals>
125   </Globals>
126</VisualStudioProject>
trunk/3rdparty/googletest/googletest/msvc/gtest_main-md.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest_main-md"
6   ProjectGUID="{3AF54C8A-10BF-4332-9147-F68ED9862033}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="4"
18         CharacterSet="2"
19         ReferencesPath="">
20         <Tool
21            Name="VCCLCompilerTool"
22            Optimization="0"
23            PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
24            MinimalRebuild="TRUE"
25            BasicRuntimeChecks="3"
26            RuntimeLibrary="3"
27            UsePrecompiledHeader="0"
28            WarningLevel="3"
29            Detect64BitPortabilityProblems="FALSE"
30            DebugInformationFormat="4"/>
31         <Tool
32            Name="VCCustomBuildTool"/>
33         <Tool
34            Name="VCLibrarianTool"
35            OutputFile="$(OutDir)/$(ProjectName)d.lib"/>
36         <Tool
37            Name="VCMIDLTool"/>
38         <Tool
39            Name="VCPostBuildEventTool"/>
40         <Tool
41            Name="VCPreBuildEventTool"/>
42         <Tool
43            Name="VCPreLinkEventTool"/>
44         <Tool
45            Name="VCResourceCompilerTool"/>
46         <Tool
47            Name="VCWebServiceProxyGeneratorTool"/>
48         <Tool
49            Name="VCXMLDataGeneratorTool"/>
50         <Tool
51            Name="VCManagedWrapperGeneratorTool"/>
52         <Tool
53            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
54      </Configuration>
55      <Configuration
56         Name="Release|Win32"
57         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
58         IntermediateDirectory="$(OutDir)/$(ProjectName)"
59         ConfigurationType="4"
60         CharacterSet="2"
61         ReferencesPath="&quot;..\include&quot;;&quot;..&quot;">
62         <Tool
63            Name="VCCLCompilerTool"
64            PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
65            RuntimeLibrary="2"
66            UsePrecompiledHeader="0"
67            WarningLevel="3"
68            Detect64BitPortabilityProblems="FALSE"
69            DebugInformationFormat="3"/>
70         <Tool
71            Name="VCCustomBuildTool"/>
72         <Tool
73            Name="VCLibrarianTool"
74            OutputFile="$(OutDir)/$(ProjectName).lib"/>
75         <Tool
76            Name="VCMIDLTool"/>
77         <Tool
78            Name="VCPostBuildEventTool"/>
79         <Tool
80            Name="VCPreBuildEventTool"/>
81         <Tool
82            Name="VCPreLinkEventTool"/>
83         <Tool
84            Name="VCResourceCompilerTool"/>
85         <Tool
86            Name="VCWebServiceProxyGeneratorTool"/>
87         <Tool
88            Name="VCXMLDataGeneratorTool"/>
89         <Tool
90            Name="VCManagedWrapperGeneratorTool"/>
91         <Tool
92            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
93      </Configuration>
94   </Configurations>
95   <References>
96      <ProjectReference
97         ReferencedProjectIdentifier="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}"
98         Name="gtest-md"/>
99   </References>
100   <Files>
101      <Filter
102         Name="Source Files"
103         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
104         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
105         <File
106            RelativePath="..\src\gtest_main.cc">
107            <FileConfiguration
108               Name="Debug|Win32">
109               <Tool
110                  Name="VCCLCompilerTool"
111                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
112            </FileConfiguration>
113            <FileConfiguration
114               Name="Release|Win32">
115               <Tool
116                  Name="VCCLCompilerTool"
117                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
118            </FileConfiguration>
119         </File>
120      </Filter>
121      <Filter
122         Name="Header Files"
123         Filter="h;hpp;hxx;hm;inl;inc;xsd"
124         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
125      </Filter>
126   </Files>
127   <Globals>
128   </Globals>
129</VisualStudioProject>
trunk/3rdparty/googletest/googletest/msvc/gtest_main.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest_main"
6   ProjectGUID="{3AF54C8A-10BF-4332-9147-F68ED9862032}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="4"
18         CharacterSet="2"
19         ReferencesPath="">
20         <Tool
21            Name="VCCLCompilerTool"
22            Optimization="0"
23            PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
24            MinimalRebuild="TRUE"
25            BasicRuntimeChecks="3"
26            RuntimeLibrary="5"
27            UsePrecompiledHeader="0"
28            WarningLevel="3"
29            Detect64BitPortabilityProblems="FALSE"
30            DebugInformationFormat="4"/>
31         <Tool
32            Name="VCCustomBuildTool"/>
33         <Tool
34            Name="VCLibrarianTool"
35            OutputFile="$(OutDir)/$(ProjectName)d.lib"/>
36         <Tool
37            Name="VCMIDLTool"/>
38         <Tool
39            Name="VCPostBuildEventTool"/>
40         <Tool
41            Name="VCPreBuildEventTool"/>
42         <Tool
43            Name="VCPreLinkEventTool"/>
44         <Tool
45            Name="VCResourceCompilerTool"/>
46         <Tool
47            Name="VCWebServiceProxyGeneratorTool"/>
48         <Tool
49            Name="VCXMLDataGeneratorTool"/>
50         <Tool
51            Name="VCManagedWrapperGeneratorTool"/>
52         <Tool
53            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
54      </Configuration>
55      <Configuration
56         Name="Release|Win32"
57         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
58         IntermediateDirectory="$(OutDir)/$(ProjectName)"
59         ConfigurationType="4"
60         CharacterSet="2"
61         ReferencesPath="&quot;..\include&quot;;&quot;..&quot;">
62         <Tool
63            Name="VCCLCompilerTool"
64            PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
65            RuntimeLibrary="4"
66            UsePrecompiledHeader="0"
67            WarningLevel="3"
68            Detect64BitPortabilityProblems="FALSE"
69            DebugInformationFormat="3"/>
70         <Tool
71            Name="VCCustomBuildTool"/>
72         <Tool
73            Name="VCLibrarianTool"
74            OutputFile="$(OutDir)/$(ProjectName).lib"/>
75         <Tool
76            Name="VCMIDLTool"/>
77         <Tool
78            Name="VCPostBuildEventTool"/>
79         <Tool
80            Name="VCPreBuildEventTool"/>
81         <Tool
82            Name="VCPreLinkEventTool"/>
83         <Tool
84            Name="VCResourceCompilerTool"/>
85         <Tool
86            Name="VCWebServiceProxyGeneratorTool"/>
87         <Tool
88            Name="VCXMLDataGeneratorTool"/>
89         <Tool
90            Name="VCManagedWrapperGeneratorTool"/>
91         <Tool
92            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
93      </Configuration>
94   </Configurations>
95   <References>
96      <ProjectReference
97         ReferencedProjectIdentifier="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}"
98         Name="gtest"/>
99   </References>
100   <Files>
101      <Filter
102         Name="Source Files"
103         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
104         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
105         <File
106            RelativePath="..\src\gtest_main.cc">
107            <FileConfiguration
108               Name="Debug|Win32">
109               <Tool
110                  Name="VCCLCompilerTool"
111                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
112            </FileConfiguration>
113            <FileConfiguration
114               Name="Release|Win32">
115               <Tool
116                  Name="VCCLCompilerTool"
117                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"/>
118            </FileConfiguration>
119         </File>
120      </Filter>
121      <Filter
122         Name="Header Files"
123         Filter="h;hpp;hxx;hm;inl;inc;xsd"
124         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
125      </Filter>
126   </Files>
127   <Globals>
128   </Globals>
129</VisualStudioProject>
trunk/3rdparty/googletest/googletest/msvc/gtest_prod_test-md.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest_prod_test-md"
6   ProjectGUID="{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="1"
18         CharacterSet="2">
19         <Tool
20            Name="VCCLCompilerTool"
21            Optimization="0"
22            PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
23            MinimalRebuild="TRUE"
24            BasicRuntimeChecks="3"
25            RuntimeLibrary="3"
26            UsePrecompiledHeader="3"
27            WarningLevel="3"
28            Detect64BitPortabilityProblems="FALSE"
29            DebugInformationFormat="4"/>
30         <Tool
31            Name="VCCustomBuildTool"/>
32         <Tool
33            Name="VCLinkerTool"
34            OutputFile="$(OutDir)/gtest_prod_test.exe"
35            LinkIncremental="2"
36            GenerateDebugInformation="TRUE"
37            ProgramDatabaseFile="$(OutDir)/gtest_prod_test.pdb"
38            SubSystem="1"
39            TargetMachine="1"/>
40         <Tool
41            Name="VCMIDLTool"/>
42         <Tool
43            Name="VCPostBuildEventTool"/>
44         <Tool
45            Name="VCPreBuildEventTool"/>
46         <Tool
47            Name="VCPreLinkEventTool"/>
48         <Tool
49            Name="VCResourceCompilerTool"/>
50         <Tool
51            Name="VCWebServiceProxyGeneratorTool"/>
52         <Tool
53            Name="VCXMLDataGeneratorTool"/>
54         <Tool
55            Name="VCWebDeploymentTool"/>
56         <Tool
57            Name="VCManagedWrapperGeneratorTool"/>
58         <Tool
59            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
60      </Configuration>
61      <Configuration
62         Name="Release|Win32"
63         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
64         IntermediateDirectory="$(OutDir)/$(ProjectName)"
65         ConfigurationType="1"
66         CharacterSet="2">
67         <Tool
68            Name="VCCLCompilerTool"
69            PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
70            RuntimeLibrary="2"
71            UsePrecompiledHeader="3"
72            WarningLevel="3"
73            Detect64BitPortabilityProblems="FALSE"
74            DebugInformationFormat="3"/>
75         <Tool
76            Name="VCCustomBuildTool"/>
77         <Tool
78            Name="VCLinkerTool"
79            OutputFile="$(OutDir)/gtest_prod_test.exe"
80            LinkIncremental="1"
81            GenerateDebugInformation="TRUE"
82            SubSystem="1"
83            OptimizeReferences="2"
84            EnableCOMDATFolding="2"
85            TargetMachine="1"/>
86         <Tool
87            Name="VCMIDLTool"/>
88         <Tool
89            Name="VCPostBuildEventTool"/>
90         <Tool
91            Name="VCPreBuildEventTool"/>
92         <Tool
93            Name="VCPreLinkEventTool"/>
94         <Tool
95            Name="VCResourceCompilerTool"/>
96         <Tool
97            Name="VCWebServiceProxyGeneratorTool"/>
98         <Tool
99            Name="VCXMLDataGeneratorTool"/>
100         <Tool
101            Name="VCWebDeploymentTool"/>
102         <Tool
103            Name="VCManagedWrapperGeneratorTool"/>
104         <Tool
105            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
106      </Configuration>
107   </Configurations>
108   <References>
109      <ProjectReference
110         ReferencedProjectIdentifier="{3AF54C8A-10BF-4332-9147-F68ED9862033}"
111         Name="gtest_main-md"/>
112   </References>
113   <Files>
114      <Filter
115         Name="Source Files"
116         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
117         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
118         <File
119            RelativePath="..\test\gtest_prod_test.cc">
120            <FileConfiguration
121               Name="Debug|Win32">
122               <Tool
123                  Name="VCCLCompilerTool"
124                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
125                  UsePrecompiledHeader="0"/>
126            </FileConfiguration>
127            <FileConfiguration
128               Name="Release|Win32">
129               <Tool
130                  Name="VCCLCompilerTool"
131                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
132                  UsePrecompiledHeader="0"/>
133            </FileConfiguration>
134         </File>
135         <File
136            RelativePath="..\test\production.cc">
137            <FileConfiguration
138               Name="Debug|Win32">
139               <Tool
140                  Name="VCCLCompilerTool"
141                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
142                  UsePrecompiledHeader="0"/>
143            </FileConfiguration>
144            <FileConfiguration
145               Name="Release|Win32">
146               <Tool
147                  Name="VCCLCompilerTool"
148                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
149                  UsePrecompiledHeader="0"/>
150            </FileConfiguration>
151         </File>
152      </Filter>
153      <Filter
154         Name="Header Files"
155         Filter="h;hpp;hxx;hm;inl;inc;xsd"
156         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
157         <File
158            RelativePath="..\test\production.h">
159         </File>
160      </Filter>
161   </Files>
162   <Globals>
163   </Globals>
164</VisualStudioProject>
trunk/3rdparty/googletest/googletest/msvc/gtest_prod_test.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest_prod_test"
6   ProjectGUID="{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="1"
18         CharacterSet="2">
19         <Tool
20            Name="VCCLCompilerTool"
21            Optimization="0"
22            PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
23            MinimalRebuild="TRUE"
24            BasicRuntimeChecks="3"
25            RuntimeLibrary="5"
26            UsePrecompiledHeader="3"
27            WarningLevel="3"
28            Detect64BitPortabilityProblems="FALSE"
29            DebugInformationFormat="4"/>
30         <Tool
31            Name="VCCustomBuildTool"/>
32         <Tool
33            Name="VCLinkerTool"
34            OutputFile="$(OutDir)/gtest_prod_test.exe"
35            LinkIncremental="2"
36            GenerateDebugInformation="TRUE"
37            ProgramDatabaseFile="$(OutDir)/gtest_prod_test.pdb"
38            SubSystem="1"
39            TargetMachine="1"/>
40         <Tool
41            Name="VCMIDLTool"/>
42         <Tool
43            Name="VCPostBuildEventTool"/>
44         <Tool
45            Name="VCPreBuildEventTool"/>
46         <Tool
47            Name="VCPreLinkEventTool"/>
48         <Tool
49            Name="VCResourceCompilerTool"/>
50         <Tool
51            Name="VCWebServiceProxyGeneratorTool"/>
52         <Tool
53            Name="VCXMLDataGeneratorTool"/>
54         <Tool
55            Name="VCWebDeploymentTool"/>
56         <Tool
57            Name="VCManagedWrapperGeneratorTool"/>
58         <Tool
59            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
60      </Configuration>
61      <Configuration
62         Name="Release|Win32"
63         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
64         IntermediateDirectory="$(OutDir)/$(ProjectName)"
65         ConfigurationType="1"
66         CharacterSet="2">
67         <Tool
68            Name="VCCLCompilerTool"
69            PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
70            RuntimeLibrary="4"
71            UsePrecompiledHeader="3"
72            WarningLevel="3"
73            Detect64BitPortabilityProblems="FALSE"
74            DebugInformationFormat="3"/>
75         <Tool
76            Name="VCCustomBuildTool"/>
77         <Tool
78            Name="VCLinkerTool"
79            OutputFile="$(OutDir)/gtest_prod_test.exe"
80            LinkIncremental="1"
81            GenerateDebugInformation="TRUE"
82            SubSystem="1"
83            OptimizeReferences="2"
84            EnableCOMDATFolding="2"
85            TargetMachine="1"/>
86         <Tool
87            Name="VCMIDLTool"/>
88         <Tool
89            Name="VCPostBuildEventTool"/>
90         <Tool
91            Name="VCPreBuildEventTool"/>
92         <Tool
93            Name="VCPreLinkEventTool"/>
94         <Tool
95            Name="VCResourceCompilerTool"/>
96         <Tool
97            Name="VCWebServiceProxyGeneratorTool"/>
98         <Tool
99            Name="VCXMLDataGeneratorTool"/>
100         <Tool
101            Name="VCWebDeploymentTool"/>
102         <Tool
103            Name="VCManagedWrapperGeneratorTool"/>
104         <Tool
105            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
106      </Configuration>
107   </Configurations>
108   <References>
109      <ProjectReference
110         ReferencedProjectIdentifier="{3AF54C8A-10BF-4332-9147-F68ED9862032}"
111         Name="gtest_main"/>
112   </References>
113   <Files>
114      <Filter
115         Name="Source Files"
116         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
117         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
118         <File
119            RelativePath="..\test\gtest_prod_test.cc">
120            <FileConfiguration
121               Name="Debug|Win32">
122               <Tool
123                  Name="VCCLCompilerTool"
124                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
125                  UsePrecompiledHeader="0"/>
126            </FileConfiguration>
127            <FileConfiguration
128               Name="Release|Win32">
129               <Tool
130                  Name="VCCLCompilerTool"
131                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
132                  UsePrecompiledHeader="0"/>
133            </FileConfiguration>
134         </File>
135         <File
136            RelativePath="..\test\production.cc">
137            <FileConfiguration
138               Name="Debug|Win32">
139               <Tool
140                  Name="VCCLCompilerTool"
141                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
142                  UsePrecompiledHeader="0"/>
143            </FileConfiguration>
144            <FileConfiguration
145               Name="Release|Win32">
146               <Tool
147                  Name="VCCLCompilerTool"
148                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
149                  UsePrecompiledHeader="0"/>
150            </FileConfiguration>
151         </File>
152      </Filter>
153      <Filter
154         Name="Header Files"
155         Filter="h;hpp;hxx;hm;inl;inc;xsd"
156         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
157         <File
158            RelativePath="..\test\production.h">
159         </File>
160      </Filter>
161   </Files>
162   <Globals>
163   </Globals>
164</VisualStudioProject>
trunk/3rdparty/googletest/googletest/msvc/gtest_unittest-md.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest_unittest-md"
6   ProjectGUID="{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="1"
18         CharacterSet="2">
19         <Tool
20            Name="VCCLCompilerTool"
21            Optimization="0"
22            PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
23            MinimalRebuild="TRUE"
24            BasicRuntimeChecks="3"
25            RuntimeLibrary="3"
26            UsePrecompiledHeader="3"
27            WarningLevel="3"
28            Detect64BitPortabilityProblems="FALSE"
29            DebugInformationFormat="4"/>
30         <Tool
31            Name="VCCustomBuildTool"/>
32         <Tool
33            Name="VCLinkerTool"
34            OutputFile="$(OutDir)/gtest_unittest.exe"
35            LinkIncremental="2"
36            GenerateDebugInformation="TRUE"
37            ProgramDatabaseFile="$(OutDir)/gtest_unittest.pdb"
38            SubSystem="1"
39            TargetMachine="1"/>
40         <Tool
41            Name="VCMIDLTool"/>
42         <Tool
43            Name="VCPostBuildEventTool"/>
44         <Tool
45            Name="VCPreBuildEventTool"/>
46         <Tool
47            Name="VCPreLinkEventTool"/>
48         <Tool
49            Name="VCResourceCompilerTool"/>
50         <Tool
51            Name="VCWebServiceProxyGeneratorTool"/>
52         <Tool
53            Name="VCXMLDataGeneratorTool"/>
54         <Tool
55            Name="VCWebDeploymentTool"/>
56         <Tool
57            Name="VCManagedWrapperGeneratorTool"/>
58         <Tool
59            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
60      </Configuration>
61      <Configuration
62         Name="Release|Win32"
63         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
64         IntermediateDirectory="$(OutDir)/$(ProjectName)"
65         ConfigurationType="1"
66         CharacterSet="2">
67         <Tool
68            Name="VCCLCompilerTool"
69            PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
70            RuntimeLibrary="2"
71            UsePrecompiledHeader="3"
72            WarningLevel="3"
73            Detect64BitPortabilityProblems="FALSE"
74            DebugInformationFormat="3"/>
75         <Tool
76            Name="VCCustomBuildTool"/>
77         <Tool
78            Name="VCLinkerTool"
79            OutputFile="$(OutDir)/gtest_unittest.exe"
80            LinkIncremental="1"
81            GenerateDebugInformation="TRUE"
82            SubSystem="1"
83            OptimizeReferences="2"
84            EnableCOMDATFolding="2"
85            TargetMachine="1"/>
86         <Tool
87            Name="VCMIDLTool"/>
88         <Tool
89            Name="VCPostBuildEventTool"/>
90         <Tool
91            Name="VCPreBuildEventTool"/>
92         <Tool
93            Name="VCPreLinkEventTool"/>
94         <Tool
95            Name="VCResourceCompilerTool"/>
96         <Tool
97            Name="VCWebServiceProxyGeneratorTool"/>
98         <Tool
99            Name="VCXMLDataGeneratorTool"/>
100         <Tool
101            Name="VCWebDeploymentTool"/>
102         <Tool
103            Name="VCManagedWrapperGeneratorTool"/>
104         <Tool
105            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
106      </Configuration>
107   </Configurations>
108   <References>
109      <ProjectReference
110         ReferencedProjectIdentifier="{3AF54C8A-10BF-4332-9147-F68ED9862033}"
111         Name="gtest_main-md"/>
112   </References>
113   <Files>
114      <Filter
115         Name="Source Files"
116         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
117         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
118         <File
119            RelativePath="..\test\gtest_unittest.cc">
120            <FileConfiguration
121               Name="Debug|Win32">
122               <Tool
123                  Name="VCCLCompilerTool"
124                  Optimization="1"
125                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
126                  BasicRuntimeChecks="0"
127                  UsePrecompiledHeader="0"
128                  DebugInformationFormat="3"/>
129            </FileConfiguration>
130            <FileConfiguration
131               Name="Release|Win32">
132               <Tool
133                  Name="VCCLCompilerTool"
134                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
135                  UsePrecompiledHeader="0"/>
136            </FileConfiguration>
137         </File>
138      </Filter>
139      <Filter
140         Name="Header Files"
141         Filter="h;hpp;hxx;hm;inl;inc;xsd"
142         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
143      </Filter>
144   </Files>
145   <Globals>
146   </Globals>
147</VisualStudioProject>
trunk/3rdparty/googletest/googletest/msvc/gtest_unittest.vcproj
r0r249096
1<?xml version="1.0" encoding="Windows-1252"?>
2<VisualStudioProject
3   ProjectType="Visual C++"
4   Version="7.10"
5   Name="gtest_unittest"
6   ProjectGUID="{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}"
7   Keyword="Win32Proj">
8   <Platforms>
9      <Platform
10         Name="Win32"/>
11   </Platforms>
12   <Configurations>
13      <Configuration
14         Name="Debug|Win32"
15         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
16         IntermediateDirectory="$(OutDir)/$(ProjectName)"
17         ConfigurationType="1"
18         CharacterSet="2">
19         <Tool
20            Name="VCCLCompilerTool"
21            Optimization="0"
22            PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
23            MinimalRebuild="TRUE"
24            BasicRuntimeChecks="3"
25            RuntimeLibrary="5"
26            UsePrecompiledHeader="3"
27            WarningLevel="3"
28            Detect64BitPortabilityProblems="FALSE"
29            DebugInformationFormat="4"/>
30         <Tool
31            Name="VCCustomBuildTool"/>
32         <Tool
33            Name="VCLinkerTool"
34            OutputFile="$(OutDir)/gtest_unittest.exe"
35            LinkIncremental="2"
36            GenerateDebugInformation="TRUE"
37            ProgramDatabaseFile="$(OutDir)/gtest_unittest.pdb"
38            SubSystem="1"
39            TargetMachine="1"/>
40         <Tool
41            Name="VCMIDLTool"/>
42         <Tool
43            Name="VCPostBuildEventTool"/>
44         <Tool
45            Name="VCPreBuildEventTool"/>
46         <Tool
47            Name="VCPreLinkEventTool"/>
48         <Tool
49            Name="VCResourceCompilerTool"/>
50         <Tool
51            Name="VCWebServiceProxyGeneratorTool"/>
52         <Tool
53            Name="VCXMLDataGeneratorTool"/>
54         <Tool
55            Name="VCWebDeploymentTool"/>
56         <Tool
57            Name="VCManagedWrapperGeneratorTool"/>
58         <Tool
59            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
60      </Configuration>
61      <Configuration
62         Name="Release|Win32"
63         OutputDirectory="$(SolutionName)/$(ConfigurationName)"
64         IntermediateDirectory="$(OutDir)/$(ProjectName)"
65         ConfigurationType="1"
66         CharacterSet="2">
67         <Tool
68            Name="VCCLCompilerTool"
69            PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
70            RuntimeLibrary="4"
71            UsePrecompiledHeader="3"
72            WarningLevel="3"
73            Detect64BitPortabilityProblems="FALSE"
74            DebugInformationFormat="3"/>
75         <Tool
76            Name="VCCustomBuildTool"/>
77         <Tool
78            Name="VCLinkerTool"
79            OutputFile="$(OutDir)/gtest_unittest.exe"
80            LinkIncremental="1"
81            GenerateDebugInformation="TRUE"
82            SubSystem="1"
83            OptimizeReferences="2"
84            EnableCOMDATFolding="2"
85            TargetMachine="1"/>
86         <Tool
87            Name="VCMIDLTool"/>
88         <Tool
89            Name="VCPostBuildEventTool"/>
90         <Tool
91            Name="VCPreBuildEventTool"/>
92         <Tool
93            Name="VCPreLinkEventTool"/>
94         <Tool
95            Name="VCResourceCompilerTool"/>
96         <Tool
97            Name="VCWebServiceProxyGeneratorTool"/>
98         <Tool
99            Name="VCXMLDataGeneratorTool"/>
100         <Tool
101            Name="VCWebDeploymentTool"/>
102         <Tool
103            Name="VCManagedWrapperGeneratorTool"/>
104         <Tool
105            Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
106      </Configuration>
107   </Configurations>
108   <References>
109      <ProjectReference
110         ReferencedProjectIdentifier="{3AF54C8A-10BF-4332-9147-F68ED9862032}"
111         Name="gtest_main"/>
112   </References>
113   <Files>
114      <Filter
115         Name="Source Files"
116         Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
117         UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
118         <File
119            RelativePath="..\test\gtest_unittest.cc">
120            <FileConfiguration
121               Name="Debug|Win32">
122               <Tool
123                  Name="VCCLCompilerTool"
124                  Optimization="1"
125                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
126                  BasicRuntimeChecks="0"
127                  UsePrecompiledHeader="0"
128                  DebugInformationFormat="3"/>
129            </FileConfiguration>
130            <FileConfiguration
131               Name="Release|Win32">
132               <Tool
133                  Name="VCCLCompilerTool"
134                  AdditionalIncludeDirectories="&quot;..&quot;;&quot;..\include&quot;"
135                  UsePrecompiledHeader="0"/>
136            </FileConfiguration>
137         </File>
138      </Filter>
139      <Filter
140         Name="Header Files"
141         Filter="h;hpp;hxx;hm;inl;inc;xsd"
142         UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
143      </Filter>
144   </Files>
145   <Globals>
146   </Globals>
147</VisualStudioProject>
trunk/3rdparty/googletest/googletest/samples/prime_tables.h
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31// Author: vladl@google.com (Vlad Losev)
32
33// This provides interface PrimeTable that determines whether a number is a
34// prime and determines a next prime number. This interface is used
35// in Google Test samples demonstrating use of parameterized tests.
36
37#ifndef GTEST_SAMPLES_PRIME_TABLES_H_
38#define GTEST_SAMPLES_PRIME_TABLES_H_
39
40#include <algorithm>
41
42// The prime table interface.
43class PrimeTable {
44 public:
45  virtual ~PrimeTable() {}
46
47  // Returns true iff n is a prime number.
48  virtual bool IsPrime(int n) const = 0;
49
50  // Returns the smallest prime number greater than p; or returns -1
51  // if the next prime is beyond the capacity of the table.
52  virtual int GetNextPrime(int p) const = 0;
53};
54
55// Implementation #1 calculates the primes on-the-fly.
56class OnTheFlyPrimeTable : public PrimeTable {
57 public:
58  virtual bool IsPrime(int n) const {
59    if (n <= 1) return false;
60
61    for (int i = 2; i*i <= n; i++) {
62      // n is divisible by an integer other than 1 and itself.
63      if ((n % i) == 0) return false;
64    }
65
66    return true;
67  }
68
69  virtual int GetNextPrime(int p) const {
70    for (int n = p + 1; n > 0; n++) {
71      if (IsPrime(n)) return n;
72    }
73
74    return -1;
75  }
76};
77
78// Implementation #2 pre-calculates the primes and stores the result
79// in an array.
80class PreCalculatedPrimeTable : public PrimeTable {
81 public:
82  // 'max' specifies the maximum number the prime table holds.
83  explicit PreCalculatedPrimeTable(int max)
84      : is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
85    CalculatePrimesUpTo(max);
86  }
87  virtual ~PreCalculatedPrimeTable() { delete[] is_prime_; }
88
89  virtual bool IsPrime(int n) const {
90    return 0 <= n && n < is_prime_size_ && is_prime_[n];
91  }
92
93  virtual int GetNextPrime(int p) const {
94    for (int n = p + 1; n < is_prime_size_; n++) {
95      if (is_prime_[n]) return n;
96    }
97
98    return -1;
99  }
100
101 private:
102  void CalculatePrimesUpTo(int max) {
103    ::std::fill(is_prime_, is_prime_ + is_prime_size_, true);
104    is_prime_[0] = is_prime_[1] = false;
105
106    for (int i = 2; i <= max; i++) {
107      if (!is_prime_[i]) continue;
108
109      // Marks all multiples of i (except i itself) as non-prime.
110      for (int j = 2*i; j <= max; j += i) {
111        is_prime_[j] = false;
112      }
113    }
114  }
115
116  const int is_prime_size_;
117  bool* const is_prime_;
118
119  // Disables compiler warning "assignment operator could not be generated."
120  void operator=(const PreCalculatedPrimeTable& rhs);
121};
122
123#endif  // GTEST_SAMPLES_PRIME_TABLES_H_
trunk/3rdparty/googletest/googletest/samples/sample1.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34#include "sample1.h"
35
36// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
37int Factorial(int n) {
38  int result = 1;
39  for (int i = 1; i <= n; i++) {
40    result *= i;
41  }
42
43  return result;
44}
45
46// Returns true iff n is a prime number.
47bool IsPrime(int n) {
48  // Trivial case 1: small numbers
49  if (n <= 1) return false;
50
51  // Trivial case 2: even numbers
52  if (n % 2 == 0) return n == 2;
53
54  // Now, we have that n is odd and n >= 3.
55
56  // Try to divide n by every odd number i, starting from 3
57  for (int i = 3; ; i += 2) {
58    // We only have to try i up to the squre root of n
59    if (i > n/i) break;
60
61    // Now, we have i <= n/i < n.
62    // If n is divisible by i, n is not prime.
63    if (n % i == 0) return false;
64  }
65
66  // n has no integer factor in the range (1, n), and thus is prime.
67  return true;
68}
trunk/3rdparty/googletest/googletest/samples/sample1.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34#ifndef GTEST_SAMPLES_SAMPLE1_H_
35#define GTEST_SAMPLES_SAMPLE1_H_
36
37// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
38int Factorial(int n);
39
40// Returns true iff n is a prime number.
41bool IsPrime(int n);
42
43#endif  // GTEST_SAMPLES_SAMPLE1_H_
trunk/3rdparty/googletest/googletest/samples/sample10_unittest.cc
r0r249096
1// Copyright 2009 Google Inc. All Rights Reserved.
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are
5// met:
6//
7//     * Redistributions of source code must retain the above copyright
8// notice, this list of conditions and the following disclaimer.
9//     * Redistributions in binary form must reproduce the above
10// copyright notice, this list of conditions and the following disclaimer
11// in the documentation and/or other materials provided with the
12// distribution.
13//     * Neither the name of Google Inc. nor the names of its
14// contributors may be used to endorse or promote products derived from
15// this software without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: vladl@google.com (Vlad Losev)
30
31// This sample shows how to use Google Test listener API to implement
32// a primitive leak checker.
33
34#include <stdio.h>
35#include <stdlib.h>
36
37#include "gtest/gtest.h"
38
39using ::testing::EmptyTestEventListener;
40using ::testing::InitGoogleTest;
41using ::testing::Test;
42using ::testing::TestCase;
43using ::testing::TestEventListeners;
44using ::testing::TestInfo;
45using ::testing::TestPartResult;
46using ::testing::UnitTest;
47
48namespace {
49
50// We will track memory used by this class.
51class Water {
52 public:
53  // Normal Water declarations go here.
54
55  // operator new and operator delete help us control water allocation.
56  void* operator new(size_t allocation_size) {
57    allocated_++;
58    return malloc(allocation_size);
59  }
60
61  void operator delete(void* block, size_t /* allocation_size */) {
62    allocated_--;
63    free(block);
64  }
65
66  static int allocated() { return allocated_; }
67
68 private:
69  static int allocated_;
70};
71
72int Water::allocated_ = 0;
73
74// This event listener monitors how many Water objects are created and
75// destroyed by each test, and reports a failure if a test leaks some Water
76// objects. It does this by comparing the number of live Water objects at
77// the beginning of a test and at the end of a test.
78class LeakChecker : public EmptyTestEventListener {
79 private:
80  // Called before a test starts.
81  virtual void OnTestStart(const TestInfo& /* test_info */) {
82    initially_allocated_ = Water::allocated();
83  }
84
85  // Called after a test ends.
86  virtual void OnTestEnd(const TestInfo& /* test_info */) {
87    int difference = Water::allocated() - initially_allocated_;
88
89    // You can generate a failure in any event handler except
90    // OnTestPartResult. Just use an appropriate Google Test assertion to do
91    // it.
92    EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
93  }
94
95  int initially_allocated_;
96};
97
98TEST(ListenersTest, DoesNotLeak) {
99  Water* water = new Water;
100  delete water;
101}
102
103// This should fail when the --check_for_leaks command line flag is
104// specified.
105TEST(ListenersTest, LeaksWater) {
106  Water* water = new Water;
107  EXPECT_TRUE(water != NULL);
108}
109
110}  // namespace
111
112int main(int argc, char **argv) {
113  InitGoogleTest(&argc, argv);
114
115  bool check_for_leaks = false;
116  if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )
117    check_for_leaks = true;
118  else
119    printf("%s\n", "Run this program with --check_for_leaks to enable "
120           "custom leak checking in the tests.");
121
122  // If we are given the --check_for_leaks command line flag, installs the
123  // leak checker.
124  if (check_for_leaks) {
125    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
126
127    // Adds the leak checker to the end of the test event listener list,
128    // after the default text output printer and the default XML report
129    // generator.
130    //
131    // The order is important - it ensures that failures generated in the
132    // leak checker's OnTestEnd() method are processed by the text and XML
133    // printers *before* their OnTestEnd() methods are called, such that
134    // they are attributed to the right test. Remember that a listener
135    // receives an OnXyzStart event *after* listeners preceding it in the
136    // list received that event, and receives an OnXyzEnd event *before*
137    // listeners preceding it.
138    //
139    // We don't need to worry about deleting the new listener later, as
140    // Google Test will do it.
141    listeners.Append(new LeakChecker);
142  }
143  return RUN_ALL_TESTS();
144}
trunk/3rdparty/googletest/googletest/samples/sample1_unittest.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34
35// This sample shows how to write a simple unit test for a function,
36// using Google C++ testing framework.
37//
38// Writing a unit test using Google C++ testing framework is easy as 1-2-3:
39
40
41// Step 1. Include necessary header files such that the stuff your
42// test logic needs is declared.
43//
44// Don't forget gtest.h, which declares the testing framework.
45
46#include <limits.h>
47#include "sample1.h"
48#include "gtest/gtest.h"
49
50
51// Step 2. Use the TEST macro to define your tests.
52//
53// TEST has two parameters: the test case name and the test name.
54// After using the macro, you should define your test logic between a
55// pair of braces.  You can use a bunch of macros to indicate the
56// success or failure of a test.  EXPECT_TRUE and EXPECT_EQ are
57// examples of such macros.  For a complete list, see gtest.h.
58//
59// <TechnicalDetails>
60//
61// In Google Test, tests are grouped into test cases.  This is how we
62// keep test code organized.  You should put logically related tests
63// into the same test case.
64//
65// The test case name and the test name should both be valid C++
66// identifiers.  And you should not use underscore (_) in the names.
67//
68// Google Test guarantees that each test you define is run exactly
69// once, but it makes no guarantee on the order the tests are
70// executed.  Therefore, you should write your tests in such a way
71// that their results don't depend on their order.
72//
73// </TechnicalDetails>
74
75
76// Tests Factorial().
77
78// Tests factorial of negative numbers.
79TEST(FactorialTest, Negative) {
80  // This test is named "Negative", and belongs to the "FactorialTest"
81  // test case.
82  EXPECT_EQ(1, Factorial(-5));
83  EXPECT_EQ(1, Factorial(-1));
84  EXPECT_GT(Factorial(-10), 0);
85
86  // <TechnicalDetails>
87  //
88  // EXPECT_EQ(expected, actual) is the same as
89  //
90  //   EXPECT_TRUE((expected) == (actual))
91  //
92  // except that it will print both the expected value and the actual
93  // value when the assertion fails.  This is very helpful for
94  // debugging.  Therefore in this case EXPECT_EQ is preferred.
95  //
96  // On the other hand, EXPECT_TRUE accepts any Boolean expression,
97  // and is thus more general.
98  //
99  // </TechnicalDetails>
100}
101
102// Tests factorial of 0.
103TEST(FactorialTest, Zero) {
104  EXPECT_EQ(1, Factorial(0));
105}
106
107// Tests factorial of positive numbers.
108TEST(FactorialTest, Positive) {
109  EXPECT_EQ(1, Factorial(1));
110  EXPECT_EQ(2, Factorial(2));
111  EXPECT_EQ(6, Factorial(3));
112  EXPECT_EQ(40320, Factorial(8));
113}
114
115
116// Tests IsPrime()
117
118// Tests negative input.
119TEST(IsPrimeTest, Negative) {
120  // This test belongs to the IsPrimeTest test case.
121
122  EXPECT_FALSE(IsPrime(-1));
123  EXPECT_FALSE(IsPrime(-2));
124  EXPECT_FALSE(IsPrime(INT_MIN));
125}
126
127// Tests some trivial cases.
128TEST(IsPrimeTest, Trivial) {
129  EXPECT_FALSE(IsPrime(0));
130  EXPECT_FALSE(IsPrime(1));
131  EXPECT_TRUE(IsPrime(2));
132  EXPECT_TRUE(IsPrime(3));
133}
134
135// Tests positive input.
136TEST(IsPrimeTest, Positive) {
137  EXPECT_FALSE(IsPrime(4));
138  EXPECT_TRUE(IsPrime(5));
139  EXPECT_FALSE(IsPrime(6));
140  EXPECT_TRUE(IsPrime(23));
141}
142
143// Step 3. Call RUN_ALL_TESTS() in main().
144//
145// We do this by linking in src/gtest_main.cc file, which consists of
146// a main() function which calls RUN_ALL_TESTS() for us.
147//
148// This runs all the tests you've defined, prints the result, and
149// returns 0 if successful, or 1 otherwise.
150//
151// Did you notice that we didn't register the tests?  The
152// RUN_ALL_TESTS() macro magically knows about all the tests we
153// defined.  Isn't this convenient?
trunk/3rdparty/googletest/googletest/samples/sample2.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34#include "sample2.h"
35
36#include <string.h>
37
38// Clones a 0-terminated C string, allocating memory using new.
39const char* MyString::CloneCString(const char* a_c_string) {
40  if (a_c_string == NULL) return NULL;
41
42  const size_t len = strlen(a_c_string);
43  char* const clone = new char[ len + 1 ];
44  memcpy(clone, a_c_string, len + 1);
45
46  return clone;
47}
48
49// Sets the 0-terminated C string this MyString object
50// represents.
51void MyString::Set(const char* a_c_string) {
52  // Makes sure this works when c_string == c_string_
53  const char* const temp = MyString::CloneCString(a_c_string);
54  delete[] c_string_;
55  c_string_ = temp;
56}
trunk/3rdparty/googletest/googletest/samples/sample2.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34#ifndef GTEST_SAMPLES_SAMPLE2_H_
35#define GTEST_SAMPLES_SAMPLE2_H_
36
37#include <string.h>
38
39
40// A simple string class.
41class MyString {
42 private:
43  const char* c_string_;
44  const MyString& operator=(const MyString& rhs);
45
46 public:
47  // Clones a 0-terminated C string, allocating memory using new.
48  static const char* CloneCString(const char* a_c_string);
49
50  ////////////////////////////////////////////////////////////
51  //
52  // C'tors
53
54  // The default c'tor constructs a NULL string.
55  MyString() : c_string_(NULL) {}
56
57  // Constructs a MyString by cloning a 0-terminated C string.
58  explicit MyString(const char* a_c_string) : c_string_(NULL) {
59    Set(a_c_string);
60  }
61
62  // Copy c'tor
63  MyString(const MyString& string) : c_string_(NULL) {
64    Set(string.c_string_);
65  }
66
67  ////////////////////////////////////////////////////////////
68  //
69  // D'tor.  MyString is intended to be a final class, so the d'tor
70  // doesn't need to be virtual.
71  ~MyString() { delete[] c_string_; }
72
73  // Gets the 0-terminated C string this MyString object represents.
74  const char* c_string() const { return c_string_; }
75
76  size_t Length() const {
77    return c_string_ == NULL ? 0 : strlen(c_string_);
78  }
79
80  // Sets the 0-terminated C string this MyString object represents.
81  void Set(const char* c_string);
82};
83
84
85#endif  // GTEST_SAMPLES_SAMPLE2_H_
trunk/3rdparty/googletest/googletest/samples/sample2_unittest.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34
35// This sample shows how to write a more complex unit test for a class
36// that has multiple member functions.
37//
38// Usually, it's a good idea to have one test for each method in your
39// class.  You don't have to do that exactly, but it helps to keep
40// your tests organized.  You may also throw in additional tests as
41// needed.
42
43#include "sample2.h"
44#include "gtest/gtest.h"
45
46// In this example, we test the MyString class (a simple string).
47
48// Tests the default c'tor.
49TEST(MyString, DefaultConstructor) {
50  const MyString s;
51
52  // Asserts that s.c_string() returns NULL.
53  //
54  // <TechnicalDetails>
55  //
56  // If we write NULL instead of
57  //
58  //   static_cast<const char *>(NULL)
59  //
60  // in this assertion, it will generate a warning on gcc 3.4.  The
61  // reason is that EXPECT_EQ needs to know the types of its
62  // arguments in order to print them when it fails.  Since NULL is
63  // #defined as 0, the compiler will use the formatter function for
64  // int to print it.  However, gcc thinks that NULL should be used as
65  // a pointer, not an int, and therefore complains.
66  //
67  // The root of the problem is C++'s lack of distinction between the
68  // integer number 0 and the null pointer constant.  Unfortunately,
69  // we have to live with this fact.
70  //
71  // </TechnicalDetails>
72  EXPECT_STREQ(NULL, s.c_string());
73
74  EXPECT_EQ(0u, s.Length());
75}
76
77const char kHelloString[] = "Hello, world!";
78
79// Tests the c'tor that accepts a C string.
80TEST(MyString, ConstructorFromCString) {
81  const MyString s(kHelloString);
82  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
83  EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
84            s.Length());
85}
86
87// Tests the copy c'tor.
88TEST(MyString, CopyConstructor) {
89  const MyString s1(kHelloString);
90  const MyString s2 = s1;
91  EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString));
92}
93
94// Tests the Set method.
95TEST(MyString, Set) {
96  MyString s;
97
98  s.Set(kHelloString);
99  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
100
101  // Set should work when the input pointer is the same as the one
102  // already in the MyString object.
103  s.Set(s.c_string());
104  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
105
106  // Can we set the MyString to NULL?
107  s.Set(NULL);
108  EXPECT_STREQ(NULL, s.c_string());
109}
trunk/3rdparty/googletest/googletest/samples/sample3-inl.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
35#define GTEST_SAMPLES_SAMPLE3_INL_H_
36
37#include <stddef.h>
38
39
40// Queue is a simple queue implemented as a singled-linked list.
41//
42// The element type must support copy constructor.
43template <typename E>  // E is the element type
44class Queue;
45
46// QueueNode is a node in a Queue, which consists of an element of
47// type E and a pointer to the next node.
48template <typename E>  // E is the element type
49class QueueNode {
50  friend class Queue<E>;
51
52 public:
53  // Gets the element in this node.
54  const E& element() const { return element_; }
55
56  // Gets the next node in the queue.
57  QueueNode* next() { return next_; }
58  const QueueNode* next() const { return next_; }
59
60 private:
61  // Creates a node with a given element value.  The next pointer is
62  // set to NULL.
63  explicit QueueNode(const E& an_element) : element_(an_element), next_(NULL) {}
64
65  // We disable the default assignment operator and copy c'tor.
66  const QueueNode& operator = (const QueueNode&);
67  QueueNode(const QueueNode&);
68
69  E element_;
70  QueueNode* next_;
71};
72
73template <typename E>  // E is the element type.
74class Queue {
75 public:
76  // Creates an empty queue.
77  Queue() : head_(NULL), last_(NULL), size_(0) {}
78
79  // D'tor.  Clears the queue.
80  ~Queue() { Clear(); }
81
82  // Clears the queue.
83  void Clear() {
84    if (size_ > 0) {
85      // 1. Deletes every node.
86      QueueNode<E>* node = head_;
87      QueueNode<E>* next = node->next();
88      for (; ;) {
89        delete node;
90        node = next;
91        if (node == NULL) break;
92        next = node->next();
93      }
94
95      // 2. Resets the member variables.
96      head_ = last_ = NULL;
97      size_ = 0;
98    }
99  }
100
101  // Gets the number of elements.
102  size_t Size() const { return size_; }
103
104  // Gets the first element of the queue, or NULL if the queue is empty.
105  QueueNode<E>* Head() { return head_; }
106  const QueueNode<E>* Head() const { return head_; }
107
108  // Gets the last element of the queue, or NULL if the queue is empty.
109  QueueNode<E>* Last() { return last_; }
110  const QueueNode<E>* Last() const { return last_; }
111
112  // Adds an element to the end of the queue.  A copy of the element is
113  // created using the copy constructor, and then stored in the queue.
114  // Changes made to the element in the queue doesn't affect the source
115  // object, and vice versa.
116  void Enqueue(const E& element) {
117    QueueNode<E>* new_node = new QueueNode<E>(element);
118
119    if (size_ == 0) {
120      head_ = last_ = new_node;
121      size_ = 1;
122    } else {
123      last_->next_ = new_node;
124      last_ = new_node;
125      size_++;
126    }
127  }
128
129  // Removes the head of the queue and returns it.  Returns NULL if
130  // the queue is empty.
131  E* Dequeue() {
132    if (size_ == 0) {
133      return NULL;
134    }
135
136    const QueueNode<E>* const old_head = head_;
137    head_ = head_->next_;
138    size_--;
139    if (size_ == 0) {
140      last_ = NULL;
141    }
142
143    E* element = new E(old_head->element());
144    delete old_head;
145
146    return element;
147  }
148
149  // Applies a function/functor on each element of the queue, and
150  // returns the result in a new queue.  The original queue is not
151  // affected.
152  template <typename F>
153  Queue* Map(F function) const {
154    Queue* new_queue = new Queue();
155    for (const QueueNode<E>* node = head_; node != NULL; node = node->next_) {
156      new_queue->Enqueue(function(node->element()));
157    }
158
159    return new_queue;
160  }
161
162 private:
163  QueueNode<E>* head_;  // The first node of the queue.
164  QueueNode<E>* last_;  // The last node of the queue.
165  size_t size_;  // The number of elements in the queue.
166
167  // We disallow copying a queue.
168  Queue(const Queue&);
169  const Queue& operator = (const Queue&);
170};
171
172#endif  // GTEST_SAMPLES_SAMPLE3_INL_H_
trunk/3rdparty/googletest/googletest/samples/sample3_unittest.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34
35// In this example, we use a more advanced feature of Google Test called
36// test fixture.
37//
38// A test fixture is a place to hold objects and functions shared by
39// all tests in a test case.  Using a test fixture avoids duplicating
40// the test code necessary to initialize and cleanup those common
41// objects for each test.  It is also useful for defining sub-routines
42// that your tests need to invoke a lot.
43//
44// <TechnicalDetails>
45//
46// The tests share the test fixture in the sense of code sharing, not
47// data sharing.  Each test is given its own fresh copy of the
48// fixture.  You cannot expect the data modified by one test to be
49// passed on to another test, which is a bad idea.
50//
51// The reason for this design is that tests should be independent and
52// repeatable.  In particular, a test should not fail as the result of
53// another test's failure.  If one test depends on info produced by
54// another test, then the two tests should really be one big test.
55//
56// The macros for indicating the success/failure of a test
57// (EXPECT_TRUE, FAIL, etc) need to know what the current test is
58// (when Google Test prints the test result, it tells you which test
59// each failure belongs to).  Technically, these macros invoke a
60// member function of the Test class.  Therefore, you cannot use them
61// in a global function.  That's why you should put test sub-routines
62// in a test fixture.
63//
64// </TechnicalDetails>
65
66#include "sample3-inl.h"
67#include "gtest/gtest.h"
68
69// To use a test fixture, derive a class from testing::Test.
70class QueueTest : public testing::Test {
71 protected:  // You should make the members protected s.t. they can be
72             // accessed from sub-classes.
73
74  // virtual void SetUp() will be called before each test is run.  You
75  // should define it if you need to initialize the varaibles.
76  // Otherwise, this can be skipped.
77  virtual void SetUp() {
78    q1_.Enqueue(1);
79    q2_.Enqueue(2);
80    q2_.Enqueue(3);
81  }
82
83  // virtual void TearDown() will be called after each test is run.
84  // You should define it if there is cleanup work to do.  Otherwise,
85  // you don't have to provide it.
86  //
87  // virtual void TearDown() {
88  // }
89
90  // A helper function that some test uses.
91  static int Double(int n) {
92    return 2*n;
93  }
94
95  // A helper function for testing Queue::Map().
96  void MapTester(const Queue<int> * q) {
97    // Creates a new queue, where each element is twice as big as the
98    // corresponding one in q.
99    const Queue<int> * const new_q = q->Map(Double);
100
101    // Verifies that the new queue has the same size as q.
102    ASSERT_EQ(q->Size(), new_q->Size());
103
104    // Verifies the relationship between the elements of the two queues.
105    for ( const QueueNode<int> * n1 = q->Head(), * n2 = new_q->Head();
106          n1 != NULL; n1 = n1->next(), n2 = n2->next() ) {
107      EXPECT_EQ(2 * n1->element(), n2->element());
108    }
109
110    delete new_q;
111  }
112
113  // Declares the variables your tests want to use.
114  Queue<int> q0_;
115  Queue<int> q1_;
116  Queue<int> q2_;
117};
118
119// When you have a test fixture, you define a test using TEST_F
120// instead of TEST.
121
122// Tests the default c'tor.
123TEST_F(QueueTest, DefaultConstructor) {
124  // You can access data in the test fixture here.
125  EXPECT_EQ(0u, q0_.Size());
126}
127
128// Tests Dequeue().
129TEST_F(QueueTest, Dequeue) {
130  int * n = q0_.Dequeue();
131  EXPECT_TRUE(n == NULL);
132
133  n = q1_.Dequeue();
134  ASSERT_TRUE(n != NULL);
135  EXPECT_EQ(1, *n);
136  EXPECT_EQ(0u, q1_.Size());
137  delete n;
138
139  n = q2_.Dequeue();
140  ASSERT_TRUE(n != NULL);
141  EXPECT_EQ(2, *n);
142  EXPECT_EQ(1u, q2_.Size());
143  delete n;
144}
145
146// Tests the Queue::Map() function.
147TEST_F(QueueTest, Map) {
148  MapTester(&q0_);
149  MapTester(&q1_);
150  MapTester(&q2_);
151}
trunk/3rdparty/googletest/googletest/samples/sample4.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34#include <stdio.h>
35
36#include "sample4.h"
37
38// Returns the current counter value, and increments it.
39int Counter::Increment() {
40  return counter_++;
41}
42
43// Prints the current counter value to STDOUT.
44void Counter::Print() const {
45  printf("%d", counter_);
46}
trunk/3rdparty/googletest/googletest/samples/sample4.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// A sample program demonstrating using Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33
34#ifndef GTEST_SAMPLES_SAMPLE4_H_
35#define GTEST_SAMPLES_SAMPLE4_H_
36
37// A simple monotonic counter.
38class Counter {
39 private:
40  int counter_;
41
42 public:
43  // Creates a counter that starts at 0.
44  Counter() : counter_(0) {}
45
46  // Returns the current counter value, and increments it.
47  int Increment();
48
49  // Prints the current counter value to STDOUT.
50  void Print() const;
51};
52
53#endif  // GTEST_SAMPLES_SAMPLE4_H_
trunk/3rdparty/googletest/googletest/samples/sample4_unittest.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gtest/gtest.h"
33#include "sample4.h"
34
35// Tests the Increment() method.
36TEST(Counter, Increment) {
37  Counter c;
38
39  // EXPECT_EQ() evaluates its arguments exactly once, so they
40  // can have side effects.
41
42  EXPECT_EQ(0, c.Increment());
43  EXPECT_EQ(1, c.Increment());
44  EXPECT_EQ(2, c.Increment());
45}
trunk/3rdparty/googletest/googletest/samples/sample5_unittest.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// This sample teaches how to reuse a test fixture in multiple test
33// cases by deriving sub-fixtures from it.
34//
35// When you define a test fixture, you specify the name of the test
36// case that will use this fixture.  Therefore, a test fixture can
37// be used by only one test case.
38//
39// Sometimes, more than one test cases may want to use the same or
40// slightly different test fixtures.  For example, you may want to
41// make sure that all tests for a GUI library don't leak important
42// system resources like fonts and brushes.  In Google Test, you do
43// this by putting the shared logic in a super (as in "super class")
44// test fixture, and then have each test case use a fixture derived
45// from this super fixture.
46
47#include <limits.h>
48#include <time.h>
49#include "sample3-inl.h"
50#include "gtest/gtest.h"
51#include "sample1.h"
52
53// In this sample, we want to ensure that every test finishes within
54// ~5 seconds.  If a test takes longer to run, we consider it a
55// failure.
56//
57// We put the code for timing a test in a test fixture called
58// "QuickTest".  QuickTest is intended to be the super fixture that
59// other fixtures derive from, therefore there is no test case with
60// the name "QuickTest".  This is OK.
61//
62// Later, we will derive multiple test fixtures from QuickTest.
63class QuickTest : public testing::Test {
64 protected:
65  // Remember that SetUp() is run immediately before a test starts.
66  // This is a good place to record the start time.
67  virtual void SetUp() {
68    start_time_ = time(NULL);
69  }
70
71  // TearDown() is invoked immediately after a test finishes.  Here we
72  // check if the test was too slow.
73  virtual void TearDown() {
74    // Gets the time when the test finishes
75    const time_t end_time = time(NULL);
76
77    // Asserts that the test took no more than ~5 seconds.  Did you
78    // know that you can use assertions in SetUp() and TearDown() as
79    // well?
80    EXPECT_TRUE(end_time - start_time_ <= 5) << "The test took too long.";
81  }
82
83  // The UTC time (in seconds) when the test starts
84  time_t start_time_;
85};
86
87
88// We derive a fixture named IntegerFunctionTest from the QuickTest
89// fixture.  All tests using this fixture will be automatically
90// required to be quick.
91class IntegerFunctionTest : public QuickTest {
92  // We don't need any more logic than already in the QuickTest fixture.
93  // Therefore the body is empty.
94};
95
96
97// Now we can write tests in the IntegerFunctionTest test case.
98
99// Tests Factorial()
100TEST_F(IntegerFunctionTest, Factorial) {
101  // Tests factorial of negative numbers.
102  EXPECT_EQ(1, Factorial(-5));
103  EXPECT_EQ(1, Factorial(-1));
104  EXPECT_GT(Factorial(-10), 0);
105
106  // Tests factorial of 0.
107  EXPECT_EQ(1, Factorial(0));
108
109  // Tests factorial of positive numbers.
110  EXPECT_EQ(1, Factorial(1));
111  EXPECT_EQ(2, Factorial(2));
112  EXPECT_EQ(6, Factorial(3));
113  EXPECT_EQ(40320, Factorial(8));
114}
115
116
117// Tests IsPrime()
118TEST_F(IntegerFunctionTest, IsPrime) {
119  // Tests negative input.
120  EXPECT_FALSE(IsPrime(-1));
121  EXPECT_FALSE(IsPrime(-2));
122  EXPECT_FALSE(IsPrime(INT_MIN));
123
124  // Tests some trivial cases.
125  EXPECT_FALSE(IsPrime(0));
126  EXPECT_FALSE(IsPrime(1));
127  EXPECT_TRUE(IsPrime(2));
128  EXPECT_TRUE(IsPrime(3));
129
130  // Tests positive input.
131  EXPECT_FALSE(IsPrime(4));
132  EXPECT_TRUE(IsPrime(5));
133  EXPECT_FALSE(IsPrime(6));
134  EXPECT_TRUE(IsPrime(23));
135}
136
137
138// The next test case (named "QueueTest") also needs to be quick, so
139// we derive another fixture from QuickTest.
140//
141// The QueueTest test fixture has some logic and shared objects in
142// addition to what's in QuickTest already.  We define the additional
143// stuff inside the body of the test fixture, as usual.
144class QueueTest : public QuickTest {
145 protected:
146  virtual void SetUp() {
147    // First, we need to set up the super fixture (QuickTest).
148    QuickTest::SetUp();
149
150    // Second, some additional setup for this fixture.
151    q1_.Enqueue(1);
152    q2_.Enqueue(2);
153    q2_.Enqueue(3);
154  }
155
156  // By default, TearDown() inherits the behavior of
157  // QuickTest::TearDown().  As we have no additional cleaning work
158  // for QueueTest, we omit it here.
159  //
160  // virtual void TearDown() {
161  //   QuickTest::TearDown();
162  // }
163
164  Queue<int> q0_;
165  Queue<int> q1_;
166  Queue<int> q2_;
167};
168
169
170// Now, let's write tests using the QueueTest fixture.
171
172// Tests the default constructor.
173TEST_F(QueueTest, DefaultConstructor) {
174  EXPECT_EQ(0u, q0_.Size());
175}
176
177// Tests Dequeue().
178TEST_F(QueueTest, Dequeue) {
179  int* n = q0_.Dequeue();
180  EXPECT_TRUE(n == NULL);
181
182  n = q1_.Dequeue();
183  EXPECT_TRUE(n != NULL);
184  EXPECT_EQ(1, *n);
185  EXPECT_EQ(0u, q1_.Size());
186  delete n;
187
188  n = q2_.Dequeue();
189  EXPECT_TRUE(n != NULL);
190  EXPECT_EQ(2, *n);
191  EXPECT_EQ(1u, q2_.Size());
192  delete n;
193}
194
195// If necessary, you can derive further test fixtures from a derived
196// fixture itself.  For example, you can derive another fixture from
197// QueueTest.  Google Test imposes no limit on how deep the hierarchy
198// can be.  In practice, however, you probably don't want it to be too
199// deep as to be confusing.
trunk/3rdparty/googletest/googletest/samples/sample6_unittest.cc
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// This sample shows how to test common properties of multiple
33// implementations of the same interface (aka interface tests).
34
35// The interface and its implementations are in this header.
36#include "prime_tables.h"
37
38#include "gtest/gtest.h"
39
40// First, we define some factory functions for creating instances of
41// the implementations.  You may be able to skip this step if all your
42// implementations can be constructed the same way.
43
44template <class T>
45PrimeTable* CreatePrimeTable();
46
47template <>
48PrimeTable* CreatePrimeTable<OnTheFlyPrimeTable>() {
49  return new OnTheFlyPrimeTable;
50}
51
52template <>
53PrimeTable* CreatePrimeTable<PreCalculatedPrimeTable>() {
54  return new PreCalculatedPrimeTable(10000);
55}
56
57// Then we define a test fixture class template.
58template <class T>
59class PrimeTableTest : public testing::Test {
60 protected:
61  // The ctor calls the factory function to create a prime table
62  // implemented by T.
63  PrimeTableTest() : table_(CreatePrimeTable<T>()) {}
64
65  virtual ~PrimeTableTest() { delete table_; }
66
67  // Note that we test an implementation via the base interface
68  // instead of the actual implementation class.  This is important
69  // for keeping the tests close to the real world scenario, where the
70  // implementation is invoked via the base interface.  It avoids
71  // got-yas where the implementation class has a method that shadows
72  // a method with the same name (but slightly different argument
73  // types) in the base interface, for example.
74  PrimeTable* const table_;
75};
76
77#if GTEST_HAS_TYPED_TEST
78
79using testing::Types;
80
81// Google Test offers two ways for reusing tests for different types.
82// The first is called "typed tests".  You should use it if you
83// already know *all* the types you are gonna exercise when you write
84// the tests.
85
86// To write a typed test case, first use
87//
88//   TYPED_TEST_CASE(TestCaseName, TypeList);
89//
90// to declare it and specify the type parameters.  As with TEST_F,
91// TestCaseName must match the test fixture name.
92
93// The list of types we want to test.
94typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable> Implementations;
95
96TYPED_TEST_CASE(PrimeTableTest, Implementations);
97
98// Then use TYPED_TEST(TestCaseName, TestName) to define a typed test,
99// similar to TEST_F.
100TYPED_TEST(PrimeTableTest, ReturnsFalseForNonPrimes) {
101  // Inside the test body, you can refer to the type parameter by
102  // TypeParam, and refer to the fixture class by TestFixture.  We
103  // don't need them in this example.
104
105  // Since we are in the template world, C++ requires explicitly
106  // writing 'this->' when referring to members of the fixture class.
107  // This is something you have to learn to live with.
108  EXPECT_FALSE(this->table_->IsPrime(-5));
109  EXPECT_FALSE(this->table_->IsPrime(0));
110  EXPECT_FALSE(this->table_->IsPrime(1));
111  EXPECT_FALSE(this->table_->IsPrime(4));
112  EXPECT_FALSE(this->table_->IsPrime(6));
113  EXPECT_FALSE(this->table_->IsPrime(100));
114}
115
116TYPED_TEST(PrimeTableTest, ReturnsTrueForPrimes) {
117  EXPECT_TRUE(this->table_->IsPrime(2));
118  EXPECT_TRUE(this->table_->IsPrime(3));
119  EXPECT_TRUE(this->table_->IsPrime(5));
120  EXPECT_TRUE(this->table_->IsPrime(7));
121  EXPECT_TRUE(this->table_->IsPrime(11));
122  EXPECT_TRUE(this->table_->IsPrime(131));
123}
124
125TYPED_TEST(PrimeTableTest, CanGetNextPrime) {
126  EXPECT_EQ(2, this->table_->GetNextPrime(0));
127  EXPECT_EQ(3, this->table_->GetNextPrime(2));
128  EXPECT_EQ(5, this->table_->GetNextPrime(3));
129  EXPECT_EQ(7, this->table_->GetNextPrime(5));
130  EXPECT_EQ(11, this->table_->GetNextPrime(7));
131  EXPECT_EQ(131, this->table_->GetNextPrime(128));
132}
133
134// That's it!  Google Test will repeat each TYPED_TEST for each type
135// in the type list specified in TYPED_TEST_CASE.  Sit back and be
136// happy that you don't have to define them multiple times.
137
138#endif  // GTEST_HAS_TYPED_TEST
139
140#if GTEST_HAS_TYPED_TEST_P
141
142using testing::Types;
143
144// Sometimes, however, you don't yet know all the types that you want
145// to test when you write the tests.  For example, if you are the
146// author of an interface and expect other people to implement it, you
147// might want to write a set of tests to make sure each implementation
148// conforms to some basic requirements, but you don't know what
149// implementations will be written in the future.
150//
151// How can you write the tests without committing to the type
152// parameters?  That's what "type-parameterized tests" can do for you.
153// It is a bit more involved than typed tests, but in return you get a
154// test pattern that can be reused in many contexts, which is a big
155// win.  Here's how you do it:
156
157// First, define a test fixture class template.  Here we just reuse
158// the PrimeTableTest fixture defined earlier:
159
160template <class T>
161class PrimeTableTest2 : public PrimeTableTest<T> {
162};
163
164// Then, declare the test case.  The argument is the name of the test
165// fixture, and also the name of the test case (as usual).  The _P
166// suffix is for "parameterized" or "pattern".
167TYPED_TEST_CASE_P(PrimeTableTest2);
168
169// Next, use TYPED_TEST_P(TestCaseName, TestName) to define a test,
170// similar to what you do with TEST_F.
171TYPED_TEST_P(PrimeTableTest2, ReturnsFalseForNonPrimes) {
172  EXPECT_FALSE(this->table_->IsPrime(-5));
173  EXPECT_FALSE(this->table_->IsPrime(0));
174  EXPECT_FALSE(this->table_->IsPrime(1));
175  EXPECT_FALSE(this->table_->IsPrime(4));
176  EXPECT_FALSE(this->table_->IsPrime(6));
177  EXPECT_FALSE(this->table_->IsPrime(100));
178}
179
180TYPED_TEST_P(PrimeTableTest2, ReturnsTrueForPrimes) {
181  EXPECT_TRUE(this->table_->IsPrime(2));
182  EXPECT_TRUE(this->table_->IsPrime(3));
183  EXPECT_TRUE(this->table_->IsPrime(5));
184  EXPECT_TRUE(this->table_->IsPrime(7));
185  EXPECT_TRUE(this->table_->IsPrime(11));
186  EXPECT_TRUE(this->table_->IsPrime(131));
187}
188
189TYPED_TEST_P(PrimeTableTest2, CanGetNextPrime) {
190  EXPECT_EQ(2, this->table_->GetNextPrime(0));
191  EXPECT_EQ(3, this->table_->GetNextPrime(2));
192  EXPECT_EQ(5, this->table_->GetNextPrime(3));
193  EXPECT_EQ(7, this->table_->GetNextPrime(5));
194  EXPECT_EQ(11, this->table_->GetNextPrime(7));
195  EXPECT_EQ(131, this->table_->GetNextPrime(128));
196}
197
198// Type-parameterized tests involve one extra step: you have to
199// enumerate the tests you defined:
200REGISTER_TYPED_TEST_CASE_P(
201    PrimeTableTest2,  // The first argument is the test case name.
202    // The rest of the arguments are the test names.
203    ReturnsFalseForNonPrimes, ReturnsTrueForPrimes, CanGetNextPrime);
204
205// At this point the test pattern is done.  However, you don't have
206// any real test yet as you haven't said which types you want to run
207// the tests with.
208
209// To turn the abstract test pattern into real tests, you instantiate
210// it with a list of types.  Usually the test pattern will be defined
211// in a .h file, and anyone can #include and instantiate it.  You can
212// even instantiate it more than once in the same program.  To tell
213// different instances apart, you give each of them a name, which will
214// become part of the test case name and can be used in test filters.
215
216// The list of types we want to test.  Note that it doesn't have to be
217// defined at the time we write the TYPED_TEST_P()s.
218typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable>
219    PrimeTableImplementations;
220INSTANTIATE_TYPED_TEST_CASE_P(OnTheFlyAndPreCalculated,    // Instance name
221                              PrimeTableTest2,             // Test case name
222                              PrimeTableImplementations);  // Type list
223
224#endif  // GTEST_HAS_TYPED_TEST_P
trunk/3rdparty/googletest/googletest/samples/sample7_unittest.cc
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31
32// This sample shows how to test common properties of multiple
33// implementations of an interface (aka interface tests) using
34// value-parameterized tests. Each test in the test case has
35// a parameter that is an interface pointer to an implementation
36// tested.
37
38// The interface and its implementations are in this header.
39#include "prime_tables.h"
40
41#include "gtest/gtest.h"
42
43#if GTEST_HAS_PARAM_TEST
44
45using ::testing::TestWithParam;
46using ::testing::Values;
47
48// As a general rule, to prevent a test from affecting the tests that come
49// after it, you should create and destroy the tested objects for each test
50// instead of reusing them.  In this sample we will define a simple factory
51// function for PrimeTable objects.  We will instantiate objects in test's
52// SetUp() method and delete them in TearDown() method.
53typedef PrimeTable* CreatePrimeTableFunc();
54
55PrimeTable* CreateOnTheFlyPrimeTable() {
56  return new OnTheFlyPrimeTable();
57}
58
59template <size_t max_precalculated>
60PrimeTable* CreatePreCalculatedPrimeTable() {
61  return new PreCalculatedPrimeTable(max_precalculated);
62}
63
64// Inside the test body, fixture constructor, SetUp(), and TearDown() you
65// can refer to the test parameter by GetParam().  In this case, the test
66// parameter is a factory function which we call in fixture's SetUp() to
67// create and store an instance of PrimeTable.
68class PrimeTableTest : public TestWithParam<CreatePrimeTableFunc*> {
69 public:
70  virtual ~PrimeTableTest() { delete table_; }
71  virtual void SetUp() { table_ = (*GetParam())(); }
72  virtual void TearDown() {
73    delete table_;
74    table_ = NULL;
75  }
76
77 protected:
78  PrimeTable* table_;
79};
80
81TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {
82  EXPECT_FALSE(table_->IsPrime(-5));
83  EXPECT_FALSE(table_->IsPrime(0));
84  EXPECT_FALSE(table_->IsPrime(1));
85  EXPECT_FALSE(table_->IsPrime(4));
86  EXPECT_FALSE(table_->IsPrime(6));
87  EXPECT_FALSE(table_->IsPrime(100));
88}
89
90TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {
91  EXPECT_TRUE(table_->IsPrime(2));
92  EXPECT_TRUE(table_->IsPrime(3));
93  EXPECT_TRUE(table_->IsPrime(5));
94  EXPECT_TRUE(table_->IsPrime(7));
95  EXPECT_TRUE(table_->IsPrime(11));
96  EXPECT_TRUE(table_->IsPrime(131));
97}
98
99TEST_P(PrimeTableTest, CanGetNextPrime) {
100  EXPECT_EQ(2, table_->GetNextPrime(0));
101  EXPECT_EQ(3, table_->GetNextPrime(2));
102  EXPECT_EQ(5, table_->GetNextPrime(3));
103  EXPECT_EQ(7, table_->GetNextPrime(5));
104  EXPECT_EQ(11, table_->GetNextPrime(7));
105  EXPECT_EQ(131, table_->GetNextPrime(128));
106}
107
108// In order to run value-parameterized tests, you need to instantiate them,
109// or bind them to a list of values which will be used as test parameters.
110// You can instantiate them in a different translation module, or even
111// instantiate them several times.
112//
113// Here, we instantiate our tests with a list of two PrimeTable object
114// factory functions:
115INSTANTIATE_TEST_CASE_P(
116    OnTheFlyAndPreCalculated,
117    PrimeTableTest,
118    Values(&CreateOnTheFlyPrimeTable, &CreatePreCalculatedPrimeTable<1000>));
119
120#else
121
122// Google Test may not support value-parameterized tests with some
123// compilers. If we use conditional compilation to compile out all
124// code referring to the gtest_main library, MSVC linker will not link
125// that library at all and consequently complain about missing entry
126// point defined in that library (fatal error LNK1561: entry point
127// must be defined). This dummy test keeps gtest_main linked in.
128TEST(DummyTest, ValueParameterizedTestsAreNotSupportedOnThisPlatform) {}
129
130#endif  // GTEST_HAS_PARAM_TEST
trunk/3rdparty/googletest/googletest/samples/sample8_unittest.cc
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31
32// This sample shows how to test code relying on some global flag variables.
33// Combine() helps with generating all possible combinations of such flags,
34// and each test is given one combination as a parameter.
35
36// Use class definitions to test from this header.
37#include "prime_tables.h"
38
39#include "gtest/gtest.h"
40
41#if GTEST_HAS_COMBINE
42
43// Suppose we want to introduce a new, improved implementation of PrimeTable
44// which combines speed of PrecalcPrimeTable and versatility of
45// OnTheFlyPrimeTable (see prime_tables.h). Inside it instantiates both
46// PrecalcPrimeTable and OnTheFlyPrimeTable and uses the one that is more
47// appropriate under the circumstances. But in low memory conditions, it can be
48// told to instantiate without PrecalcPrimeTable instance at all and use only
49// OnTheFlyPrimeTable.
50class HybridPrimeTable : public PrimeTable {
51 public:
52  HybridPrimeTable(bool force_on_the_fly, int max_precalculated)
53      : on_the_fly_impl_(new OnTheFlyPrimeTable),
54        precalc_impl_(force_on_the_fly ? NULL :
55                          new PreCalculatedPrimeTable(max_precalculated)),
56        max_precalculated_(max_precalculated) {}
57  virtual ~HybridPrimeTable() {
58    delete on_the_fly_impl_;
59    delete precalc_impl_;
60  }
61
62  virtual bool IsPrime(int n) const {
63    if (precalc_impl_ != NULL && n < max_precalculated_)
64      return precalc_impl_->IsPrime(n);
65    else
66      return on_the_fly_impl_->IsPrime(n);
67  }
68
69  virtual int GetNextPrime(int p) const {
70    int next_prime = -1;
71    if (precalc_impl_ != NULL && p < max_precalculated_)
72      next_prime = precalc_impl_->GetNextPrime(p);
73
74    return next_prime != -1 ? next_prime : on_the_fly_impl_->GetNextPrime(p);
75  }
76
77 private:
78  OnTheFlyPrimeTable* on_the_fly_impl_;
79  PreCalculatedPrimeTable* precalc_impl_;
80  int max_precalculated_;
81};
82
83using ::testing::TestWithParam;
84using ::testing::Bool;
85using ::testing::Values;
86using ::testing::Combine;
87
88// To test all code paths for HybridPrimeTable we must test it with numbers
89// both within and outside PreCalculatedPrimeTable's capacity and also with
90// PreCalculatedPrimeTable disabled. We do this by defining fixture which will
91// accept different combinations of parameters for instantiating a
92// HybridPrimeTable instance.
93class PrimeTableTest : public TestWithParam< ::testing::tuple<bool, int> > {
94 protected:
95  virtual void SetUp() {
96    // This can be written as
97    //
98    // bool force_on_the_fly;
99    // int max_precalculated;
100    // tie(force_on_the_fly, max_precalculated) = GetParam();
101    //
102    // once the Google C++ Style Guide allows use of ::std::tr1::tie.
103    //
104    bool force_on_the_fly = ::testing::get<0>(GetParam());
105    int max_precalculated = ::testing::get<1>(GetParam());
106    table_ = new HybridPrimeTable(force_on_the_fly, max_precalculated);
107  }
108  virtual void TearDown() {
109    delete table_;
110    table_ = NULL;
111  }
112  HybridPrimeTable* table_;
113};
114
115TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {
116  // Inside the test body, you can refer to the test parameter by GetParam().
117  // In this case, the test parameter is a PrimeTable interface pointer which
118  // we can use directly.
119  // Please note that you can also save it in the fixture's SetUp() method
120  // or constructor and use saved copy in the tests.
121
122  EXPECT_FALSE(table_->IsPrime(-5));
123  EXPECT_FALSE(table_->IsPrime(0));
124  EXPECT_FALSE(table_->IsPrime(1));
125  EXPECT_FALSE(table_->IsPrime(4));
126  EXPECT_FALSE(table_->IsPrime(6));
127  EXPECT_FALSE(table_->IsPrime(100));
128}
129
130TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {
131  EXPECT_TRUE(table_->IsPrime(2));
132  EXPECT_TRUE(table_->IsPrime(3));
133  EXPECT_TRUE(table_->IsPrime(5));
134  EXPECT_TRUE(table_->IsPrime(7));
135  EXPECT_TRUE(table_->IsPrime(11));
136  EXPECT_TRUE(table_->IsPrime(131));
137}
138
139TEST_P(PrimeTableTest, CanGetNextPrime) {
140  EXPECT_EQ(2, table_->GetNextPrime(0));
141  EXPECT_EQ(3, table_->GetNextPrime(2));
142  EXPECT_EQ(5, table_->GetNextPrime(3));
143  EXPECT_EQ(7, table_->GetNextPrime(5));
144  EXPECT_EQ(11, table_->GetNextPrime(7));
145  EXPECT_EQ(131, table_->GetNextPrime(128));
146}
147
148// In order to run value-parameterized tests, you need to instantiate them,
149// or bind them to a list of values which will be used as test parameters.
150// You can instantiate them in a different translation module, or even
151// instantiate them several times.
152//
153// Here, we instantiate our tests with a list of parameters. We must combine
154// all variations of the boolean flag suppressing PrecalcPrimeTable and some
155// meaningful values for tests. We choose a small value (1), and a value that
156// will put some of the tested numbers beyond the capability of the
157// PrecalcPrimeTable instance and some inside it (10). Combine will produce all
158// possible combinations.
159INSTANTIATE_TEST_CASE_P(MeaningfulTestParameters,
160                        PrimeTableTest,
161                        Combine(Bool(), Values(1, 10)));
162
163#else
164
165// Google Test may not support Combine() with some compilers. If we
166// use conditional compilation to compile out all code referring to
167// the gtest_main library, MSVC linker will not link that library at
168// all and consequently complain about missing entry point defined in
169// that library (fatal error LNK1561: entry point must be
170// defined). This dummy test keeps gtest_main linked in.
171TEST(DummyTest, CombineIsNotSupportedOnThisPlatform) {}
172
173#endif  // GTEST_HAS_COMBINE
trunk/3rdparty/googletest/googletest/samples/sample9_unittest.cc
r0r249096
1// Copyright 2009 Google Inc. All Rights Reserved.
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are
5// met:
6//
7//     * Redistributions of source code must retain the above copyright
8// notice, this list of conditions and the following disclaimer.
9//     * Redistributions in binary form must reproduce the above
10// copyright notice, this list of conditions and the following disclaimer
11// in the documentation and/or other materials provided with the
12// distribution.
13//     * Neither the name of Google Inc. nor the names of its
14// contributors may be used to endorse or promote products derived from
15// this software without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: vladl@google.com (Vlad Losev)
30
31// This sample shows how to use Google Test listener API to implement
32// an alternative console output and how to use the UnitTest reflection API
33// to enumerate test cases and tests and to inspect their results.
34
35#include <stdio.h>
36
37#include "gtest/gtest.h"
38
39using ::testing::EmptyTestEventListener;
40using ::testing::InitGoogleTest;
41using ::testing::Test;
42using ::testing::TestCase;
43using ::testing::TestEventListeners;
44using ::testing::TestInfo;
45using ::testing::TestPartResult;
46using ::testing::UnitTest;
47
48namespace {
49
50// Provides alternative output mode which produces minimal amount of
51// information about tests.
52class TersePrinter : public EmptyTestEventListener {
53 private:
54  // Called before any test activity starts.
55  virtual void OnTestProgramStart(const UnitTest& /* unit_test */) {}
56
57  // Called after all test activities have ended.
58  virtual void OnTestProgramEnd(const UnitTest& unit_test) {
59    fprintf(stdout, "TEST %s\n", unit_test.Passed() ? "PASSED" : "FAILED");
60    fflush(stdout);
61  }
62
63  // Called before a test starts.
64  virtual void OnTestStart(const TestInfo& test_info) {
65    fprintf(stdout,
66            "*** Test %s.%s starting.\n",
67            test_info.test_case_name(),
68            test_info.name());
69    fflush(stdout);
70  }
71
72  // Called after a failed assertion or a SUCCEED() invocation.
73  virtual void OnTestPartResult(const TestPartResult& test_part_result) {
74    fprintf(stdout,
75            "%s in %s:%d\n%s\n",
76            test_part_result.failed() ? "*** Failure" : "Success",
77            test_part_result.file_name(),
78            test_part_result.line_number(),
79            test_part_result.summary());
80    fflush(stdout);
81  }
82
83  // Called after a test ends.
84  virtual void OnTestEnd(const TestInfo& test_info) {
85    fprintf(stdout,
86            "*** Test %s.%s ending.\n",
87            test_info.test_case_name(),
88            test_info.name());
89    fflush(stdout);
90  }
91};  // class TersePrinter
92
93TEST(CustomOutputTest, PrintsMessage) {
94  printf("Printing something from the test body...\n");
95}
96
97TEST(CustomOutputTest, Succeeds) {
98  SUCCEED() << "SUCCEED() has been invoked from here";
99}
100
101TEST(CustomOutputTest, Fails) {
102  EXPECT_EQ(1, 2)
103      << "This test fails in order to demonstrate alternative failure messages";
104}
105
106}  // namespace
107
108int main(int argc, char **argv) {
109  InitGoogleTest(&argc, argv);
110
111  bool terse_output = false;
112  if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 )
113    terse_output = true;
114  else
115    printf("%s\n", "Run this program with --terse_output to change the way "
116           "it prints its output.");
117
118  UnitTest& unit_test = *UnitTest::GetInstance();
119
120  // If we are given the --terse_output command line flag, suppresses the
121  // standard output and attaches own result printer.
122  if (terse_output) {
123    TestEventListeners& listeners = unit_test.listeners();
124
125    // Removes the default console output listener from the list so it will
126    // not receive events from Google Test and won't print any output. Since
127    // this operation transfers ownership of the listener to the caller we
128    // have to delete it as well.
129    delete listeners.Release(listeners.default_result_printer());
130
131    // Adds the custom output listener to the list. It will now receive
132    // events from Google Test and print the alternative output. We don't
133    // have to worry about deleting it since Google Test assumes ownership
134    // over it after adding it to the list.
135    listeners.Append(new TersePrinter);
136  }
137  int ret_val = RUN_ALL_TESTS();
138
139  // This is an example of using the UnitTest reflection API to inspect test
140  // results. Here we discount failures from the tests we expected to fail.
141  int unexpectedly_failed_tests = 0;
142  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
143    const TestCase& test_case = *unit_test.GetTestCase(i);
144    for (int j = 0; j < test_case.total_test_count(); ++j) {
145      const TestInfo& test_info = *test_case.GetTestInfo(j);
146      // Counts failed tests that were not meant to fail (those without
147      // 'Fails' in the name).
148      if (test_info.result()->Failed() &&
149          strcmp(test_info.name(), "Fails") != 0) {
150        unexpectedly_failed_tests++;
151      }
152    }
153  }
154
155  // Test that were meant to fail should not affect the test program outcome.
156  if (unexpectedly_failed_tests == 0)
157    ret_val = 0;
158
159  return ret_val;
160}
trunk/3rdparty/googletest/googletest/scripts/common.py
r0r249096
1# Copyright 2013 Google Inc. All Rights Reserved.
2#
3# Redistribution and use in source and binary forms, with or without
4# modification, are permitted provided that the following conditions are
5# met:
6#
7#     * Redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer.
9#     * Redistributions in binary form must reproduce the above
10# copyright notice, this list of conditions and the following disclaimer
11# in the documentation and/or other materials provided with the
12# distribution.
13#     * Neither the name of Google Inc. nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29"""Shared utilities for writing scripts for Google Test/Mock."""
30
31__author__ = 'wan@google.com (Zhanyong Wan)'
32
33
34import os
35import re
36
37
38# Matches the line from 'svn info .' output that describes what SVN
39# path the current local directory corresponds to.  For example, in
40# a googletest SVN workspace's trunk/test directory, the output will be:
41#
42# URL: https://googletest.googlecode.com/svn/trunk/test
43_SVN_INFO_URL_RE = re.compile(r'^URL: https://(\w+)\.googlecode\.com/svn(.*)')
44
45
46def GetCommandOutput(command):
47  """Runs the shell command and returns its stdout as a list of lines."""
48
49  f = os.popen(command, 'r')
50  lines = [line.strip() for line in f.readlines()]
51  f.close()
52  return lines
53
54
55def GetSvnInfo():
56  """Returns the project name and the current SVN workspace's root path."""
57
58  for line in GetCommandOutput('svn info .'):
59    m = _SVN_INFO_URL_RE.match(line)
60    if m:
61      project = m.group(1)  # googletest or googlemock
62      rel_path = m.group(2)
63      root = os.path.realpath(rel_path.count('/') * '../')
64      return project, root
65
66  return None, None
67
68
69def GetSvnTrunk():
70  """Returns the current SVN workspace's trunk root path."""
71
72  _, root = GetSvnInfo()
73  return root + '/trunk' if root else None
74
75
76def IsInGTestSvn():
77  project, _ = GetSvnInfo()
78  return project == 'googletest'
79
80
81def IsInGMockSvn():
82  project, _ = GetSvnInfo()
83  return project == 'googlemock'
trunk/3rdparty/googletest/googletest/scripts/fuse_gtest_files.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""fuse_gtest_files.py v0.2.0
33Fuses Google Test source code into a .h file and a .cc file.
34
35SYNOPSIS
36       fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
37
38       Scans GTEST_ROOT_DIR for Google Test source code, and generates
39       two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
40       Then you can build your tests by adding OUTPUT_DIR to the include
41       search path and linking with OUTPUT_DIR/gtest/gtest-all.cc.  These
42       two files contain everything you need to use Google Test.  Hence
43       you can "install" Google Test by copying them to wherever you want.
44
45       GTEST_ROOT_DIR can be omitted and defaults to the parent
46       directory of the directory holding this script.
47
48EXAMPLES
49       ./fuse_gtest_files.py fused_gtest
50       ./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
51
52This tool is experimental.  In particular, it assumes that there is no
53conditional inclusion of Google Test headers.  Please report any
54problems to googletestframework@googlegroups.com.  You can read
55http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for
56more information.
57"""
58
59__author__ = 'wan@google.com (Zhanyong Wan)'
60
61import os
62import re
63import sets
64import sys
65
66# We assume that this file is in the scripts/ directory in the Google
67# Test root directory.
68DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
69
70# Regex for matching '#include "gtest/..."'.
71INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"')
72
73# Regex for matching '#include "src/..."'.
74INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
75
76# Where to find the source seed files.
77GTEST_H_SEED = 'include/gtest/gtest.h'
78GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
79GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
80
81# Where to put the generated files.
82GTEST_H_OUTPUT = 'gtest/gtest.h'
83GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
84
85
86def VerifyFileExists(directory, relative_path):
87  """Verifies that the given file exists; aborts on failure.
88
89  relative_path is the file path relative to the given directory.
90  """
91
92  if not os.path.isfile(os.path.join(directory, relative_path)):
93    print 'ERROR: Cannot find %s in directory %s.' % (relative_path,
94                                                      directory)
95    print ('Please either specify a valid project root directory '
96           'or omit it on the command line.')
97    sys.exit(1)
98
99
100def ValidateGTestRootDir(gtest_root):
101  """Makes sure gtest_root points to a valid gtest root directory.
102
103  The function aborts the program on failure.
104  """
105
106  VerifyFileExists(gtest_root, GTEST_H_SEED)
107  VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
108
109
110def VerifyOutputFile(output_dir, relative_path):
111  """Verifies that the given output file path is valid.
112
113  relative_path is relative to the output_dir directory.
114  """
115
116  # Makes sure the output file either doesn't exist or can be overwritten.
117  output_file = os.path.join(output_dir, relative_path)
118  if os.path.exists(output_file):
119    # TODO(wan@google.com): The following user-interaction doesn't
120    # work with automated processes.  We should provide a way for the
121    # Makefile to force overwriting the files.
122    print ('%s already exists in directory %s - overwrite it? (y/N) ' %
123           (relative_path, output_dir))
124    answer = sys.stdin.readline().strip()
125    if answer not in ['y', 'Y']:
126      print 'ABORTED.'
127      sys.exit(1)
128
129  # Makes sure the directory holding the output file exists; creates
130  # it and all its ancestors if necessary.
131  parent_directory = os.path.dirname(output_file)
132  if not os.path.isdir(parent_directory):
133    os.makedirs(parent_directory)
134
135
136def ValidateOutputDir(output_dir):
137  """Makes sure output_dir points to a valid output directory.
138
139  The function aborts the program on failure.
140  """
141
142  VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
143  VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
144
145
146def FuseGTestH(gtest_root, output_dir):
147  """Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
148
149  output_file = file(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
150  processed_files = sets.Set()  # Holds all gtest headers we've processed.
151
152  def ProcessFile(gtest_header_path):
153    """Processes the given gtest header file."""
154
155    # We don't process the same header twice.
156    if gtest_header_path in processed_files:
157      return
158
159    processed_files.add(gtest_header_path)
160
161    # Reads each line in the given gtest header.
162    for line in file(os.path.join(gtest_root, gtest_header_path), 'r'):
163      m = INCLUDE_GTEST_FILE_REGEX.match(line)
164      if m:
165        # It's '#include "gtest/..."' - let's process it recursively.
166        ProcessFile('include/' + m.group(1))
167      else:
168        # Otherwise we copy the line unchanged to the output file.
169        output_file.write(line)
170
171  ProcessFile(GTEST_H_SEED)
172  output_file.close()
173
174
175def FuseGTestAllCcToFile(gtest_root, output_file):
176  """Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
177
178  processed_files = sets.Set()
179
180  def ProcessFile(gtest_source_file):
181    """Processes the given gtest source file."""
182
183    # We don't process the same #included file twice.
184    if gtest_source_file in processed_files:
185      return
186
187    processed_files.add(gtest_source_file)
188
189    # Reads each line in the given gtest source file.
190    for line in file(os.path.join(gtest_root, gtest_source_file), 'r'):
191      m = INCLUDE_GTEST_FILE_REGEX.match(line)
192      if m:
193        if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
194          # It's '#include "gtest/gtest-spi.h"'.  This file is not
195          # #included by "gtest/gtest.h", so we need to process it.
196          ProcessFile(GTEST_SPI_H_SEED)
197        else:
198          # It's '#include "gtest/foo.h"' where foo is not gtest-spi.
199          # We treat it as '#include "gtest/gtest.h"', as all other
200          # gtest headers are being fused into gtest.h and cannot be
201          # #included directly.
202
203          # There is no need to #include "gtest/gtest.h" more than once.
204          if not GTEST_H_SEED in processed_files:
205            processed_files.add(GTEST_H_SEED)
206            output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,))
207      else:
208        m = INCLUDE_SRC_FILE_REGEX.match(line)
209        if m:
210          # It's '#include "src/foo"' - let's process it recursively.
211          ProcessFile(m.group(1))
212        else:
213          output_file.write(line)
214
215  ProcessFile(GTEST_ALL_CC_SEED)
216
217
218def FuseGTestAllCc(gtest_root, output_dir):
219  """Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
220
221  output_file = file(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
222  FuseGTestAllCcToFile(gtest_root, output_file)
223  output_file.close()
224
225
226def FuseGTest(gtest_root, output_dir):
227  """Fuses gtest.h and gtest-all.cc."""
228
229  ValidateGTestRootDir(gtest_root)
230  ValidateOutputDir(output_dir)
231
232  FuseGTestH(gtest_root, output_dir)
233  FuseGTestAllCc(gtest_root, output_dir)
234
235
236def main():
237  argc = len(sys.argv)
238  if argc == 2:
239    # fuse_gtest_files.py OUTPUT_DIR
240    FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
241  elif argc == 3:
242    # fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
243    FuseGTest(sys.argv[1], sys.argv[2])
244  else:
245    print __doc__
246    sys.exit(1)
247
248
249if __name__ == '__main__':
250  main()
trunk/3rdparty/googletest/googletest/scripts/gen_gtest_pred_impl.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2006, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""gen_gtest_pred_impl.py v0.1
33
34Generates the implementation of Google Test predicate assertions and
35accompanying tests.
36
37Usage:
38
39  gen_gtest_pred_impl.py MAX_ARITY
40
41where MAX_ARITY is a positive integer.
42
43The command generates the implementation of up-to MAX_ARITY-ary
44predicate assertions, and writes it to file gtest_pred_impl.h in the
45directory where the script is.  It also generates the accompanying
46unit test in file gtest_pred_impl_unittest.cc.
47"""
48
49__author__ = 'wan@google.com (Zhanyong Wan)'
50
51import os
52import sys
53import time
54
55# Where this script is.
56SCRIPT_DIR = os.path.dirname(sys.argv[0])
57
58# Where to store the generated header.
59HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
60
61# Where to store the generated unit test.
62UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
63
64
65def HeaderPreamble(n):
66  """Returns the preamble for the header file.
67
68  Args:
69    n:  the maximum arity of the predicate macros to be generated.
70  """
71
72  # A map that defines the values used in the preamble template.
73  DEFS = {
74    'today' : time.strftime('%m/%d/%Y'),
75    'year' : time.strftime('%Y'),
76    'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
77    'n' : n
78    }
79
80  return (
81"""// Copyright 2006, Google Inc.
82// All rights reserved.
83//
84// Redistribution and use in source and binary forms, with or without
85// modification, are permitted provided that the following conditions are
86// met:
87//
88//     * Redistributions of source code must retain the above copyright
89// notice, this list of conditions and the following disclaimer.
90//     * Redistributions in binary form must reproduce the above
91// copyright notice, this list of conditions and the following disclaimer
92// in the documentation and/or other materials provided with the
93// distribution.
94//     * Neither the name of Google Inc. nor the names of its
95// contributors may be used to endorse or promote products derived from
96// this software without specific prior written permission.
97//
98// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
99// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
100// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
101// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
102// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
103// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
104// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
105// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
106// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
107// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
108// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
109
110// This file is AUTOMATICALLY GENERATED on %(today)s by command
111// '%(command)s'.  DO NOT EDIT BY HAND!
112//
113// Implements a family of generic predicate assertion macros.
114
115#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
116#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
117
118// Makes sure this header is not included before gtest.h.
119#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
120# error Do not include gtest_pred_impl.h directly.  Include gtest.h instead.
121#endif  // GTEST_INCLUDE_GTEST_GTEST_H_
122
123// This header implements a family of generic predicate assertion
124// macros:
125//
126//   ASSERT_PRED_FORMAT1(pred_format, v1)
127//   ASSERT_PRED_FORMAT2(pred_format, v1, v2)
128//   ...
129//
130// where pred_format is a function or functor that takes n (in the
131// case of ASSERT_PRED_FORMATn) values and their source expression
132// text, and returns a testing::AssertionResult.  See the definition
133// of ASSERT_EQ in gtest.h for an example.
134//
135// If you don't care about formatting, you can use the more
136// restrictive version:
137//
138//   ASSERT_PRED1(pred, v1)
139//   ASSERT_PRED2(pred, v1, v2)
140//   ...
141//
142// where pred is an n-ary function or functor that returns bool,
143// and the values v1, v2, ..., must support the << operator for
144// streaming to std::ostream.
145//
146// We also define the EXPECT_* variations.
147//
148// For now we only support predicates whose arity is at most %(n)s.
149// Please email googletestframework@googlegroups.com if you need
150// support for higher arities.
151
152// GTEST_ASSERT_ is the basic statement to which all of the assertions
153// in this file reduce.  Don't use this in your code.
154
155#define GTEST_ASSERT_(expression, on_failure) \\
156  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
157  if (const ::testing::AssertionResult gtest_ar = (expression)) \\
158    ; \\
159  else \\
160    on_failure(gtest_ar.failure_message())
161""" % DEFS)
162
163
164def Arity(n):
165  """Returns the English name of the given arity."""
166
167  if n < 0:
168    return None
169  elif n <= 3:
170    return ['nullary', 'unary', 'binary', 'ternary'][n]
171  else:
172    return '%s-ary' % n
173
174
175def Title(word):
176  """Returns the given word in title case.  The difference between
177  this and string's title() method is that Title('4-ary') is '4-ary'
178  while '4-ary'.title() is '4-Ary'."""
179
180  return word[0].upper() + word[1:]
181
182
183def OneTo(n):
184  """Returns the list [1, 2, 3, ..., n]."""
185
186  return range(1, n + 1)
187
188
189def Iter(n, format, sep=''):
190  """Given a positive integer n, a format string that contains 0 or
191  more '%s' format specs, and optionally a separator string, returns
192  the join of n strings, each formatted with the format string on an
193  iterator ranged from 1 to n.
194
195  Example:
196
197  Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
198  """
199
200  # How many '%s' specs are in format?
201  spec_count = len(format.split('%s')) - 1
202  return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
203
204
205def ImplementationForArity(n):
206  """Returns the implementation of n-ary predicate assertions."""
207
208  # A map the defines the values used in the implementation template.
209  DEFS = {
210    'n' : str(n),
211    'vs' : Iter(n, 'v%s', sep=', '),
212    'vts' : Iter(n, '#v%s', sep=', '),
213    'arity' : Arity(n),
214    'Arity' : Title(Arity(n))
215    }
216
217  impl = """
218
219// Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
220// this in your code.
221template <typename Pred""" % DEFS
222
223  impl += Iter(n, """,
224          typename T%s""")
225
226  impl += """>
227AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
228
229  impl += Iter(n, """,
230                                  const char* e%s""")
231
232  impl += """,
233                                  Pred pred"""
234
235  impl += Iter(n, """,
236                                  const T%s& v%s""")
237
238  impl += """) {
239  if (pred(%(vs)s)) return AssertionSuccess();
240
241""" % DEFS
242
243  impl += '  return AssertionFailure() << pred_text << "("'
244
245  impl += Iter(n, """
246                            << e%s""", sep=' << ", "')
247
248  impl += ' << ") evaluates to false, where"'
249
250  impl += Iter(n, """
251                            << "\\n" << e%s << " evaluates to " << v%s""")
252
253  impl += """;
254}
255
256// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
257// Don't use this in your code.
258#define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
259  GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\
260                on_failure)
261
262// Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
263// this in your code.
264#define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
265  GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
266
267  impl += Iter(n, """, \\
268                                             #v%s""")
269
270  impl += """, \\
271                                             pred"""
272
273  impl += Iter(n, """, \\
274                                             v%s""")
275
276  impl += """), on_failure)
277
278// %(Arity)s predicate assertion macros.
279#define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
280  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
281#define EXPECT_PRED%(n)s(pred, %(vs)s) \\
282  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
283#define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
284  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
285#define ASSERT_PRED%(n)s(pred, %(vs)s) \\
286  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
287
288""" % DEFS
289
290  return impl
291
292
293def HeaderPostamble():
294  """Returns the postamble for the header file."""
295
296  return """
297
298#endif  // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
299"""
300
301
302def GenerateFile(path, content):
303  """Given a file path and a content string, overwrites it with the
304  given content."""
305
306  print 'Updating file %s . . .' % path
307
308  f = file(path, 'w+')
309  print >>f, content,
310  f.close()
311
312  print 'File %s has been updated.' % path
313
314
315def GenerateHeader(n):
316  """Given the maximum arity n, updates the header file that implements
317  the predicate assertions."""
318
319  GenerateFile(HEADER,
320               HeaderPreamble(n)
321               + ''.join([ImplementationForArity(i) for i in OneTo(n)])
322               + HeaderPostamble())
323
324
325def UnitTestPreamble():
326  """Returns the preamble for the unit test file."""
327
328  # A map that defines the values used in the preamble template.
329  DEFS = {
330    'today' : time.strftime('%m/%d/%Y'),
331    'year' : time.strftime('%Y'),
332    'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
333    }
334
335  return (
336"""// Copyright 2006, Google Inc.
337// All rights reserved.
338//
339// Redistribution and use in source and binary forms, with or without
340// modification, are permitted provided that the following conditions are
341// met:
342//
343//     * Redistributions of source code must retain the above copyright
344// notice, this list of conditions and the following disclaimer.
345//     * Redistributions in binary form must reproduce the above
346// copyright notice, this list of conditions and the following disclaimer
347// in the documentation and/or other materials provided with the
348// distribution.
349//     * Neither the name of Google Inc. nor the names of its
350// contributors may be used to endorse or promote products derived from
351// this software without specific prior written permission.
352//
353// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
354// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
355// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
356// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
357// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
358// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
359// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
360// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
361// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
362// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
363// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
364
365// This file is AUTOMATICALLY GENERATED on %(today)s by command
366// '%(command)s'.  DO NOT EDIT BY HAND!
367
368// Regression test for gtest_pred_impl.h
369//
370// This file is generated by a script and quite long.  If you intend to
371// learn how Google Test works by reading its unit tests, read
372// gtest_unittest.cc instead.
373//
374// This is intended as a regression test for the Google Test predicate
375// assertions.  We compile it as part of the gtest_unittest target
376// only to keep the implementation tidy and compact, as it is quite
377// involved to set up the stage for testing Google Test using Google
378// Test itself.
379//
380// Currently, gtest_unittest takes ~11 seconds to run in the testing
381// daemon.  In the future, if it grows too large and needs much more
382// time to finish, we should consider separating this file into a
383// stand-alone regression test.
384
385#include <iostream>
386
387#include "gtest/gtest.h"
388#include "gtest/gtest-spi.h"
389
390// A user-defined data type.
391struct Bool {
392  explicit Bool(int val) : value(val != 0) {}
393
394  bool operator>(int n) const { return value > Bool(n).value; }
395
396  Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
397
398  bool operator==(const Bool& rhs) const { return value == rhs.value; }
399
400  bool value;
401};
402
403// Enables Bool to be used in assertions.
404std::ostream& operator<<(std::ostream& os, const Bool& x) {
405  return os << (x.value ? "true" : "false");
406}
407
408""" % DEFS)
409
410
411def TestsForArity(n):
412  """Returns the tests for n-ary predicate assertions."""
413
414  # A map that defines the values used in the template for the tests.
415  DEFS = {
416    'n' : n,
417    'es' : Iter(n, 'e%s', sep=', '),
418    'vs' : Iter(n, 'v%s', sep=', '),
419    'vts' : Iter(n, '#v%s', sep=', '),
420    'tvs' : Iter(n, 'T%s v%s', sep=', '),
421    'int_vs' : Iter(n, 'int v%s', sep=', '),
422    'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
423    'types' : Iter(n, 'typename T%s', sep=', '),
424    'v_sum' : Iter(n, 'v%s', sep=' + '),
425    'arity' : Arity(n),
426    'Arity' : Title(Arity(n)),
427    }
428
429  tests = (
430"""// Sample functions/functors for testing %(arity)s predicate assertions.
431
432// A %(arity)s predicate function.
433template <%(types)s>
434bool PredFunction%(n)s(%(tvs)s) {
435  return %(v_sum)s > 0;
436}
437
438// The following two functions are needed to circumvent a bug in
439// gcc 2.95.3, which sometimes has problem with the above template
440// function.
441bool PredFunction%(n)sInt(%(int_vs)s) {
442  return %(v_sum)s > 0;
443}
444bool PredFunction%(n)sBool(%(Bool_vs)s) {
445  return %(v_sum)s > 0;
446}
447""" % DEFS)
448
449  tests += """
450// A %(arity)s predicate functor.
451struct PredFunctor%(n)s {
452  template <%(types)s>
453  bool operator()(""" % DEFS
454
455  tests += Iter(n, 'const T%s& v%s', sep=""",
456                  """)
457
458  tests += """) {
459    return %(v_sum)s > 0;
460  }
461};
462""" % DEFS
463
464  tests += """
465// A %(arity)s predicate-formatter function.
466template <%(types)s>
467testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
468
469  tests += Iter(n, 'const char* e%s', sep=""",
470                                             """)
471
472  tests += Iter(n, """,
473                                             const T%s& v%s""")
474
475  tests += """) {
476  if (PredFunction%(n)s(%(vs)s))
477    return testing::AssertionSuccess();
478
479  return testing::AssertionFailure()
480      << """ % DEFS
481
482  tests += Iter(n, 'e%s', sep=' << " + " << ')
483
484  tests += """
485      << " is expected to be positive, but evaluates to "
486      << %(v_sum)s << ".";
487}
488""" % DEFS
489
490  tests += """
491// A %(arity)s predicate-formatter functor.
492struct PredFormatFunctor%(n)s {
493  template <%(types)s>
494  testing::AssertionResult operator()(""" % DEFS
495
496  tests += Iter(n, 'const char* e%s', sep=""",
497                                      """)
498
499  tests += Iter(n, """,
500                                      const T%s& v%s""")
501
502  tests += """) const {
503    return PredFormatFunction%(n)s(%(es)s, %(vs)s);
504  }
505};
506""" % DEFS
507
508  tests += """
509// Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
510
511class Predicate%(n)sTest : public testing::Test {
512 protected:
513  virtual void SetUp() {
514    expected_to_finish_ = true;
515    finished_ = false;""" % DEFS
516
517  tests += """
518    """ + Iter(n, 'n%s_ = ') + """0;
519  }
520"""
521
522  tests += """
523  virtual void TearDown() {
524    // Verifies that each of the predicate's arguments was evaluated
525    // exactly once."""
526
527  tests += ''.join(["""
528    EXPECT_EQ(1, n%s_) <<
529        "The predicate assertion didn't evaluate argument %s "
530        "exactly once.";""" % (i, i + 1) for i in OneTo(n)])
531
532  tests += """
533
534    // Verifies that the control flow in the test function is expected.
535    if (expected_to_finish_ && !finished_) {
536      FAIL() << "The predicate assertion unexpactedly aborted the test.";
537    } else if (!expected_to_finish_ && finished_) {
538      FAIL() << "The failed predicate assertion didn't abort the test "
539                "as expected.";
540    }
541  }
542
543  // true iff the test function is expected to run to finish.
544  static bool expected_to_finish_;
545
546  // true iff the test function did run to finish.
547  static bool finished_;
548""" % DEFS
549
550  tests += Iter(n, """
551  static int n%s_;""")
552
553  tests += """
554};
555
556bool Predicate%(n)sTest::expected_to_finish_;
557bool Predicate%(n)sTest::finished_;
558""" % DEFS
559
560  tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
561""") % DEFS
562
563  tests += """
564typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
565typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
566typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
567typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
568""" % DEFS
569
570  def GenTest(use_format, use_assert, expect_failure,
571              use_functor, use_user_type):
572    """Returns the test for a predicate assertion macro.
573
574    Args:
575      use_format:     true iff the assertion is a *_PRED_FORMAT*.
576      use_assert:     true iff the assertion is a ASSERT_*.
577      expect_failure: true iff the assertion is expected to fail.
578      use_functor:    true iff the first argument of the assertion is
579                      a functor (as opposed to a function)
580      use_user_type:  true iff the predicate functor/function takes
581                      argument(s) of a user-defined type.
582
583    Example:
584
585      GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
586      of a successful EXPECT_PRED_FORMATn() that takes a functor
587      whose arguments have built-in types."""
588
589    if use_assert:
590      assrt = 'ASSERT'  # 'assert' is reserved, so we cannot use
591                        # that identifier here.
592    else:
593      assrt = 'EXPECT'
594
595    assertion = assrt + '_PRED'
596
597    if use_format:
598      pred_format = 'PredFormat'
599      assertion += '_FORMAT'
600    else:
601      pred_format = 'Pred'
602
603    assertion += '%(n)s' % DEFS
604
605    if use_functor:
606      pred_format_type = 'functor'
607      pred_format += 'Functor%(n)s()'
608    else:
609      pred_format_type = 'function'
610      pred_format += 'Function%(n)s'
611      if not use_format:
612        if use_user_type:
613          pred_format += 'Bool'
614        else:
615          pred_format += 'Int'
616
617    test_name = pred_format_type.title()
618
619    if use_user_type:
620      arg_type = 'user-defined type (Bool)'
621      test_name += 'OnUserType'
622      if expect_failure:
623        arg = 'Bool(n%s_++)'
624      else:
625        arg = 'Bool(++n%s_)'
626    else:
627      arg_type = 'built-in type (int)'
628      test_name += 'OnBuiltInType'
629      if expect_failure:
630        arg = 'n%s_++'
631      else:
632        arg = '++n%s_'
633
634    if expect_failure:
635      successful_or_failed = 'failed'
636      expected_or_not = 'expected.'
637      test_name +=  'Failure'
638    else:
639      successful_or_failed = 'successful'
640      expected_or_not = 'UNEXPECTED!'
641      test_name +=  'Success'
642
643    # A map that defines the values used in the test template.
644    defs = DEFS.copy()
645    defs.update({
646      'assert' : assrt,
647      'assertion' : assertion,
648      'test_name' : test_name,
649      'pf_type' : pred_format_type,
650      'pf' : pred_format,
651      'arg_type' : arg_type,
652      'arg' : arg,
653      'successful' : successful_or_failed,
654      'expected' : expected_or_not,
655      })
656
657    test = """
658// Tests a %(successful)s %(assertion)s where the
659// predicate-formatter is a %(pf_type)s on a %(arg_type)s.
660TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
661
662    indent = (len(assertion) + 3)*' '
663    extra_indent = ''
664
665    if expect_failure:
666      extra_indent = '  '
667      if use_assert:
668        test += """
669  expected_to_finish_ = false;
670  EXPECT_FATAL_FAILURE({  // NOLINT"""
671      else:
672        test += """
673  EXPECT_NONFATAL_FAILURE({  // NOLINT"""
674
675    test += '\n' + extra_indent + """  %(assertion)s(%(pf)s""" % defs
676
677    test = test % defs
678    test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
679    test += ');\n' + extra_indent + '  finished_ = true;\n'
680
681    if expect_failure:
682      test += '  }, "");\n'
683
684    test += '}\n'
685    return test
686
687  # Generates tests for all 2**6 = 64 combinations.
688  tests += ''.join([GenTest(use_format, use_assert, expect_failure,
689                            use_functor, use_user_type)
690                    for use_format in [0, 1]
691                    for use_assert in [0, 1]
692                    for expect_failure in [0, 1]
693                    for use_functor in [0, 1]
694                    for use_user_type in [0, 1]
695                    ])
696
697  return tests
698
699
700def UnitTestPostamble():
701  """Returns the postamble for the tests."""
702
703  return ''
704
705
706def GenerateUnitTest(n):
707  """Returns the tests for up-to n-ary predicate assertions."""
708
709  GenerateFile(UNIT_TEST,
710               UnitTestPreamble()
711               + ''.join([TestsForArity(i) for i in OneTo(n)])
712               + UnitTestPostamble())
713
714
715def _Main():
716  """The entry point of the script.  Generates the header file and its
717  unit test."""
718
719  if len(sys.argv) != 2:
720    print __doc__
721    print 'Author: ' + __author__
722    sys.exit(1)
723
724  n = int(sys.argv[1])
725  GenerateHeader(n)
726  GenerateUnitTest(n)
727
728
729if __name__ == '__main__':
730  _Main()
trunk/3rdparty/googletest/googletest/scripts/gtest-config.in
r0r249096
1#!/bin/sh
2
3# These variables are automatically filled in by the configure script.
4name="@PACKAGE_TARNAME@"
5version="@PACKAGE_VERSION@"
6
7show_usage()
8{
9  echo "Usage: gtest-config [OPTIONS...]"
10}
11
12show_help()
13{
14  show_usage
15  cat <<\EOF
16
17The `gtest-config' script provides access to the necessary compile and linking
18flags to connect with Google C++ Testing Framework, both in a build prior to
19installation, and on the system proper after installation. The installation
20overrides may be issued in combination with any other queries, but will only
21affect installation queries if called on a built but not installed gtest. The
22installation queries may not be issued with any other types of queries, and
23only one installation query may be made at a time. The version queries and
24compiler flag queries may be combined as desired but not mixed. Different
25version queries are always combined with logical "and" semantics, and only the
26last of any particular query is used while all previous ones ignored. All
27versions must be specified as a sequence of numbers separated by periods.
28Compiler flag queries output the union of the sets of flags when combined.
29
30 Examples:
31  gtest-config --min-version=1.0 || echo "Insufficient Google Test version."
32
33  g++ $(gtest-config --cppflags --cxxflags) -o foo.o -c foo.cpp
34  g++ $(gtest-config --ldflags --libs) -o foo foo.o
35
36  # When using a built but not installed Google Test:
37  g++ $(../../my_gtest_build/scripts/gtest-config ...) ...
38
39  # When using an installed Google Test, but with installation overrides:
40  export GTEST_PREFIX="/opt"
41  g++ $(gtest-config --libdir="/opt/lib64" ...) ...
42
43 Help:
44  --usage                    brief usage information
45  --help                     display this help message
46
47 Installation Overrides:
48  --prefix=<dir>             overrides the installation prefix
49  --exec-prefix=<dir>        overrides the executable installation prefix
50  --libdir=<dir>             overrides the library installation prefix
51  --includedir=<dir>         overrides the header file installation prefix
52
53 Installation Queries:
54  --prefix                   installation prefix
55  --exec-prefix              executable installation prefix
56  --libdir                   library installation directory
57  --includedir               header file installation directory
58  --version                  the version of the Google Test installation
59
60 Version Queries:
61  --min-version=VERSION      return 0 if the version is at least VERSION
62  --exact-version=VERSION    return 0 if the version is exactly VERSION
63  --max-version=VERSION      return 0 if the version is at most VERSION
64
65 Compilation Flag Queries:
66  --cppflags                 compile flags specific to the C-like preprocessors
67  --cxxflags                 compile flags appropriate for C++ programs
68  --ldflags                  linker flags
69  --libs                     libraries for linking
70
71EOF
72}
73
74# This function bounds our version with a min and a max. It uses some clever
75# POSIX-compliant variable expansion to portably do all the work in the shell
76# and avoid any dependency on a particular "sed" or "awk" implementation.
77# Notable is that it will only ever compare the first 3 components of versions.
78# Further components will be cleanly stripped off. All versions must be
79# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and
80# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should
81# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than
82# continuing to maintain our own shell version.
83check_versions()
84{
85  major_version=${version%%.*}
86  minor_version="0"
87  point_version="0"
88  if test "${version#*.}" != "${version}"; then
89    minor_version=${version#*.}
90    minor_version=${minor_version%%.*}
91  fi
92  if test "${version#*.*.}" != "${version}"; then
93    point_version=${version#*.*.}
94    point_version=${point_version%%.*}
95  fi
96
97  min_version="$1"
98  min_major_version=${min_version%%.*}
99  min_minor_version="0"
100  min_point_version="0"
101  if test "${min_version#*.}" != "${min_version}"; then
102    min_minor_version=${min_version#*.}
103    min_minor_version=${min_minor_version%%.*}
104  fi
105  if test "${min_version#*.*.}" != "${min_version}"; then
106    min_point_version=${min_version#*.*.}
107    min_point_version=${min_point_version%%.*}
108  fi
109
110  max_version="$2"
111  max_major_version=${max_version%%.*}
112  max_minor_version="0"
113  max_point_version="0"
114  if test "${max_version#*.}" != "${max_version}"; then
115    max_minor_version=${max_version#*.}
116    max_minor_version=${max_minor_version%%.*}
117  fi
118  if test "${max_version#*.*.}" != "${max_version}"; then
119    max_point_version=${max_version#*.*.}
120    max_point_version=${max_point_version%%.*}
121  fi
122
123  test $(($major_version)) -lt $(($min_major_version)) && exit 1
124  if test $(($major_version)) -eq $(($min_major_version)); then
125    test $(($minor_version)) -lt $(($min_minor_version)) && exit 1
126    if test $(($minor_version)) -eq $(($min_minor_version)); then
127      test $(($point_version)) -lt $(($min_point_version)) && exit 1
128    fi
129  fi
130
131  test $(($major_version)) -gt $(($max_major_version)) && exit 1
132  if test $(($major_version)) -eq $(($max_major_version)); then
133    test $(($minor_version)) -gt $(($max_minor_version)) && exit 1
134    if test $(($minor_version)) -eq $(($max_minor_version)); then
135      test $(($point_version)) -gt $(($max_point_version)) && exit 1
136    fi
137  fi
138
139  exit 0
140}
141
142# Show the usage line when no arguments are specified.
143if test $# -eq 0; then
144  show_usage
145  exit 1
146fi
147
148while test $# -gt 0; do
149  case $1 in
150    --usage)          show_usage;         exit 0;;
151    --help)           show_help;          exit 0;;
152
153    # Installation overrides
154    --prefix=*)       GTEST_PREFIX=${1#--prefix=};;
155    --exec-prefix=*)  GTEST_EXEC_PREFIX=${1#--exec-prefix=};;
156    --libdir=*)       GTEST_LIBDIR=${1#--libdir=};;
157    --includedir=*)   GTEST_INCLUDEDIR=${1#--includedir=};;
158
159    # Installation queries
160    --prefix|--exec-prefix|--libdir|--includedir|--version)
161      if test -n "${do_query}"; then
162        show_usage
163        exit 1
164      fi
165      do_query=${1#--}
166      ;;
167
168    # Version checking
169    --min-version=*)
170      do_check_versions=yes
171      min_version=${1#--min-version=}
172      ;;
173    --max-version=*)
174      do_check_versions=yes
175      max_version=${1#--max-version=}
176      ;;
177    --exact-version=*)
178      do_check_versions=yes
179      exact_version=${1#--exact-version=}
180      ;;
181
182    # Compiler flag output
183    --cppflags)       echo_cppflags=yes;;
184    --cxxflags)       echo_cxxflags=yes;;
185    --ldflags)        echo_ldflags=yes;;
186    --libs)           echo_libs=yes;;
187
188    # Everything else is an error
189    *)                show_usage;         exit 1;;
190  esac
191  shift
192done
193
194# These have defaults filled in by the configure script but can also be
195# overridden by environment variables or command line parameters.
196prefix="${GTEST_PREFIX:-@prefix@}"
197exec_prefix="${GTEST_EXEC_PREFIX:-@exec_prefix@}"
198libdir="${GTEST_LIBDIR:-@libdir@}"
199includedir="${GTEST_INCLUDEDIR:-@includedir@}"
200
201# We try and detect if our binary is not located at its installed location. If
202# it's not, we provide variables pointing to the source and build tree rather
203# than to the install tree. This allows building against a just-built gtest
204# rather than an installed gtest.
205bindir="@bindir@"
206this_relative_bindir=`dirname $0`
207this_bindir=`cd ${this_relative_bindir}; pwd -P`
208if test "${this_bindir}" = "${this_bindir%${bindir}}"; then
209  # The path to the script doesn't end in the bindir sequence from Autoconf,
210  # assume that we are in a build tree.
211  build_dir=`dirname ${this_bindir}`
212  src_dir=`cd ${this_bindir}; cd @top_srcdir@; pwd -P`
213
214  # TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we
215  # should work to remove it, and/or remove libtool altogether, replacing it
216  # with direct references to the library and a link path.
217  gtest_libs="${build_dir}/lib/libgtest.la @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
218  gtest_ldflags=""
219
220  # We provide hooks to include from either the source or build dir, where the
221  # build dir is always preferred. This will potentially allow us to write
222  # build rules for generated headers and have them automatically be preferred
223  # over provided versions.
224  gtest_cppflags="-I${build_dir}/include -I${src_dir}/include"
225  gtest_cxxflags="@PTHREAD_CFLAGS@"
226else
227  # We're using an installed gtest, although it may be staged under some
228  # prefix. Assume (as our own libraries do) that we can resolve the prefix,
229  # and are present in the dynamic link paths.
230  gtest_ldflags="-L${libdir}"
231  gtest_libs="-l${name} @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
232  gtest_cppflags="-I${includedir}"
233  gtest_cxxflags="@PTHREAD_CFLAGS@"
234fi
235
236# Do an installation query if requested.
237if test -n "$do_query"; then
238  case $do_query in
239    prefix)           echo $prefix;       exit 0;;
240    exec-prefix)      echo $exec_prefix;  exit 0;;
241    libdir)           echo $libdir;       exit 0;;
242    includedir)       echo $includedir;   exit 0;;
243    version)          echo $version;      exit 0;;
244    *)                show_usage;         exit 1;;
245  esac
246fi
247
248# Do a version check if requested.
249if test "$do_check_versions" = "yes"; then
250  # Make sure we didn't receive a bad combination of parameters.
251  test "$echo_cppflags" = "yes" && show_usage && exit 1
252  test "$echo_cxxflags" = "yes" && show_usage && exit 1
253  test "$echo_ldflags" = "yes"  && show_usage && exit 1
254  test "$echo_libs" = "yes"     && show_usage && exit 1
255
256  if test "$exact_version" != ""; then
257    check_versions $exact_version $exact_version
258    # unreachable
259  else
260    check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999}
261    # unreachable
262  fi
263fi
264
265# Do the output in the correct order so that these can be used in-line of
266# a compiler invocation.
267output=""
268test "$echo_cppflags" = "yes" && output="$output $gtest_cppflags"
269test "$echo_cxxflags" = "yes" && output="$output $gtest_cxxflags"
270test "$echo_ldflags" = "yes"  && output="$output $gtest_ldflags"
271test "$echo_libs" = "yes"     && output="$output $gtest_libs"
272echo $output
273
274exit 0
trunk/3rdparty/googletest/googletest/scripts/pump.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""pump v0.2.0 - Pretty Useful for Meta Programming.
33
34A tool for preprocessor meta programming.  Useful for generating
35repetitive boilerplate code.  Especially useful for writing C++
36classes, functions, macros, and templates that need to work with
37various number of arguments.
38
39USAGE:
40       pump.py SOURCE_FILE
41
42EXAMPLES:
43       pump.py foo.cc.pump
44         Converts foo.cc.pump to foo.cc.
45
46GRAMMAR:
47       CODE ::= ATOMIC_CODE*
48       ATOMIC_CODE ::= $var ID = EXPRESSION
49           | $var ID = [[ CODE ]]
50           | $range ID EXPRESSION..EXPRESSION
51           | $for ID SEPARATOR [[ CODE ]]
52           | $($)
53           | $ID
54           | $(EXPRESSION)
55           | $if EXPRESSION [[ CODE ]] ELSE_BRANCH
56           | [[ CODE ]]
57           | RAW_CODE
58       SEPARATOR ::= RAW_CODE | EMPTY
59       ELSE_BRANCH ::= $else [[ CODE ]]
60           | $elif EXPRESSION [[ CODE ]] ELSE_BRANCH
61           | EMPTY
62       EXPRESSION has Python syntax.
63"""
64
65__author__ = 'wan@google.com (Zhanyong Wan)'
66
67import os
68import re
69import sys
70
71
72TOKEN_TABLE = [
73    (re.compile(r'\$var\s+'), '$var'),
74    (re.compile(r'\$elif\s+'), '$elif'),
75    (re.compile(r'\$else\s+'), '$else'),
76    (re.compile(r'\$for\s+'), '$for'),
77    (re.compile(r'\$if\s+'), '$if'),
78    (re.compile(r'\$range\s+'), '$range'),
79    (re.compile(r'\$[_A-Za-z]\w*'), '$id'),
80    (re.compile(r'\$\(\$\)'), '$($)'),
81    (re.compile(r'\$'), '$'),
82    (re.compile(r'\[\[\n?'), '[['),
83    (re.compile(r'\]\]\n?'), ']]'),
84    ]
85
86
87class Cursor:
88  """Represents a position (line and column) in a text file."""
89
90  def __init__(self, line=-1, column=-1):
91    self.line = line
92    self.column = column
93
94  def __eq__(self, rhs):
95    return self.line == rhs.line and self.column == rhs.column
96
97  def __ne__(self, rhs):
98    return not self == rhs
99
100  def __lt__(self, rhs):
101    return self.line < rhs.line or (
102        self.line == rhs.line and self.column < rhs.column)
103
104  def __le__(self, rhs):
105    return self < rhs or self == rhs
106
107  def __gt__(self, rhs):
108    return rhs < self
109
110  def __ge__(self, rhs):
111    return rhs <= self
112
113  def __str__(self):
114    if self == Eof():
115      return 'EOF'
116    else:
117      return '%s(%s)' % (self.line + 1, self.column)
118
119  def __add__(self, offset):
120    return Cursor(self.line, self.column + offset)
121
122  def __sub__(self, offset):
123    return Cursor(self.line, self.column - offset)
124
125  def Clone(self):
126    """Returns a copy of self."""
127
128    return Cursor(self.line, self.column)
129
130
131# Special cursor to indicate the end-of-file.
132def Eof():
133  """Returns the special cursor to denote the end-of-file."""
134  return Cursor(-1, -1)
135
136
137class Token:
138  """Represents a token in a Pump source file."""
139
140  def __init__(self, start=None, end=None, value=None, token_type=None):
141    if start is None:
142      self.start = Eof()
143    else:
144      self.start = start
145    if end is None:
146      self.end = Eof()
147    else:
148      self.end = end
149    self.value = value
150    self.token_type = token_type
151
152  def __str__(self):
153    return 'Token @%s: \'%s\' type=%s' % (
154        self.start, self.value, self.token_type)
155
156  def Clone(self):
157    """Returns a copy of self."""
158
159    return Token(self.start.Clone(), self.end.Clone(), self.value,
160                 self.token_type)
161
162
163def StartsWith(lines, pos, string):
164  """Returns True iff the given position in lines starts with 'string'."""
165
166  return lines[pos.line][pos.column:].startswith(string)
167
168
169def FindFirstInLine(line, token_table):
170  best_match_start = -1
171  for (regex, token_type) in token_table:
172    m = regex.search(line)
173    if m:
174      # We found regex in lines
175      if best_match_start < 0 or m.start() < best_match_start:
176        best_match_start = m.start()
177        best_match_length = m.end() - m.start()
178        best_match_token_type = token_type
179
180  if best_match_start < 0:
181    return None
182
183  return (best_match_start, best_match_length, best_match_token_type)
184
185
186def FindFirst(lines, token_table, cursor):
187  """Finds the first occurrence of any string in strings in lines."""
188
189  start = cursor.Clone()
190  cur_line_number = cursor.line
191  for line in lines[start.line:]:
192    if cur_line_number == start.line:
193      line = line[start.column:]
194    m = FindFirstInLine(line, token_table)
195    if m:
196      # We found a regex in line.
197      (start_column, length, token_type) = m
198      if cur_line_number == start.line:
199        start_column += start.column
200      found_start = Cursor(cur_line_number, start_column)
201      found_end = found_start + length
202      return MakeToken(lines, found_start, found_end, token_type)
203    cur_line_number += 1
204  # We failed to find str in lines
205  return None
206
207
208def SubString(lines, start, end):
209  """Returns a substring in lines."""
210
211  if end == Eof():
212    end = Cursor(len(lines) - 1, len(lines[-1]))
213
214  if start >= end:
215    return ''
216
217  if start.line == end.line:
218    return lines[start.line][start.column:end.column]
219
220  result_lines = ([lines[start.line][start.column:]] +
221                  lines[start.line + 1:end.line] +
222                  [lines[end.line][:end.column]])
223  return ''.join(result_lines)
224
225
226def StripMetaComments(str):
227  """Strip meta comments from each line in the given string."""
228
229  # First, completely remove lines containing nothing but a meta
230  # comment, including the trailing \n.
231  str = re.sub(r'^\s*\$\$.*\n', '', str)
232
233  # Then, remove meta comments from contentful lines.
234  return re.sub(r'\s*\$\$.*', '', str)
235
236
237def MakeToken(lines, start, end, token_type):
238  """Creates a new instance of Token."""
239
240  return Token(start, end, SubString(lines, start, end), token_type)
241
242
243def ParseToken(lines, pos, regex, token_type):
244  line = lines[pos.line][pos.column:]
245  m = regex.search(line)
246  if m and not m.start():
247    return MakeToken(lines, pos, pos + m.end(), token_type)
248  else:
249    print 'ERROR: %s expected at %s.' % (token_type, pos)
250    sys.exit(1)
251
252
253ID_REGEX = re.compile(r'[_A-Za-z]\w*')
254EQ_REGEX = re.compile(r'=')
255REST_OF_LINE_REGEX = re.compile(r'.*?(?=$|\$\$)')
256OPTIONAL_WHITE_SPACES_REGEX = re.compile(r'\s*')
257WHITE_SPACE_REGEX = re.compile(r'\s')
258DOT_DOT_REGEX = re.compile(r'\.\.')
259
260
261def Skip(lines, pos, regex):
262  line = lines[pos.line][pos.column:]
263  m = re.search(regex, line)
264  if m and not m.start():
265    return pos + m.end()
266  else:
267    return pos
268
269
270def SkipUntil(lines, pos, regex, token_type):
271  line = lines[pos.line][pos.column:]
272  m = re.search(regex, line)
273  if m:
274    return pos + m.start()
275  else:
276    print ('ERROR: %s expected on line %s after column %s.' %
277           (token_type, pos.line + 1, pos.column))
278    sys.exit(1)
279
280
281def ParseExpTokenInParens(lines, pos):
282  def ParseInParens(pos):
283    pos = Skip(lines, pos, OPTIONAL_WHITE_SPACES_REGEX)
284    pos = Skip(lines, pos, r'\(')
285    pos = Parse(pos)
286    pos = Skip(lines, pos, r'\)')
287    return pos
288
289  def Parse(pos):
290    pos = SkipUntil(lines, pos, r'\(|\)', ')')
291    if SubString(lines, pos, pos + 1) == '(':
292      pos = Parse(pos + 1)
293      pos = Skip(lines, pos, r'\)')
294      return Parse(pos)
295    else:
296      return pos
297
298  start = pos.Clone()
299  pos = ParseInParens(pos)
300  return MakeToken(lines, start, pos, 'exp')
301
302
303def RStripNewLineFromToken(token):
304  if token.value.endswith('\n'):
305    return Token(token.start, token.end, token.value[:-1], token.token_type)
306  else:
307    return token
308
309
310def TokenizeLines(lines, pos):
311  while True:
312    found = FindFirst(lines, TOKEN_TABLE, pos)
313    if not found:
314      yield MakeToken(lines, pos, Eof(), 'code')
315      return
316
317    if found.start == pos:
318      prev_token = None
319      prev_token_rstripped = None
320    else:
321      prev_token = MakeToken(lines, pos, found.start, 'code')
322      prev_token_rstripped = RStripNewLineFromToken(prev_token)
323
324    if found.token_type == '$var':
325      if prev_token_rstripped:
326        yield prev_token_rstripped
327      yield found
328      id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
329      yield id_token
330      pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
331
332      eq_token = ParseToken(lines, pos, EQ_REGEX, '=')
333      yield eq_token
334      pos = Skip(lines, eq_token.end, r'\s*')
335
336      if SubString(lines, pos, pos + 2) != '[[':
337        exp_token = ParseToken(lines, pos, REST_OF_LINE_REGEX, 'exp')
338        yield exp_token
339        pos = Cursor(exp_token.end.line + 1, 0)
340    elif found.token_type == '$for':
341      if prev_token_rstripped:
342        yield prev_token_rstripped
343      yield found
344      id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
345      yield id_token
346      pos = Skip(lines, id_token.end, WHITE_SPACE_REGEX)
347    elif found.token_type == '$range':
348      if prev_token_rstripped:
349        yield prev_token_rstripped
350      yield found
351      id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
352      yield id_token
353      pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
354
355      dots_pos = SkipUntil(lines, pos, DOT_DOT_REGEX, '..')
356      yield MakeToken(lines, pos, dots_pos, 'exp')
357      yield MakeToken(lines, dots_pos, dots_pos + 2, '..')
358      pos = dots_pos + 2
359      new_pos = Cursor(pos.line + 1, 0)
360      yield MakeToken(lines, pos, new_pos, 'exp')
361      pos = new_pos
362    elif found.token_type == '$':
363      if prev_token:
364        yield prev_token
365      yield found
366      exp_token = ParseExpTokenInParens(lines, found.end)
367      yield exp_token
368      pos = exp_token.end
369    elif (found.token_type == ']]' or found.token_type == '$if' or
370          found.token_type == '$elif' or found.token_type == '$else'):
371      if prev_token_rstripped:
372        yield prev_token_rstripped
373      yield found
374      pos = found.end
375    else:
376      if prev_token:
377        yield prev_token
378      yield found
379      pos = found.end
380
381
382def Tokenize(s):
383  """A generator that yields the tokens in the given string."""
384  if s != '':
385    lines = s.splitlines(True)
386    for token in TokenizeLines(lines, Cursor(0, 0)):
387      yield token
388
389
390class CodeNode:
391  def __init__(self, atomic_code_list=None):
392    self.atomic_code = atomic_code_list
393
394
395class VarNode:
396  def __init__(self, identifier=None, atomic_code=None):
397    self.identifier = identifier
398    self.atomic_code = atomic_code
399
400
401class RangeNode:
402  def __init__(self, identifier=None, exp1=None, exp2=None):
403    self.identifier = identifier
404    self.exp1 = exp1
405    self.exp2 = exp2
406
407
408class ForNode:
409  def __init__(self, identifier=None, sep=None, code=None):
410    self.identifier = identifier
411    self.sep = sep
412    self.code = code
413
414
415class ElseNode:
416  def __init__(self, else_branch=None):
417    self.else_branch = else_branch
418
419
420class IfNode:
421  def __init__(self, exp=None, then_branch=None, else_branch=None):
422    self.exp = exp
423    self.then_branch = then_branch
424    self.else_branch = else_branch
425
426
427class RawCodeNode:
428  def __init__(self, token=None):
429    self.raw_code = token
430
431
432class LiteralDollarNode:
433  def __init__(self, token):
434    self.token = token
435
436
437class ExpNode:
438  def __init__(self, token, python_exp):
439    self.token = token
440    self.python_exp = python_exp
441
442
443def PopFront(a_list):
444  head = a_list[0]
445  a_list[:1] = []
446  return head
447
448
449def PushFront(a_list, elem):
450  a_list[:0] = [elem]
451
452
453def PopToken(a_list, token_type=None):
454  token = PopFront(a_list)
455  if token_type is not None and token.token_type != token_type:
456    print 'ERROR: %s expected at %s' % (token_type, token.start)
457    print 'ERROR: %s found instead' % (token,)
458    sys.exit(1)
459
460  return token
461
462
463def PeekToken(a_list):
464  if not a_list:
465    return None
466
467  return a_list[0]
468
469
470def ParseExpNode(token):
471  python_exp = re.sub(r'([_A-Za-z]\w*)', r'self.GetValue("\1")', token.value)
472  return ExpNode(token, python_exp)
473
474
475def ParseElseNode(tokens):
476  def Pop(token_type=None):
477    return PopToken(tokens, token_type)
478
479  next = PeekToken(tokens)
480  if not next:
481    return None
482  if next.token_type == '$else':
483    Pop('$else')
484    Pop('[[')
485    code_node = ParseCodeNode(tokens)
486    Pop(']]')
487    return code_node
488  elif next.token_type == '$elif':
489    Pop('$elif')
490    exp = Pop('code')
491    Pop('[[')
492    code_node = ParseCodeNode(tokens)
493    Pop(']]')
494    inner_else_node = ParseElseNode(tokens)
495    return CodeNode([IfNode(ParseExpNode(exp), code_node, inner_else_node)])
496  elif not next.value.strip():
497    Pop('code')
498    return ParseElseNode(tokens)
499  else:
500    return None
501
502
503def ParseAtomicCodeNode(tokens):
504  def Pop(token_type=None):
505    return PopToken(tokens, token_type)
506
507  head = PopFront(tokens)
508  t = head.token_type
509  if t == 'code':
510    return RawCodeNode(head)
511  elif t == '$var':
512    id_token = Pop('id')
513    Pop('=')
514    next = PeekToken(tokens)
515    if next.token_type == 'exp':
516      exp_token = Pop()
517      return VarNode(id_token, ParseExpNode(exp_token))
518    Pop('[[')
519    code_node = ParseCodeNode(tokens)
520    Pop(']]')
521    return VarNode(id_token, code_node)
522  elif t == '$for':
523    id_token = Pop('id')
524    next_token = PeekToken(tokens)
525    if next_token.token_type == 'code':
526      sep_token = next_token
527      Pop('code')
528    else:
529      sep_token = None
530    Pop('[[')
531    code_node = ParseCodeNode(tokens)
532    Pop(']]')
533    return ForNode(id_token, sep_token, code_node)
534  elif t == '$if':
535    exp_token = Pop('code')
536    Pop('[[')
537    code_node = ParseCodeNode(tokens)
538    Pop(']]')
539    else_node = ParseElseNode(tokens)
540    return IfNode(ParseExpNode(exp_token), code_node, else_node)
541  elif t == '$range':
542    id_token = Pop('id')
543    exp1_token = Pop('exp')
544    Pop('..')
545    exp2_token = Pop('exp')
546    return RangeNode(id_token, ParseExpNode(exp1_token),
547                     ParseExpNode(exp2_token))
548  elif t == '$id':
549    return ParseExpNode(Token(head.start + 1, head.end, head.value[1:], 'id'))
550  elif t == '$($)':
551    return LiteralDollarNode(head)
552  elif t == '$':
553    exp_token = Pop('exp')
554    return ParseExpNode(exp_token)
555  elif t == '[[':
556    code_node = ParseCodeNode(tokens)
557    Pop(']]')
558    return code_node
559  else:
560    PushFront(tokens, head)
561    return None
562
563
564def ParseCodeNode(tokens):
565  atomic_code_list = []
566  while True:
567    if not tokens:
568      break
569    atomic_code_node = ParseAtomicCodeNode(tokens)
570    if atomic_code_node:
571      atomic_code_list.append(atomic_code_node)
572    else:
573      break
574  return CodeNode(atomic_code_list)
575
576
577def ParseToAST(pump_src_text):
578  """Convert the given Pump source text into an AST."""
579  tokens = list(Tokenize(pump_src_text))
580  code_node = ParseCodeNode(tokens)
581  return code_node
582
583
584class Env:
585  def __init__(self):
586    self.variables = []
587    self.ranges = []
588
589  def Clone(self):
590    clone = Env()
591    clone.variables = self.variables[:]
592    clone.ranges = self.ranges[:]
593    return clone
594
595  def PushVariable(self, var, value):
596    # If value looks like an int, store it as an int.
597    try:
598      int_value = int(value)
599      if ('%s' % int_value) == value:
600        value = int_value
601    except Exception:
602      pass
603    self.variables[:0] = [(var, value)]
604
605  def PopVariable(self):
606    self.variables[:1] = []
607
608  def PushRange(self, var, lower, upper):
609    self.ranges[:0] = [(var, lower, upper)]
610
611  def PopRange(self):
612    self.ranges[:1] = []
613
614  def GetValue(self, identifier):
615    for (var, value) in self.variables:
616      if identifier == var:
617        return value
618
619    print 'ERROR: meta variable %s is undefined.' % (identifier,)
620    sys.exit(1)
621
622  def EvalExp(self, exp):
623    try:
624      result = eval(exp.python_exp)
625    except Exception, e:
626      print 'ERROR: caught exception %s: %s' % (e.__class__.__name__, e)
627      print ('ERROR: failed to evaluate meta expression %s at %s' %
628             (exp.python_exp, exp.token.start))
629      sys.exit(1)
630    return result
631
632  def GetRange(self, identifier):
633    for (var, lower, upper) in self.ranges:
634      if identifier == var:
635        return (lower, upper)
636
637    print 'ERROR: range %s is undefined.' % (identifier,)
638    sys.exit(1)
639
640
641class Output:
642  def __init__(self):
643    self.string = ''
644
645  def GetLastLine(self):
646    index = self.string.rfind('\n')
647    if index < 0:
648      return ''
649
650    return self.string[index + 1:]
651
652  def Append(self, s):
653    self.string += s
654
655
656def RunAtomicCode(env, node, output):
657  if isinstance(node, VarNode):
658    identifier = node.identifier.value.strip()
659    result = Output()
660    RunAtomicCode(env.Clone(), node.atomic_code, result)
661    value = result.string
662    env.PushVariable(identifier, value)
663  elif isinstance(node, RangeNode):
664    identifier = node.identifier.value.strip()
665    lower = int(env.EvalExp(node.exp1))
666    upper = int(env.EvalExp(node.exp2))
667    env.PushRange(identifier, lower, upper)
668  elif isinstance(node, ForNode):
669    identifier = node.identifier.value.strip()
670    if node.sep is None:
671      sep = ''
672    else:
673      sep = node.sep.value
674    (lower, upper) = env.GetRange(identifier)
675    for i in range(lower, upper + 1):
676      new_env = env.Clone()
677      new_env.PushVariable(identifier, i)
678      RunCode(new_env, node.code, output)
679      if i != upper:
680        output.Append(sep)
681  elif isinstance(node, RawCodeNode):
682    output.Append(node.raw_code.value)
683  elif isinstance(node, IfNode):
684    cond = env.EvalExp(node.exp)
685    if cond:
686      RunCode(env.Clone(), node.then_branch, output)
687    elif node.else_branch is not None:
688      RunCode(env.Clone(), node.else_branch, output)
689  elif isinstance(node, ExpNode):
690    value = env.EvalExp(node)
691    output.Append('%s' % (value,))
692  elif isinstance(node, LiteralDollarNode):
693    output.Append('$')
694  elif isinstance(node, CodeNode):
695    RunCode(env.Clone(), node, output)
696  else:
697    print 'BAD'
698    print node
699    sys.exit(1)
700
701
702def RunCode(env, code_node, output):
703  for atomic_code in code_node.atomic_code:
704    RunAtomicCode(env, atomic_code, output)
705
706
707def IsSingleLineComment(cur_line):
708  return '//' in cur_line
709
710
711def IsInPreprocessorDirective(prev_lines, cur_line):
712  if cur_line.lstrip().startswith('#'):
713    return True
714  return prev_lines and prev_lines[-1].endswith('\\')
715
716
717def WrapComment(line, output):
718  loc = line.find('//')
719  before_comment = line[:loc].rstrip()
720  if before_comment == '':
721    indent = loc
722  else:
723    output.append(before_comment)
724    indent = len(before_comment) - len(before_comment.lstrip())
725  prefix = indent*' ' + '// '
726  max_len = 80 - len(prefix)
727  comment = line[loc + 2:].strip()
728  segs = [seg for seg in re.split(r'(\w+\W*)', comment) if seg != '']
729  cur_line = ''
730  for seg in segs:
731    if len((cur_line + seg).rstrip()) < max_len:
732      cur_line += seg
733    else:
734      if cur_line.strip() != '':
735        output.append(prefix + cur_line.rstrip())
736      cur_line = seg.lstrip()
737  if cur_line.strip() != '':
738    output.append(prefix + cur_line.strip())
739
740
741def WrapCode(line, line_concat, output):
742  indent = len(line) - len(line.lstrip())
743  prefix = indent*' '  # Prefix of the current line
744  max_len = 80 - indent - len(line_concat)  # Maximum length of the current line
745  new_prefix = prefix + 4*' '  # Prefix of a continuation line
746  new_max_len = max_len - 4  # Maximum length of a continuation line
747  # Prefers to wrap a line after a ',' or ';'.
748  segs = [seg for seg in re.split(r'([^,;]+[,;]?)', line.strip()) if seg != '']
749  cur_line = ''  # The current line without leading spaces.
750  for seg in segs:
751    # If the line is still too long, wrap at a space.
752    while cur_line == '' and len(seg.strip()) > max_len:
753      seg = seg.lstrip()
754      split_at = seg.rfind(' ', 0, max_len)
755      output.append(prefix + seg[:split_at].strip() + line_concat)
756      seg = seg[split_at + 1:]
757      prefix = new_prefix
758      max_len = new_max_len
759
760    if len((cur_line + seg).rstrip()) < max_len:
761      cur_line = (cur_line + seg).lstrip()
762    else:
763      output.append(prefix + cur_line.rstrip() + line_concat)
764      prefix = new_prefix
765      max_len = new_max_len
766      cur_line = seg.lstrip()
767  if cur_line.strip() != '':
768    output.append(prefix + cur_line.strip())
769
770
771def WrapPreprocessorDirective(line, output):
772  WrapCode(line, ' \\', output)
773
774
775def WrapPlainCode(line, output):
776  WrapCode(line, '', output)
777
778
779def IsMultiLineIWYUPragma(line):
780  return re.search(r'/\* IWYU pragma: ', line)
781
782
783def IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
784  return (re.match(r'^#(ifndef|define|endif\s*//)\s*[\w_]+\s*$', line) or
785          re.match(r'^#include\s', line) or
786          # Don't break IWYU pragmas, either; that causes iwyu.py problems.
787          re.search(r'// IWYU pragma: ', line))
788
789
790def WrapLongLine(line, output):
791  line = line.rstrip()
792  if len(line) <= 80:
793    output.append(line)
794  elif IsSingleLineComment(line):
795    if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
796      # The style guide made an exception to allow long header guard lines,
797      # includes and IWYU pragmas.
798      output.append(line)
799    else:
800      WrapComment(line, output)
801  elif IsInPreprocessorDirective(output, line):
802    if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
803      # The style guide made an exception to allow long header guard lines,
804      # includes and IWYU pragmas.
805      output.append(line)
806    else:
807      WrapPreprocessorDirective(line, output)
808  elif IsMultiLineIWYUPragma(line):
809    output.append(line)
810  else:
811    WrapPlainCode(line, output)
812
813
814def BeautifyCode(string):
815  lines = string.splitlines()
816  output = []
817  for line in lines:
818    WrapLongLine(line, output)
819  output2 = [line.rstrip() for line in output]
820  return '\n'.join(output2) + '\n'
821
822
823def ConvertFromPumpSource(src_text):
824  """Return the text generated from the given Pump source text."""
825  ast = ParseToAST(StripMetaComments(src_text))
826  output = Output()
827  RunCode(Env(), ast, output)
828  return BeautifyCode(output.string)
829
830
831def main(argv):
832  if len(argv) == 1:
833    print __doc__
834    sys.exit(1)
835
836  file_path = argv[-1]
837  output_str = ConvertFromPumpSource(file(file_path, 'r').read())
838  if file_path.endswith('.pump'):
839    output_file_path = file_path[:-5]
840  else:
841    output_file_path = '-'
842  if output_file_path == '-':
843    print output_str,
844  else:
845    output_file = file(output_file_path, 'w')
846    output_file.write('// This file was GENERATED by command:\n')
847    output_file.write('//     %s %s\n' %
848                      (os.path.basename(__file__), os.path.basename(file_path)))
849    output_file.write('// DO NOT EDIT BY HAND!!!\n\n')
850    output_file.write(output_str)
851    output_file.close()
852
853
854if __name__ == '__main__':
855  main(sys.argv)
trunk/3rdparty/googletest/googletest/scripts/release_docs.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2013 Google Inc. All Rights Reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9#     * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11#     * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15#     * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31"""Script for branching Google Test/Mock wiki pages for a new version.
32
33SYNOPSIS
34       release_docs.py NEW_RELEASE_VERSION
35
36       Google Test and Google Mock's external user documentation is in
37       interlinked wiki files.  When we release a new version of
38       Google Test or Google Mock, we need to branch the wiki files
39       such that users of a specific version of Google Test/Mock can
40       look up documenation relevant for that version.  This script
41       automates that process by:
42
43         - branching the current wiki pages (which document the
44           behavior of the SVN trunk head) to pages for the specified
45           version (e.g. branching FAQ.wiki to V2_6_FAQ.wiki when
46           NEW_RELEASE_VERSION is 2.6);
47         - updating the links in the branched files to point to the branched
48           version (e.g. a link in V2_6_FAQ.wiki that pointed to
49           Primer.wiki#Anchor will now point to V2_6_Primer.wiki#Anchor).
50
51       NOTE: NEW_RELEASE_VERSION must be a NEW version number for
52       which the wiki pages don't yet exist; otherwise you'll get SVN
53       errors like "svn: Path 'V1_7_PumpManual.wiki' is not a
54       directory" when running the script.
55
56EXAMPLE
57       $ cd PATH/TO/GTEST_SVN_WORKSPACE/trunk
58       $ scripts/release_docs.py 2.6  # create wiki pages for v2.6
59       $ svn status                   # verify the file list
60       $ svn diff                     # verify the file contents
61       $ svn commit -m "release wiki pages for v2.6"
62"""
63
64__author__ = 'wan@google.com (Zhanyong Wan)'
65
66import os
67import re
68import sys
69
70import common
71
72
73# Wiki pages that shouldn't be branched for every gtest/gmock release.
74GTEST_UNVERSIONED_WIKIS = ['DevGuide.wiki']
75GMOCK_UNVERSIONED_WIKIS = [
76    'DesignDoc.wiki',
77    'DevGuide.wiki',
78    'KnownIssues.wiki'
79    ]
80
81
82def DropWikiSuffix(wiki_filename):
83  """Removes the .wiki suffix (if any) from the given filename."""
84
85  return (wiki_filename[:-len('.wiki')] if wiki_filename.endswith('.wiki')
86          else wiki_filename)
87
88
89class WikiBrancher(object):
90  """Branches ..."""
91
92  def __init__(self, dot_version):
93    self.project, svn_root_path = common.GetSvnInfo()
94    if self.project not in ('googletest', 'googlemock'):
95      sys.exit('This script must be run in a gtest or gmock SVN workspace.')
96    self.wiki_dir = svn_root_path + '/wiki'
97    # Turn '2.6' to 'V2_6_'.
98    self.version_prefix = 'V' + dot_version.replace('.', '_') + '_'
99    self.files_to_branch = self.GetFilesToBranch()
100    page_names = [DropWikiSuffix(f) for f in self.files_to_branch]
101    # A link to Foo.wiki is in one of the following forms:
102    #   [Foo words]
103    #   [Foo#Anchor words]
104    #   [http://code.google.com/.../wiki/Foo words]
105    #   [http://code.google.com/.../wiki/Foo#Anchor words]
106    # We want to replace 'Foo' with 'V2_6_Foo' in the above cases.
107    self.search_for_re = re.compile(
108        # This regex matches either
109        #   [Foo
110        # or
111        #   /wiki/Foo
112        # followed by a space or a #, where Foo is the name of an
113        # unversioned wiki page.
114        r'(\[|/wiki/)(%s)([ #])' % '|'.join(page_names))
115    self.replace_with = r'\1%s\2\3' % (self.version_prefix,)
116
117  def GetFilesToBranch(self):
118    """Returns a list of .wiki file names that need to be branched."""
119
120    unversioned_wikis = (GTEST_UNVERSIONED_WIKIS if self.project == 'googletest'
121                         else GMOCK_UNVERSIONED_WIKIS)
122    return [f for f in os.listdir(self.wiki_dir)
123            if (f.endswith('.wiki') and
124                not re.match(r'^V\d', f) and  # Excluded versioned .wiki files.
125                f not in unversioned_wikis)]
126
127  def BranchFiles(self):
128    """Branches the .wiki files needed to be branched."""
129
130    print 'Branching %d .wiki files:' % (len(self.files_to_branch),)
131    os.chdir(self.wiki_dir)
132    for f in self.files_to_branch:
133      command = 'svn cp %s %s%s' % (f, self.version_prefix, f)
134      print command
135      os.system(command)
136
137  def UpdateLinksInBranchedFiles(self):
138
139    for f in self.files_to_branch:
140      source_file = os.path.join(self.wiki_dir, f)
141      versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f)
142      print 'Updating links in %s.' % (versioned_file,)
143      text = file(source_file, 'r').read()
144      new_text = self.search_for_re.sub(self.replace_with, text)
145      file(versioned_file, 'w').write(new_text)
146
147
148def main():
149  if len(sys.argv) != 2:
150    sys.exit(__doc__)
151
152  brancher = WikiBrancher(sys.argv[1])
153  brancher.BranchFiles()
154  brancher.UpdateLinksInBranchedFiles()
155
156
157if __name__ == '__main__':
158  main()
trunk/3rdparty/googletest/googletest/scripts/test/Makefile
r0r249096
1# A Makefile for fusing Google Test and building a sample test against it.
2#
3# SYNOPSIS:
4#
5#   make [all]  - makes everything.
6#   make TARGET - makes the given target.
7#   make check  - makes everything and runs the built sample test.
8#   make clean  - removes all files generated by make.
9
10# Points to the root of fused Google Test, relative to where this file is.
11FUSED_GTEST_DIR = output
12
13# Paths to the fused gtest files.
14FUSED_GTEST_H = $(FUSED_GTEST_DIR)/gtest/gtest.h
15FUSED_GTEST_ALL_CC = $(FUSED_GTEST_DIR)/gtest/gtest-all.cc
16
17# Where to find the sample test.
18SAMPLE_DIR = ../../samples
19
20# Where to find gtest_main.cc.
21GTEST_MAIN_CC = ../../src/gtest_main.cc
22
23# Flags passed to the preprocessor.
24# We have no idea here whether pthreads is available in the system, so
25# disable its use.
26CPPFLAGS += -I$(FUSED_GTEST_DIR) -DGTEST_HAS_PTHREAD=0
27
28# Flags passed to the C++ compiler.
29CXXFLAGS += -g
30
31all : sample1_unittest
32
33check : all
34   ./sample1_unittest
35
36clean :
37   rm -rf $(FUSED_GTEST_DIR) sample1_unittest *.o
38
39$(FUSED_GTEST_H) :
40   ../fuse_gtest_files.py $(FUSED_GTEST_DIR)
41
42$(FUSED_GTEST_ALL_CC) :
43   ../fuse_gtest_files.py $(FUSED_GTEST_DIR)
44
45gtest-all.o : $(FUSED_GTEST_H) $(FUSED_GTEST_ALL_CC)
46   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(FUSED_GTEST_DIR)/gtest/gtest-all.cc
47
48gtest_main.o : $(FUSED_GTEST_H) $(GTEST_MAIN_CC)
49   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GTEST_MAIN_CC)
50
51sample1.o : $(SAMPLE_DIR)/sample1.cc $(SAMPLE_DIR)/sample1.h
52   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(SAMPLE_DIR)/sample1.cc
53
54sample1_unittest.o : $(SAMPLE_DIR)/sample1_unittest.cc \
55                     $(SAMPLE_DIR)/sample1.h $(FUSED_GTEST_H)
56   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(SAMPLE_DIR)/sample1_unittest.cc
57
58sample1_unittest : sample1.o sample1_unittest.o gtest-all.o gtest_main.o
59   $(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ -o $@
trunk/3rdparty/googletest/googletest/scripts/upload.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2007 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Tool for uploading diffs from a version control system to the codereview app.
18
19Usage summary: upload.py [options] [-- diff_options]
20
21Diff options are passed to the diff command of the underlying system.
22
23Supported version control systems:
24  Git
25  Mercurial
26  Subversion
27
28It is important for Git/Mercurial users to specify a tree/node/branch to diff
29against by using the '--rev' option.
30"""
31# This code is derived from appcfg.py in the App Engine SDK (open source),
32# and from ASPN recipe #146306.
33
34import cookielib
35import getpass
36import logging
37import md5
38import mimetypes
39import optparse
40import os
41import re
42import socket
43import subprocess
44import sys
45import urllib
46import urllib2
47import urlparse
48
49try:
50  import readline
51except ImportError:
52  pass
53
54# The logging verbosity:
55#  0: Errors only.
56#  1: Status messages.
57#  2: Info logs.
58#  3: Debug logs.
59verbosity = 1
60
61# Max size of patch or base file.
62MAX_UPLOAD_SIZE = 900 * 1024
63
64
65def GetEmail(prompt):
66  """Prompts the user for their email address and returns it.
67
68  The last used email address is saved to a file and offered up as a suggestion
69  to the user. If the user presses enter without typing in anything the last
70  used email address is used. If the user enters a new address, it is saved
71  for next time we prompt.
72
73  """
74  last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
75  last_email = ""
76  if os.path.exists(last_email_file_name):
77    try:
78      last_email_file = open(last_email_file_name, "r")
79      last_email = last_email_file.readline().strip("\n")
80      last_email_file.close()
81      prompt += " [%s]" % last_email
82    except IOError, e:
83      pass
84  email = raw_input(prompt + ": ").strip()
85  if email:
86    try:
87      last_email_file = open(last_email_file_name, "w")
88      last_email_file.write(email)
89      last_email_file.close()
90    except IOError, e:
91      pass
92  else:
93    email = last_email
94  return email
95
96
97def StatusUpdate(msg):
98  """Print a status message to stdout.
99
100  If 'verbosity' is greater than 0, print the message.
101
102  Args:
103    msg: The string to print.
104  """
105  if verbosity > 0:
106    print msg
107
108
109def ErrorExit(msg):
110  """Print an error message to stderr and exit."""
111  print >>sys.stderr, msg
112  sys.exit(1)
113
114
115class ClientLoginError(urllib2.HTTPError):
116  """Raised to indicate there was an error authenticating with ClientLogin."""
117
118  def __init__(self, url, code, msg, headers, args):
119    urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
120    self.args = args
121    self.reason = args["Error"]
122
123
124class AbstractRpcServer(object):
125  """Provides a common interface for a simple RPC server."""
126
127  def __init__(self, host, auth_function, host_override=None, extra_headers={},
128               save_cookies=False):
129    """Creates a new HttpRpcServer.
130
131    Args:
132      host: The host to send requests to.
133      auth_function: A function that takes no arguments and returns an
134        (email, password) tuple when called. Will be called if authentication
135        is required.
136      host_override: The host header to send to the server (defaults to host).
137      extra_headers: A dict of extra headers to append to every request.
138      save_cookies: If True, save the authentication cookies to local disk.
139        If False, use an in-memory cookiejar instead.  Subclasses must
140        implement this functionality.  Defaults to False.
141    """
142    self.host = host
143    self.host_override = host_override
144    self.auth_function = auth_function
145    self.authenticated = False
146    self.extra_headers = extra_headers
147    self.save_cookies = save_cookies
148    self.opener = self._GetOpener()
149    if self.host_override:
150      logging.info("Server: %s; Host: %s", self.host, self.host_override)
151    else:
152      logging.info("Server: %s", self.host)
153
154  def _GetOpener(self):
155    """Returns an OpenerDirector for making HTTP requests.
156
157    Returns:
158      A urllib2.OpenerDirector object.
159    """
160    raise NotImplementedError()
161
162  def _CreateRequest(self, url, data=None):
163    """Creates a new urllib request."""
164    logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
165    req = urllib2.Request(url, data=data)
166    if self.host_override:
167      req.add_header("Host", self.host_override)
168    for key, value in self.extra_headers.iteritems():
169      req.add_header(key, value)
170    return req
171
172  def _GetAuthToken(self, email, password):
173    """Uses ClientLogin to authenticate the user, returning an auth token.
174
175    Args:
176      email:    The user's email address
177      password: The user's password
178
179    Raises:
180      ClientLoginError: If there was an error authenticating with ClientLogin.
181      HTTPError: If there was some other form of HTTP error.
182
183    Returns:
184      The authentication token returned by ClientLogin.
185    """
186    account_type = "GOOGLE"
187    if self.host.endswith(".google.com"):
188      # Needed for use inside Google.
189      account_type = "HOSTED"
190    req = self._CreateRequest(
191        url="https://www.google.com/accounts/ClientLogin",
192        data=urllib.urlencode({
193            "Email": email,
194            "Passwd": password,
195            "service": "ah",
196            "source": "rietveld-codereview-upload",
197            "accountType": account_type,
198        }),
199    )
200    try:
201      response = self.opener.open(req)
202      response_body = response.read()
203      response_dict = dict(x.split("=")
204                           for x in response_body.split("\n") if x)
205      return response_dict["Auth"]
206    except urllib2.HTTPError, e:
207      if e.code == 403:
208        body = e.read()
209        response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
210        raise ClientLoginError(req.get_full_url(), e.code, e.msg,
211                               e.headers, response_dict)
212      else:
213        raise
214
215  def _GetAuthCookie(self, auth_token):
216    """Fetches authentication cookies for an authentication token.
217
218    Args:
219      auth_token: The authentication token returned by ClientLogin.
220
221    Raises:
222      HTTPError: If there was an error fetching the authentication cookies.
223    """
224    # This is a dummy value to allow us to identify when we're successful.
225    continue_location = "http://localhost/"
226    args = {"continue": continue_location, "auth": auth_token}
227    req = self._CreateRequest("http://%s/_ah/login?%s" %
228                              (self.host, urllib.urlencode(args)))
229    try:
230      response = self.opener.open(req)
231    except urllib2.HTTPError, e:
232      response = e
233    if (response.code != 302 or
234        response.info()["location"] != continue_location):
235      raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
236                              response.headers, response.fp)
237    self.authenticated = True
238
239  def _Authenticate(self):
240    """Authenticates the user.
241
242    The authentication process works as follows:
243     1) We get a username and password from the user
244     2) We use ClientLogin to obtain an AUTH token for the user
245        (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
246     3) We pass the auth token to /_ah/login on the server to obtain an
247        authentication cookie. If login was successful, it tries to redirect
248        us to the URL we provided.
249
250    If we attempt to access the upload API without first obtaining an
251    authentication cookie, it returns a 401 response and directs us to
252    authenticate ourselves with ClientLogin.
253    """
254    for i in range(3):
255      credentials = self.auth_function()
256      try:
257        auth_token = self._GetAuthToken(credentials[0], credentials[1])
258      except ClientLoginError, e:
259        if e.reason == "BadAuthentication":
260          print >>sys.stderr, "Invalid username or password."
261          continue
262        if e.reason == "CaptchaRequired":
263          print >>sys.stderr, (
264              "Please go to\n"
265              "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
266              "and verify you are a human.  Then try again.")
267          break
268        if e.reason == "NotVerified":
269          print >>sys.stderr, "Account not verified."
270          break
271        if e.reason == "TermsNotAgreed":
272          print >>sys.stderr, "User has not agreed to TOS."
273          break
274        if e.reason == "AccountDeleted":
275          print >>sys.stderr, "The user account has been deleted."
276          break
277        if e.reason == "AccountDisabled":
278          print >>sys.stderr, "The user account has been disabled."
279          break
280        if e.reason == "ServiceDisabled":
281          print >>sys.stderr, ("The user's access to the service has been "
282                               "disabled.")
283          break
284        if e.reason == "ServiceUnavailable":
285          print >>sys.stderr, "The service is not available; try again later."
286          break
287        raise
288      self._GetAuthCookie(auth_token)
289      return
290
291  def Send(self, request_path, payload=None,
292           content_type="application/octet-stream",
293           timeout=None,
294           **kwargs):
295    """Sends an RPC and returns the response.
296
297    Args:
298      request_path: The path to send the request to, eg /api/appversion/create.
299      payload: The body of the request, or None to send an empty request.
300      content_type: The Content-Type header to use.
301      timeout: timeout in seconds; default None i.e. no timeout.
302        (Note: for large requests on OS X, the timeout doesn't work right.)
303      kwargs: Any keyword arguments are converted into query string parameters.
304
305    Returns:
306      The response body, as a string.
307    """
308    # TODO: Don't require authentication.  Let the server say
309    # whether it is necessary.
310    if not self.authenticated:
311      self._Authenticate()
312
313    old_timeout = socket.getdefaulttimeout()
314    socket.setdefaulttimeout(timeout)
315    try:
316      tries = 0
317      while True:
318        tries += 1
319        args = dict(kwargs)
320        url = "http://%s%s" % (self.host, request_path)
321        if args:
322          url += "?" + urllib.urlencode(args)
323        req = self._CreateRequest(url=url, data=payload)
324        req.add_header("Content-Type", content_type)
325        try:
326          f = self.opener.open(req)
327          response = f.read()
328          f.close()
329          return response
330        except urllib2.HTTPError, e:
331          if tries > 3:
332            raise
333          elif e.code == 401:
334            self._Authenticate()
335##           elif e.code >= 500 and e.code < 600:
336##             # Server Error - try again.
337##             continue
338          else:
339            raise
340    finally:
341      socket.setdefaulttimeout(old_timeout)
342
343
344class HttpRpcServer(AbstractRpcServer):
345  """Provides a simplified RPC-style interface for HTTP requests."""
346
347  def _Authenticate(self):
348    """Save the cookie jar after authentication."""
349    super(HttpRpcServer, self)._Authenticate()
350    if self.save_cookies:
351      StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
352      self.cookie_jar.save()
353
354  def _GetOpener(self):
355    """Returns an OpenerDirector that supports cookies and ignores redirects.
356
357    Returns:
358      A urllib2.OpenerDirector object.
359    """
360    opener = urllib2.OpenerDirector()
361    opener.add_handler(urllib2.ProxyHandler())
362    opener.add_handler(urllib2.UnknownHandler())
363    opener.add_handler(urllib2.HTTPHandler())
364    opener.add_handler(urllib2.HTTPDefaultErrorHandler())
365    opener.add_handler(urllib2.HTTPSHandler())
366    opener.add_handler(urllib2.HTTPErrorProcessor())
367    if self.save_cookies:
368      self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
369      self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
370      if os.path.exists(self.cookie_file):
371        try:
372          self.cookie_jar.load()
373          self.authenticated = True
374          StatusUpdate("Loaded authentication cookies from %s" %
375                       self.cookie_file)
376        except (cookielib.LoadError, IOError):
377          # Failed to load cookies - just ignore them.
378          pass
379      else:
380        # Create an empty cookie file with mode 600
381        fd = os.open(self.cookie_file, os.O_CREAT, 0600)
382        os.close(fd)
383      # Always chmod the cookie file
384      os.chmod(self.cookie_file, 0600)
385    else:
386      # Don't save cookies across runs of update.py.
387      self.cookie_jar = cookielib.CookieJar()
388    opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
389    return opener
390
391
392parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
393parser.add_option("-y", "--assume_yes", action="store_true",
394                  dest="assume_yes", default=False,
395                  help="Assume that the answer to yes/no questions is 'yes'.")
396# Logging
397group = parser.add_option_group("Logging options")
398group.add_option("-q", "--quiet", action="store_const", const=0,
399                 dest="verbose", help="Print errors only.")
400group.add_option("-v", "--verbose", action="store_const", const=2,
401                 dest="verbose", default=1,
402                 help="Print info level logs (default).")
403group.add_option("--noisy", action="store_const", const=3,
404                 dest="verbose", help="Print all logs.")
405# Review server
406group = parser.add_option_group("Review server options")
407group.add_option("-s", "--server", action="store", dest="server",
408                 default="codereview.appspot.com",
409                 metavar="SERVER",
410                 help=("The server to upload to. The format is host[:port]. "
411                       "Defaults to 'codereview.appspot.com'."))
412group.add_option("-e", "--email", action="store", dest="email",
413                 metavar="EMAIL", default=None,
414                 help="The username to use. Will prompt if omitted.")
415group.add_option("-H", "--host", action="store", dest="host",
416                 metavar="HOST", default=None,
417                 help="Overrides the Host header sent with all RPCs.")
418group.add_option("--no_cookies", action="store_false",
419                 dest="save_cookies", default=True,
420                 help="Do not save authentication cookies to local disk.")
421# Issue
422group = parser.add_option_group("Issue options")
423group.add_option("-d", "--description", action="store", dest="description",
424                 metavar="DESCRIPTION", default=None,
425                 help="Optional description when creating an issue.")
426group.add_option("-f", "--description_file", action="store",
427                 dest="description_file", metavar="DESCRIPTION_FILE",
428                 default=None,
429                 help="Optional path of a file that contains "
430                      "the description when creating an issue.")
431group.add_option("-r", "--reviewers", action="store", dest="reviewers",
432                 metavar="REVIEWERS", default=None,
433                 help="Add reviewers (comma separated email addresses).")
434group.add_option("--cc", action="store", dest="cc",
435                 metavar="CC", default=None,
436                 help="Add CC (comma separated email addresses).")
437# Upload options
438group = parser.add_option_group("Patch options")
439group.add_option("-m", "--message", action="store", dest="message",
440                 metavar="MESSAGE", default=None,
441                 help="A message to identify the patch. "
442                      "Will prompt if omitted.")
443group.add_option("-i", "--issue", type="int", action="store",
444                 metavar="ISSUE", default=None,
445                 help="Issue number to which to add. Defaults to new issue.")
446group.add_option("--download_base", action="store_true",
447                 dest="download_base", default=False,
448                 help="Base files will be downloaded by the server "
449                 "(side-by-side diffs may not work on files with CRs).")
450group.add_option("--rev", action="store", dest="revision",
451                 metavar="REV", default=None,
452                 help="Branch/tree/revision to diff against (used by DVCS).")
453group.add_option("--send_mail", action="store_true",
454                 dest="send_mail", default=False,
455                 help="Send notification email to reviewers.")
456
457
458def GetRpcServer(options):
459  """Returns an instance of an AbstractRpcServer.
460
461  Returns:
462    A new AbstractRpcServer, on which RPC calls can be made.
463  """
464
465  rpc_server_class = HttpRpcServer
466
467  def GetUserCredentials():
468    """Prompts the user for a username and password."""
469    email = options.email
470    if email is None:
471      email = GetEmail("Email (login for uploading to %s)" % options.server)
472    password = getpass.getpass("Password for %s: " % email)
473    return (email, password)
474
475  # If this is the dev_appserver, use fake authentication.
476  host = (options.host or options.server).lower()
477  if host == "localhost" or host.startswith("localhost:"):
478    email = options.email
479    if email is None:
480      email = "test@example.com"
481      logging.info("Using debug user %s.  Override with --email" % email)
482    server = rpc_server_class(
483        options.server,
484        lambda: (email, "password"),
485        host_override=options.host,
486        extra_headers={"Cookie":
487                       'dev_appserver_login="%s:False"' % email},
488        save_cookies=options.save_cookies)
489    # Don't try to talk to ClientLogin.
490    server.authenticated = True
491    return server
492
493  return rpc_server_class(options.server, GetUserCredentials,
494                          host_override=options.host,
495                          save_cookies=options.save_cookies)
496
497
498def EncodeMultipartFormData(fields, files):
499  """Encode form fields for multipart/form-data.
500
501  Args:
502    fields: A sequence of (name, value) elements for regular form fields.
503    files: A sequence of (name, filename, value) elements for data to be
504           uploaded as files.
505  Returns:
506    (content_type, body) ready for httplib.HTTP instance.
507
508  Source:
509    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
510  """
511  BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
512  CRLF = '\r\n'
513  lines = []
514  for (key, value) in fields:
515    lines.append('--' + BOUNDARY)
516    lines.append('Content-Disposition: form-data; name="%s"' % key)
517    lines.append('')
518    lines.append(value)
519  for (key, filename, value) in files:
520    lines.append('--' + BOUNDARY)
521    lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
522             (key, filename))
523    lines.append('Content-Type: %s' % GetContentType(filename))
524    lines.append('')
525    lines.append(value)
526  lines.append('--' + BOUNDARY + '--')
527  lines.append('')
528  body = CRLF.join(lines)
529  content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
530  return content_type, body
531
532
533def GetContentType(filename):
534  """Helper to guess the content-type from the filename."""
535  return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
536
537
538# Use a shell for subcommands on Windows to get a PATH search.
539use_shell = sys.platform.startswith("win")
540
541def RunShellWithReturnCode(command, print_output=False,
542                           universal_newlines=True):
543  """Executes a command and returns the output from stdout and the return code.
544
545  Args:
546    command: Command to execute.
547    print_output: If True, the output is printed to stdout.
548                  If False, both stdout and stderr are ignored.
549    universal_newlines: Use universal_newlines flag (default: True).
550
551  Returns:
552    Tuple (output, return code)
553  """
554  logging.info("Running %s", command)
555  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
556                       shell=use_shell, universal_newlines=universal_newlines)
557  if print_output:
558    output_array = []
559    while True:
560      line = p.stdout.readline()
561      if not line:
562        break
563      print line.strip("\n")
564      output_array.append(line)
565    output = "".join(output_array)
566  else:
567    output = p.stdout.read()
568  p.wait()
569  errout = p.stderr.read()
570  if print_output and errout:
571    print >>sys.stderr, errout
572  p.stdout.close()
573  p.stderr.close()
574  return output, p.returncode
575
576
577def RunShell(command, silent_ok=False, universal_newlines=True,
578             print_output=False):
579  data, retcode = RunShellWithReturnCode(command, print_output,
580                                         universal_newlines)
581  if retcode:
582    ErrorExit("Got error status from %s:\n%s" % (command, data))
583  if not silent_ok and not data:
584    ErrorExit("No output from %s" % command)
585  return data
586
587
588class VersionControlSystem(object):
589  """Abstract base class providing an interface to the VCS."""
590
591  def __init__(self, options):
592    """Constructor.
593
594    Args:
595      options: Command line options.
596    """
597    self.options = options
598
599  def GenerateDiff(self, args):
600    """Return the current diff as a string.
601
602    Args:
603      args: Extra arguments to pass to the diff command.
604    """
605    raise NotImplementedError(
606        "abstract method -- subclass %s must override" % self.__class__)
607
608  def GetUnknownFiles(self):
609    """Return a list of files unknown to the VCS."""
610    raise NotImplementedError(
611        "abstract method -- subclass %s must override" % self.__class__)
612
613  def CheckForUnknownFiles(self):
614    """Show an "are you sure?" prompt if there are unknown files."""
615    unknown_files = self.GetUnknownFiles()
616    if unknown_files:
617      print "The following files are not added to version control:"
618      for line in unknown_files:
619        print line
620      prompt = "Are you sure to continue?(y/N) "
621      answer = raw_input(prompt).strip()
622      if answer != "y":
623        ErrorExit("User aborted")
624
625  def GetBaseFile(self, filename):
626    """Get the content of the upstream version of a file.
627
628    Returns:
629      A tuple (base_content, new_content, is_binary, status)
630        base_content: The contents of the base file.
631        new_content: For text files, this is empty.  For binary files, this is
632          the contents of the new file, since the diff output won't contain
633          information to reconstruct the current file.
634        is_binary: True iff the file is binary.
635        status: The status of the file.
636    """
637
638    raise NotImplementedError(
639        "abstract method -- subclass %s must override" % self.__class__)
640
641
642  def GetBaseFiles(self, diff):
643    """Helper that calls GetBase file for each file in the patch.
644
645    Returns:
646      A dictionary that maps from filename to GetBaseFile's tuple.  Filenames
647      are retrieved based on lines that start with "Index:" or
648      "Property changes on:".
649    """
650    files = {}
651    for line in diff.splitlines(True):
652      if line.startswith('Index:') or line.startswith('Property changes on:'):
653        unused, filename = line.split(':', 1)
654        # On Windows if a file has property changes its filename uses '\'
655        # instead of '/'.
656        filename = filename.strip().replace('\\', '/')
657        files[filename] = self.GetBaseFile(filename)
658    return files
659
660
661  def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
662                      files):
663    """Uploads the base files (and if necessary, the current ones as well)."""
664
665    def UploadFile(filename, file_id, content, is_binary, status, is_base):
666      """Uploads a file to the server."""
667      file_too_large = False
668      if is_base:
669        type = "base"
670      else:
671        type = "current"
672      if len(content) > MAX_UPLOAD_SIZE:
673        print ("Not uploading the %s file for %s because it's too large." %
674               (type, filename))
675        file_too_large = True
676        content = ""
677      checksum = md5.new(content).hexdigest()
678      if options.verbose > 0 and not file_too_large:
679        print "Uploading %s file for %s" % (type, filename)
680      url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
681      form_fields = [("filename", filename),
682                     ("status", status),
683                     ("checksum", checksum),
684                     ("is_binary", str(is_binary)),
685                     ("is_current", str(not is_base)),
686                    ]
687      if file_too_large:
688        form_fields.append(("file_too_large", "1"))
689      if options.email:
690        form_fields.append(("user", options.email))
691      ctype, body = EncodeMultipartFormData(form_fields,
692                                            [("data", filename, content)])
693      response_body = rpc_server.Send(url, body,
694                                      content_type=ctype)
695      if not response_body.startswith("OK"):
696        StatusUpdate("  --> %s" % response_body)
697        sys.exit(1)
698
699    patches = dict()
700    [patches.setdefault(v, k) for k, v in patch_list]
701    for filename in patches.keys():
702      base_content, new_content, is_binary, status = files[filename]
703      file_id_str = patches.get(filename)
704      if file_id_str.find("nobase") != -1:
705        base_content = None
706        file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
707      file_id = int(file_id_str)
708      if base_content != None:
709        UploadFile(filename, file_id, base_content, is_binary, status, True)
710      if new_content != None:
711        UploadFile(filename, file_id, new_content, is_binary, status, False)
712
713  def IsImage(self, filename):
714    """Returns true if the filename has an image extension."""
715    mimetype =  mimetypes.guess_type(filename)[0]
716    if not mimetype:
717      return False
718    return mimetype.startswith("image/")
719
720
721class SubversionVCS(VersionControlSystem):
722  """Implementation of the VersionControlSystem interface for Subversion."""
723
724  def __init__(self, options):
725    super(SubversionVCS, self).__init__(options)
726    if self.options.revision:
727      match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
728      if not match:
729        ErrorExit("Invalid Subversion revision %s." % self.options.revision)
730      self.rev_start = match.group(1)
731      self.rev_end = match.group(3)
732    else:
733      self.rev_start = self.rev_end = None
734    # Cache output from "svn list -r REVNO dirname".
735    # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
736    self.svnls_cache = {}
737    # SVN base URL is required to fetch files deleted in an older revision.
738    # Result is cached to not guess it over and over again in GetBaseFile().
739    required = self.options.download_base or self.options.revision is not None
740    self.svn_base = self._GuessBase(required)
741
742  def GuessBase(self, required):
743    """Wrapper for _GuessBase."""
744    return self.svn_base
745
746  def _GuessBase(self, required):
747    """Returns the SVN base URL.
748
749    Args:
750      required: If true, exits if the url can't be guessed, otherwise None is
751        returned.
752    """
753    info = RunShell(["svn", "info"])
754    for line in info.splitlines():
755      words = line.split()
756      if len(words) == 2 and words[0] == "URL:":
757        url = words[1]
758        scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
759        username, netloc = urllib.splituser(netloc)
760        if username:
761          logging.info("Removed username from base URL")
762        if netloc.endswith("svn.python.org"):
763          if netloc == "svn.python.org":
764            if path.startswith("/projects/"):
765              path = path[9:]
766          elif netloc != "pythondev@svn.python.org":
767            ErrorExit("Unrecognized Python URL: %s" % url)
768          base = "http://svn.python.org/view/*checkout*%s/" % path
769          logging.info("Guessed Python base = %s", base)
770        elif netloc.endswith("svn.collab.net"):
771          if path.startswith("/repos/"):
772            path = path[6:]
773          base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
774          logging.info("Guessed CollabNet base = %s", base)
775        elif netloc.endswith(".googlecode.com"):
776          path = path + "/"
777          base = urlparse.urlunparse(("http", netloc, path, params,
778                                      query, fragment))
779          logging.info("Guessed Google Code base = %s", base)
780        else:
781          path = path + "/"
782          base = urlparse.urlunparse((scheme, netloc, path, params,
783                                      query, fragment))
784          logging.info("Guessed base = %s", base)
785        return base
786    if required:
787      ErrorExit("Can't find URL in output from svn info")
788    return None
789
790  def GenerateDiff(self, args):
791    cmd = ["svn", "diff"]
792    if self.options.revision:
793      cmd += ["-r", self.options.revision]
794    cmd.extend(args)
795    data = RunShell(cmd)
796    count = 0
797    for line in data.splitlines():
798      if line.startswith("Index:") or line.startswith("Property changes on:"):
799        count += 1
800        logging.info(line)
801    if not count:
802      ErrorExit("No valid patches found in output from svn diff")
803    return data
804
805  def _CollapseKeywords(self, content, keyword_str):
806    """Collapses SVN keywords."""
807    # svn cat translates keywords but svn diff doesn't. As a result of this
808    # behavior patching.PatchChunks() fails with a chunk mismatch error.
809    # This part was originally written by the Review Board development team
810    # who had the same problem (http://reviews.review-board.org/r/276/).
811    # Mapping of keywords to known aliases
812    svn_keywords = {
813      # Standard keywords
814      'Date':                ['Date', 'LastChangedDate'],
815      'Revision':            ['Revision', 'LastChangedRevision', 'Rev'],
816      'Author':              ['Author', 'LastChangedBy'],
817      'HeadURL':             ['HeadURL', 'URL'],
818      'Id':                  ['Id'],
819
820      # Aliases
821      'LastChangedDate':     ['LastChangedDate', 'Date'],
822      'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
823      'LastChangedBy':       ['LastChangedBy', 'Author'],
824      'URL':                 ['URL', 'HeadURL'],
825    }
826
827    def repl(m):
828       if m.group(2):
829         return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
830       return "$%s$" % m.group(1)
831    keywords = [keyword
832                for name in keyword_str.split(" ")
833                for keyword in svn_keywords.get(name, [])]
834    return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
835
836  def GetUnknownFiles(self):
837    status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
838    unknown_files = []
839    for line in status.split("\n"):
840      if line and line[0] == "?":
841        unknown_files.append(line)
842    return unknown_files
843
844  def ReadFile(self, filename):
845    """Returns the contents of a file."""
846    file = open(filename, 'rb')
847    result = ""
848    try:
849      result = file.read()
850    finally:
851      file.close()
852    return result
853
854  def GetStatus(self, filename):
855    """Returns the status of a file."""
856    if not self.options.revision:
857      status = RunShell(["svn", "status", "--ignore-externals", filename])
858      if not status:
859        ErrorExit("svn status returned no output for %s" % filename)
860      status_lines = status.splitlines()
861      # If file is in a cl, the output will begin with
862      # "\n--- Changelist 'cl_name':\n".  See
863      # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
864      if (len(status_lines) == 3 and
865          not status_lines[0] and
866          status_lines[1].startswith("--- Changelist")):
867        status = status_lines[2]
868      else:
869        status = status_lines[0]
870    # If we have a revision to diff against we need to run "svn list"
871    # for the old and the new revision and compare the results to get
872    # the correct status for a file.
873    else:
874      dirname, relfilename = os.path.split(filename)
875      if dirname not in self.svnls_cache:
876        cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
877        out, returncode = RunShellWithReturnCode(cmd)
878        if returncode:
879          ErrorExit("Failed to get status for %s." % filename)
880        old_files = out.splitlines()
881        args = ["svn", "list"]
882        if self.rev_end:
883          args += ["-r", self.rev_end]
884        cmd = args + [dirname or "."]
885        out, returncode = RunShellWithReturnCode(cmd)
886        if returncode:
887          ErrorExit("Failed to run command %s" % cmd)
888        self.svnls_cache[dirname] = (old_files, out.splitlines())
889      old_files, new_files = self.svnls_cache[dirname]
890      if relfilename in old_files and relfilename not in new_files:
891        status = "D   "
892      elif relfilename in old_files and relfilename in new_files:
893        status = "M   "
894      else:
895        status = "A   "
896    return status
897
898  def GetBaseFile(self, filename):
899    status = self.GetStatus(filename)
900    base_content = None
901    new_content = None
902
903    # If a file is copied its status will be "A  +", which signifies
904    # "addition-with-history".  See "svn st" for more information.  We need to
905    # upload the original file or else diff parsing will fail if the file was
906    # edited.
907    if status[0] == "A" and status[3] != "+":
908      # We'll need to upload the new content if we're adding a binary file
909      # since diff's output won't contain it.
910      mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
911                          silent_ok=True)
912      base_content = ""
913      is_binary = mimetype and not mimetype.startswith("text/")
914      if is_binary and self.IsImage(filename):
915        new_content = self.ReadFile(filename)
916    elif (status[0] in ("M", "D", "R") or
917          (status[0] == "A" and status[3] == "+") or  # Copied file.
918          (status[0] == " " and status[1] == "M")):  # Property change.
919      args = []
920      if self.options.revision:
921        url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
922      else:
923        # Don't change filename, it's needed later.
924        url = filename
925        args += ["-r", "BASE"]
926      cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
927      mimetype, returncode = RunShellWithReturnCode(cmd)
928      if returncode:
929        # File does not exist in the requested revision.
930        # Reset mimetype, it contains an error message.
931        mimetype = ""
932      get_base = False
933      is_binary = mimetype and not mimetype.startswith("text/")
934      if status[0] == " ":
935        # Empty base content just to force an upload.
936        base_content = ""
937      elif is_binary:
938        if self.IsImage(filename):
939          get_base = True
940          if status[0] == "M":
941            if not self.rev_end:
942              new_content = self.ReadFile(filename)
943            else:
944              url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
945              new_content = RunShell(["svn", "cat", url],
946                                     universal_newlines=True, silent_ok=True)
947        else:
948          base_content = ""
949      else:
950        get_base = True
951
952      if get_base:
953        if is_binary:
954          universal_newlines = False
955        else:
956          universal_newlines = True
957        if self.rev_start:
958          # "svn cat -r REV delete_file.txt" doesn't work. cat requires
959          # the full URL with "@REV" appended instead of using "-r" option.
960          url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
961          base_content = RunShell(["svn", "cat", url],
962                                  universal_newlines=universal_newlines,
963                                  silent_ok=True)
964        else:
965          base_content = RunShell(["svn", "cat", filename],
966                                  universal_newlines=universal_newlines,
967                                  silent_ok=True)
968        if not is_binary:
969          args = []
970          if self.rev_start:
971            url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
972          else:
973            url = filename
974            args += ["-r", "BASE"]
975          cmd = ["svn"] + args + ["propget", "svn:keywords", url]
976          keywords, returncode = RunShellWithReturnCode(cmd)
977          if keywords and not returncode:
978            base_content = self._CollapseKeywords(base_content, keywords)
979    else:
980      StatusUpdate("svn status returned unexpected output: %s" % status)
981      sys.exit(1)
982    return base_content, new_content, is_binary, status[0:5]
983
984
985class GitVCS(VersionControlSystem):
986  """Implementation of the VersionControlSystem interface for Git."""
987
988  def __init__(self, options):
989    super(GitVCS, self).__init__(options)
990    # Map of filename -> hash of base file.
991    self.base_hashes = {}
992
993  def GenerateDiff(self, extra_args):
994    # This is more complicated than svn's GenerateDiff because we must convert
995    # the diff output to include an svn-style "Index:" line as well as record
996    # the hashes of the base files, so we can upload them along with our diff.
997    if self.options.revision:
998      extra_args = [self.options.revision] + extra_args
999    gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
1000    svndiff = []
1001    filecount = 0
1002    filename = None
1003    for line in gitdiff.splitlines():
1004      match = re.match(r"diff --git a/(.*) b/.*$", line)
1005      if match:
1006        filecount += 1
1007        filename = match.group(1)
1008        svndiff.append("Index: %s\n" % filename)
1009      else:
1010        # The "index" line in a git diff looks like this (long hashes elided):
1011        #   index 82c0d44..b2cee3f 100755
1012        # We want to save the left hash, as that identifies the base file.
1013        match = re.match(r"index (\w+)\.\.", line)
1014        if match:
1015          self.base_hashes[filename] = match.group(1)
1016      svndiff.append(line + "\n")
1017    if not filecount:
1018      ErrorExit("No valid patches found in output from git diff")
1019    return "".join(svndiff)
1020
1021  def GetUnknownFiles(self):
1022    status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
1023                      silent_ok=True)
1024    return status.splitlines()
1025
1026  def GetBaseFile(self, filename):
1027    hash = self.base_hashes[filename]
1028    base_content = None
1029    new_content = None
1030    is_binary = False
1031    if hash == "0" * 40:  # All-zero hash indicates no base file.
1032      status = "A"
1033      base_content = ""
1034    else:
1035      status = "M"
1036      base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
1037      if returncode:
1038        ErrorExit("Got error status from 'git show %s'" % hash)
1039    return (base_content, new_content, is_binary, status)
1040
1041
1042class MercurialVCS(VersionControlSystem):
1043  """Implementation of the VersionControlSystem interface for Mercurial."""
1044
1045  def __init__(self, options, repo_dir):
1046    super(MercurialVCS, self).__init__(options)
1047    # Absolute path to repository (we can be in a subdir)
1048    self.repo_dir = os.path.normpath(repo_dir)
1049    # Compute the subdir
1050    cwd = os.path.normpath(os.getcwd())
1051    assert cwd.startswith(self.repo_dir)
1052    self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
1053    if self.options.revision:
1054      self.base_rev = self.options.revision
1055    else:
1056      self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
1057
1058  def _GetRelPath(self, filename):
1059    """Get relative path of a file according to the current directory,
1060    given its logical path in the repo."""
1061    assert filename.startswith(self.subdir), filename
1062    return filename[len(self.subdir):].lstrip(r"\/")
1063
1064  def GenerateDiff(self, extra_args):
1065    # If no file specified, restrict to the current subdir
1066    extra_args = extra_args or ["."]
1067    cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
1068    data = RunShell(cmd, silent_ok=True)
1069    svndiff = []
1070    filecount = 0
1071    for line in data.splitlines():
1072      m = re.match("diff --git a/(\S+) b/(\S+)", line)
1073      if m:
1074        # Modify line to make it look like as it comes from svn diff.
1075        # With this modification no changes on the server side are required
1076        # to make upload.py work with Mercurial repos.
1077        # NOTE: for proper handling of moved/copied files, we have to use
1078        # the second filename.
1079        filename = m.group(2)
1080        svndiff.append("Index: %s" % filename)
1081        svndiff.append("=" * 67)
1082        filecount += 1
1083        logging.info(line)
1084      else:
1085        svndiff.append(line)
1086    if not filecount:
1087      ErrorExit("No valid patches found in output from hg diff")
1088    return "\n".join(svndiff) + "\n"
1089
1090  def GetUnknownFiles(self):
1091    """Return a list of files unknown to the VCS."""
1092    args = []
1093    status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
1094        silent_ok=True)
1095    unknown_files = []
1096    for line in status.splitlines():
1097      st, fn = line.split(" ", 1)
1098      if st == "?":
1099        unknown_files.append(fn)
1100    return unknown_files
1101
1102  def GetBaseFile(self, filename):
1103    # "hg status" and "hg cat" both take a path relative to the current subdir
1104    # rather than to the repo root, but "hg diff" has given us the full path
1105    # to the repo root.
1106    base_content = ""
1107    new_content = None
1108    is_binary = False
1109    oldrelpath = relpath = self._GetRelPath(filename)
1110    # "hg status -C" returns two lines for moved/copied files, one otherwise
1111    out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
1112    out = out.splitlines()
1113    # HACK: strip error message about missing file/directory if it isn't in
1114    # the working copy
1115    if out[0].startswith('%s: ' % relpath):
1116      out = out[1:]
1117    if len(out) > 1:
1118      # Moved/copied => considered as modified, use old filename to
1119      # retrieve base contents
1120      oldrelpath = out[1].strip()
1121      status = "M"
1122    else:
1123      status, _ = out[0].split(' ', 1)
1124    if status != "A":
1125      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
1126        silent_ok=True)
1127      is_binary = "\0" in base_content  # Mercurial's heuristic
1128    if status != "R":
1129      new_content = open(relpath, "rb").read()
1130      is_binary = is_binary or "\0" in new_content
1131    if is_binary and base_content:
1132      # Fetch again without converting newlines
1133      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
1134        silent_ok=True, universal_newlines=False)
1135    if not is_binary or not self.IsImage(relpath):
1136      new_content = None
1137    return base_content, new_content, is_binary, status
1138
1139
1140# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
1141def SplitPatch(data):
1142  """Splits a patch into separate pieces for each file.
1143
1144  Args:
1145    data: A string containing the output of svn diff.
1146
1147  Returns:
1148    A list of 2-tuple (filename, text) where text is the svn diff output
1149      pertaining to filename.
1150  """
1151  patches = []
1152  filename = None
1153  diff = []
1154  for line in data.splitlines(True):
1155    new_filename = None
1156    if line.startswith('Index:'):
1157      unused, new_filename = line.split(':', 1)
1158      new_filename = new_filename.strip()
1159    elif line.startswith('Property changes on:'):
1160      unused, temp_filename = line.split(':', 1)
1161      # When a file is modified, paths use '/' between directories, however
1162      # when a property is modified '\' is used on Windows.  Make them the same
1163      # otherwise the file shows up twice.
1164      temp_filename = temp_filename.strip().replace('\\', '/')
1165      if temp_filename != filename:
1166        # File has property changes but no modifications, create a new diff.
1167        new_filename = temp_filename
1168    if new_filename:
1169      if filename and diff:
1170        patches.append((filename, ''.join(diff)))
1171      filename = new_filename
1172      diff = [line]
1173      continue
1174    if diff is not None:
1175      diff.append(line)
1176  if filename and diff:
1177    patches.append((filename, ''.join(diff)))
1178  return patches
1179
1180
1181def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
1182  """Uploads a separate patch for each file in the diff output.
1183
1184  Returns a list of [patch_key, filename] for each file.
1185  """
1186  patches = SplitPatch(data)
1187  rv = []
1188  for patch in patches:
1189    if len(patch[1]) > MAX_UPLOAD_SIZE:
1190      print ("Not uploading the patch for " + patch[0] +
1191             " because the file is too large.")
1192      continue
1193    form_fields = [("filename", patch[0])]
1194    if not options.download_base:
1195      form_fields.append(("content_upload", "1"))
1196    files = [("data", "data.diff", patch[1])]
1197    ctype, body = EncodeMultipartFormData(form_fields, files)
1198    url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
1199    print "Uploading patch for " + patch[0]
1200    response_body = rpc_server.Send(url, body, content_type=ctype)
1201    lines = response_body.splitlines()
1202    if not lines or lines[0] != "OK":
1203      StatusUpdate("  --> %s" % response_body)
1204      sys.exit(1)
1205    rv.append([lines[1], patch[0]])
1206  return rv
1207
1208
1209def GuessVCS(options):
1210  """Helper to guess the version control system.
1211
1212  This examines the current directory, guesses which VersionControlSystem
1213  we're using, and returns an instance of the appropriate class.  Exit with an
1214  error if we can't figure it out.
1215
1216  Returns:
1217    A VersionControlSystem instance. Exits if the VCS can't be guessed.
1218  """
1219  # Mercurial has a command to get the base directory of a repository
1220  # Try running it, but don't die if we don't have hg installed.
1221  # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
1222  try:
1223    out, returncode = RunShellWithReturnCode(["hg", "root"])
1224    if returncode == 0:
1225      return MercurialVCS(options, out.strip())
1226  except OSError, (errno, message):
1227    if errno != 2:  # ENOENT -- they don't have hg installed.
1228      raise
1229
1230  # Subversion has a .svn in all working directories.
1231  if os.path.isdir('.svn'):
1232    logging.info("Guessed VCS = Subversion")
1233    return SubversionVCS(options)
1234
1235  # Git has a command to test if you're in a git tree.
1236  # Try running it, but don't die if we don't have git installed.
1237  try:
1238    out, returncode = RunShellWithReturnCode(["git", "rev-parse",
1239                                              "--is-inside-work-tree"])
1240    if returncode == 0:
1241      return GitVCS(options)
1242  except OSError, (errno, message):
1243    if errno != 2:  # ENOENT -- they don't have git installed.
1244      raise
1245
1246  ErrorExit(("Could not guess version control system. "
1247             "Are you in a working copy directory?"))
1248
1249
1250def RealMain(argv, data=None):
1251  """The real main function.
1252
1253  Args:
1254    argv: Command line arguments.
1255    data: Diff contents. If None (default) the diff is generated by
1256      the VersionControlSystem implementation returned by GuessVCS().
1257
1258  Returns:
1259    A 2-tuple (issue id, patchset id).
1260    The patchset id is None if the base files are not uploaded by this
1261    script (applies only to SVN checkouts).
1262  """
1263  logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
1264                              "%(lineno)s %(message)s "))
1265  os.environ['LC_ALL'] = 'C'
1266  options, args = parser.parse_args(argv[1:])
1267  global verbosity
1268  verbosity = options.verbose
1269  if verbosity >= 3:
1270    logging.getLogger().setLevel(logging.DEBUG)
1271  elif verbosity >= 2:
1272    logging.getLogger().setLevel(logging.INFO)
1273  vcs = GuessVCS(options)
1274  if isinstance(vcs, SubversionVCS):
1275    # base field is only allowed for Subversion.
1276    # Note: Fetching base files may become deprecated in future releases.
1277    base = vcs.GuessBase(options.download_base)
1278  else:
1279    base = None
1280  if not base and options.download_base:
1281    options.download_base = True
1282    logging.info("Enabled upload of base file")
1283  if not options.assume_yes:
1284    vcs.CheckForUnknownFiles()
1285  if data is None:
1286    data = vcs.GenerateDiff(args)
1287  files = vcs.GetBaseFiles(data)
1288  if verbosity >= 1:
1289    print "Upload server:", options.server, "(change with -s/--server)"
1290  if options.issue:
1291    prompt = "Message describing this patch set: "
1292  else:
1293    prompt = "New issue subject: "
1294  message = options.message or raw_input(prompt).strip()
1295  if not message:
1296    ErrorExit("A non-empty message is required")
1297  rpc_server = GetRpcServer(options)
1298  form_fields = [("subject", message)]
1299  if base:
1300    form_fields.append(("base", base))
1301  if options.issue:
1302    form_fields.append(("issue", str(options.issue)))
1303  if options.email:
1304    form_fields.append(("user", options.email))
1305  if options.reviewers:
1306    for reviewer in options.reviewers.split(','):
1307      if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
1308        ErrorExit("Invalid email address: %s" % reviewer)
1309    form_fields.append(("reviewers", options.reviewers))
1310  if options.cc:
1311    for cc in options.cc.split(','):
1312      if "@" in cc and not cc.split("@")[1].count(".") == 1:
1313        ErrorExit("Invalid email address: %s" % cc)
1314    form_fields.append(("cc", options.cc))
1315  description = options.description
1316  if options.description_file:
1317    if options.description:
1318      ErrorExit("Can't specify description and description_file")
1319    file = open(options.description_file, 'r')
1320    description = file.read()
1321    file.close()
1322  if description:
1323    form_fields.append(("description", description))
1324  # Send a hash of all the base file so the server can determine if a copy
1325  # already exists in an earlier patchset.
1326  base_hashes = ""
1327  for file, info in files.iteritems():
1328    if not info[0] is None:
1329      checksum = md5.new(info[0]).hexdigest()
1330      if base_hashes:
1331        base_hashes += "|"
1332      base_hashes += checksum + ":" + file
1333  form_fields.append(("base_hashes", base_hashes))
1334  # If we're uploading base files, don't send the email before the uploads, so
1335  # that it contains the file status.
1336  if options.send_mail and options.download_base:
1337    form_fields.append(("send_mail", "1"))
1338  if not options.download_base:
1339    form_fields.append(("content_upload", "1"))
1340  if len(data) > MAX_UPLOAD_SIZE:
1341    print "Patch is large, so uploading file patches separately."
1342    uploaded_diff_file = []
1343    form_fields.append(("separate_patches", "1"))
1344  else:
1345    uploaded_diff_file = [("data", "data.diff", data)]
1346  ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
1347  response_body = rpc_server.Send("/upload", body, content_type=ctype)
1348  patchset = None
1349  if not options.download_base or not uploaded_diff_file:
1350    lines = response_body.splitlines()
1351    if len(lines) >= 2:
1352      msg = lines[0]
1353      patchset = lines[1].strip()
1354      patches = [x.split(" ", 1) for x in lines[2:]]
1355    else:
1356      msg = response_body
1357  else:
1358    msg = response_body
1359  StatusUpdate(msg)
1360  if not response_body.startswith("Issue created.") and \
1361  not response_body.startswith("Issue updated."):
1362    sys.exit(0)
1363  issue = msg[msg.rfind("/")+1:]
1364
1365  if not uploaded_diff_file:
1366    result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
1367    if not options.download_base:
1368      patches = result
1369
1370  if not options.download_base:
1371    vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
1372    if options.send_mail:
1373      rpc_server.Send("/" + issue + "/mail", payload="")
1374  return issue, patchset
1375
1376
1377def main():
1378  try:
1379    RealMain(sys.argv)
1380  except KeyboardInterrupt:
1381    print
1382    StatusUpdate("Interrupted.")
1383    sys.exit(1)
1384
1385
1386if __name__ == "__main__":
1387  main()
trunk/3rdparty/googletest/googletest/scripts/upload_gtest.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""upload_gtest.py v0.1.0 -- uploads a Google Test patch for review.
33
34This simple wrapper passes all command line flags and
35--cc=googletestframework@googlegroups.com to upload.py.
36
37USAGE: upload_gtest.py [options for upload.py]
38"""
39
40__author__ = 'wan@google.com (Zhanyong Wan)'
41
42import os
43import sys
44
45CC_FLAG = '--cc='
46GTEST_GROUP = 'googletestframework@googlegroups.com'
47
48
49def main():
50  # Finds the path to upload.py, assuming it is in the same directory
51  # as this file.
52  my_dir = os.path.dirname(os.path.abspath(__file__))
53  upload_py_path = os.path.join(my_dir, 'upload.py')
54
55  # Adds Google Test discussion group to the cc line if it's not there
56  # already.
57  upload_py_argv = [upload_py_path]
58  found_cc_flag = False
59  for arg in sys.argv[1:]:
60    if arg.startswith(CC_FLAG):
61      found_cc_flag = True
62      cc_line = arg[len(CC_FLAG):]
63      cc_list = [addr for addr in cc_line.split(',') if addr]
64      if GTEST_GROUP not in cc_list:
65        cc_list.append(GTEST_GROUP)
66      upload_py_argv.append(CC_FLAG + ','.join(cc_list))
67    else:
68      upload_py_argv.append(arg)
69
70  if not found_cc_flag:
71    upload_py_argv.append(CC_FLAG + GTEST_GROUP)
72
73  # Invokes upload.py with the modified command line flags.
74  os.execv(upload_py_path, upload_py_argv)
75
76
77if __name__ == '__main__':
78  main()
trunk/3rdparty/googletest/googletest/src/gtest-all.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: mheule@google.com (Markus Heule)
31//
32// Google C++ Testing Framework (Google Test)
33//
34// Sometimes it's desirable to build Google Test by compiling a single file.
35// This file serves this purpose.
36
37// This line ensures that gtest.h can be compiled on its own, even
38// when it's fused.
39#include "gtest/gtest.h"
40
41// The following lines pull in the real gtest *.cc files.
42#include "src/gtest.cc"
43#include "src/gtest-death-test.cc"
44#include "src/gtest-filepath.cc"
45#include "src/gtest-port.cc"
46#include "src/gtest-printers.cc"
47#include "src/gtest-test-part.cc"
48#include "src/gtest-typed-test.cc"
trunk/3rdparty/googletest/googletest/src/gtest-death-test.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
31//
32// This file implements death tests.
33
34#include "gtest/gtest-death-test.h"
35#include "gtest/internal/gtest-port.h"
36#include "gtest/internal/custom/gtest.h"
37
38#if GTEST_HAS_DEATH_TEST
39
40# if GTEST_OS_MAC
41#  include <crt_externs.h>
42# endif  // GTEST_OS_MAC
43
44# include <errno.h>
45# include <fcntl.h>
46# include <limits.h>
47
48# if GTEST_OS_LINUX
49#  include <signal.h>
50# endif  // GTEST_OS_LINUX
51
52# include <stdarg.h>
53
54# if GTEST_OS_WINDOWS
55#  include <windows.h>
56# else
57#  include <sys/mman.h>
58#  include <sys/wait.h>
59# endif  // GTEST_OS_WINDOWS
60
61# if GTEST_OS_QNX
62#  include <spawn.h>
63# endif  // GTEST_OS_QNX
64
65#endif  // GTEST_HAS_DEATH_TEST
66
67#include "gtest/gtest-message.h"
68#include "gtest/internal/gtest-string.h"
69
70// Indicates that this translation unit is part of Google Test's
71// implementation.  It must come before gtest-internal-inl.h is
72// included, or there will be a compiler error.  This trick exists to
73// prevent the accidental inclusion of gtest-internal-inl.h in the
74// user's code.
75#define GTEST_IMPLEMENTATION_ 1
76#include "src/gtest-internal-inl.h"
77#undef GTEST_IMPLEMENTATION_
78
79namespace testing {
80
81// Constants.
82
83// The default death test style.
84static const char kDefaultDeathTestStyle[] = "fast";
85
86GTEST_DEFINE_string_(
87    death_test_style,
88    internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
89    "Indicates how to run a death test in a forked child process: "
90    "\"threadsafe\" (child process re-executes the test binary "
91    "from the beginning, running only the specific death test) or "
92    "\"fast\" (child process runs the death test immediately "
93    "after forking).");
94
95GTEST_DEFINE_bool_(
96    death_test_use_fork,
97    internal::BoolFromGTestEnv("death_test_use_fork", false),
98    "Instructs to use fork()/_exit() instead of clone() in death tests. "
99    "Ignored and always uses fork() on POSIX systems where clone() is not "
100    "implemented. Useful when running under valgrind or similar tools if "
101    "those do not support clone(). Valgrind 3.3.1 will just fail if "
102    "it sees an unsupported combination of clone() flags. "
103    "It is not recommended to use this flag w/o valgrind though it will "
104    "work in 99% of the cases. Once valgrind is fixed, this flag will "
105    "most likely be removed.");
106
107namespace internal {
108GTEST_DEFINE_string_(
109    internal_run_death_test, "",
110    "Indicates the file, line number, temporal index of "
111    "the single death test to run, and a file descriptor to "
112    "which a success code may be sent, all separated by "
113    "the '|' characters.  This flag is specified if and only if the current "
114    "process is a sub-process launched for running a thread-safe "
115    "death test.  FOR INTERNAL USE ONLY.");
116}  // namespace internal
117
118#if GTEST_HAS_DEATH_TEST
119
120namespace internal {
121
122// Valid only for fast death tests. Indicates the code is running in the
123// child process of a fast style death test.
124static bool g_in_fast_death_test_child = false;
125
126// Returns a Boolean value indicating whether the caller is currently
127// executing in the context of the death test child process.  Tools such as
128// Valgrind heap checkers may need this to modify their behavior in death
129// tests.  IMPORTANT: This is an internal utility.  Using it may break the
130// implementation of death tests.  User code MUST NOT use it.
131bool InDeathTestChild() {
132# if GTEST_OS_WINDOWS
133
134  // On Windows, death tests are thread-safe regardless of the value of the
135  // death_test_style flag.
136  return !GTEST_FLAG(internal_run_death_test).empty();
137
138# else
139
140  if (GTEST_FLAG(death_test_style) == "threadsafe")
141    return !GTEST_FLAG(internal_run_death_test).empty();
142  else
143    return g_in_fast_death_test_child;
144#endif
145}
146
147}  // namespace internal
148
149// ExitedWithCode constructor.
150ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
151}
152
153// ExitedWithCode function-call operator.
154bool ExitedWithCode::operator()(int exit_status) const {
155# if GTEST_OS_WINDOWS
156
157  return exit_status == exit_code_;
158
159# else
160
161  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
162
163# endif  // GTEST_OS_WINDOWS
164}
165
166# if !GTEST_OS_WINDOWS
167// KilledBySignal constructor.
168KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
169}
170
171// KilledBySignal function-call operator.
172bool KilledBySignal::operator()(int exit_status) const {
173#  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
174  {
175    bool result;
176    if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
177      return result;
178    }
179  }
180#  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
181  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
182}
183# endif  // !GTEST_OS_WINDOWS
184
185namespace internal {
186
187// Utilities needed for death tests.
188
189// Generates a textual description of a given exit code, in the format
190// specified by wait(2).
191static std::string ExitSummary(int exit_code) {
192  Message m;
193
194# if GTEST_OS_WINDOWS
195
196  m << "Exited with exit status " << exit_code;
197
198# else
199
200  if (WIFEXITED(exit_code)) {
201    m << "Exited with exit status " << WEXITSTATUS(exit_code);
202  } else if (WIFSIGNALED(exit_code)) {
203    m << "Terminated by signal " << WTERMSIG(exit_code);
204  }
205#  ifdef WCOREDUMP
206  if (WCOREDUMP(exit_code)) {
207    m << " (core dumped)";
208  }
209#  endif
210# endif  // GTEST_OS_WINDOWS
211
212  return m.GetString();
213}
214
215// Returns true if exit_status describes a process that was terminated
216// by a signal, or exited normally with a nonzero exit code.
217bool ExitedUnsuccessfully(int exit_status) {
218  return !ExitedWithCode(0)(exit_status);
219}
220
221# if !GTEST_OS_WINDOWS
222// Generates a textual failure message when a death test finds more than
223// one thread running, or cannot determine the number of threads, prior
224// to executing the given statement.  It is the responsibility of the
225// caller not to pass a thread_count of 1.
226static std::string DeathTestThreadWarning(size_t thread_count) {
227  Message msg;
228  msg << "Death tests use fork(), which is unsafe particularly"
229      << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
230  if (thread_count == 0)
231    msg << "couldn't detect the number of threads.";
232  else
233    msg << "detected " << thread_count << " threads.";
234  return msg.GetString();
235}
236# endif  // !GTEST_OS_WINDOWS
237
238// Flag characters for reporting a death test that did not die.
239static const char kDeathTestLived = 'L';
240static const char kDeathTestReturned = 'R';
241static const char kDeathTestThrew = 'T';
242static const char kDeathTestInternalError = 'I';
243
244// An enumeration describing all of the possible ways that a death test can
245// conclude.  DIED means that the process died while executing the test
246// code; LIVED means that process lived beyond the end of the test code;
247// RETURNED means that the test statement attempted to execute a return
248// statement, which is not allowed; THREW means that the test statement
249// returned control by throwing an exception.  IN_PROGRESS means the test
250// has not yet concluded.
251// TODO(vladl@google.com): Unify names and possibly values for
252// AbortReason, DeathTestOutcome, and flag characters above.
253enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
254
255// Routine for aborting the program which is safe to call from an
256// exec-style death test child process, in which case the error
257// message is propagated back to the parent process.  Otherwise, the
258// message is simply printed to stderr.  In either case, the program
259// then exits with status 1.
260void DeathTestAbort(const std::string& message) {
261  // On a POSIX system, this function may be called from a threadsafe-style
262  // death test child process, which operates on a very small stack.  Use
263  // the heap for any additional non-minuscule memory requirements.
264  const InternalRunDeathTestFlag* const flag =
265      GetUnitTestImpl()->internal_run_death_test_flag();
266  if (flag != NULL) {
267    FILE* parent = posix::FDOpen(flag->write_fd(), "w");
268    fputc(kDeathTestInternalError, parent);
269    fprintf(parent, "%s", message.c_str());
270    fflush(parent);
271    _exit(1);
272  } else {
273    fprintf(stderr, "%s", message.c_str());
274    fflush(stderr);
275    posix::Abort();
276  }
277}
278
279// A replacement for CHECK that calls DeathTestAbort if the assertion
280// fails.
281# define GTEST_DEATH_TEST_CHECK_(expression) \
282  do { \
283    if (!::testing::internal::IsTrue(expression)) { \
284      DeathTestAbort( \
285          ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
286          + ::testing::internal::StreamableToString(__LINE__) + ": " \
287          + #expression); \
288    } \
289  } while (::testing::internal::AlwaysFalse())
290
291// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
292// evaluating any system call that fulfills two conditions: it must return
293// -1 on failure, and set errno to EINTR when it is interrupted and
294// should be tried again.  The macro expands to a loop that repeatedly
295// evaluates the expression as long as it evaluates to -1 and sets
296// errno to EINTR.  If the expression evaluates to -1 but errno is
297// something other than EINTR, DeathTestAbort is called.
298# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
299  do { \
300    int gtest_retval; \
301    do { \
302      gtest_retval = (expression); \
303    } while (gtest_retval == -1 && errno == EINTR); \
304    if (gtest_retval == -1) { \
305      DeathTestAbort( \
306          ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
307          + ::testing::internal::StreamableToString(__LINE__) + ": " \
308          + #expression + " != -1"); \
309    } \
310  } while (::testing::internal::AlwaysFalse())
311
312// Returns the message describing the last system error in errno.
313std::string GetLastErrnoDescription() {
314    return errno == 0 ? "" : posix::StrError(errno);
315}
316
317// This is called from a death test parent process to read a failure
318// message from the death test child process and log it with the FATAL
319// severity. On Windows, the message is read from a pipe handle. On other
320// platforms, it is read from a file descriptor.
321static void FailFromInternalError(int fd) {
322  Message error;
323  char buffer[256];
324  int num_read;
325
326  do {
327    while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
328      buffer[num_read] = '\0';
329      error << buffer;
330    }
331  } while (num_read == -1 && errno == EINTR);
332
333  if (num_read == 0) {
334    GTEST_LOG_(FATAL) << error.GetString();
335  } else {
336    const int last_error = errno;
337    GTEST_LOG_(FATAL) << "Error while reading death test internal: "
338                      << GetLastErrnoDescription() << " [" << last_error << "]";
339  }
340}
341
342// Death test constructor.  Increments the running death test count
343// for the current test.
344DeathTest::DeathTest() {
345  TestInfo* const info = GetUnitTestImpl()->current_test_info();
346  if (info == NULL) {
347    DeathTestAbort("Cannot run a death test outside of a TEST or "
348                   "TEST_F construct");
349  }
350}
351
352// Creates and returns a death test by dispatching to the current
353// death test factory.
354bool DeathTest::Create(const char* statement, const RE* regex,
355                       const char* file, int line, DeathTest** test) {
356  return GetUnitTestImpl()->death_test_factory()->Create(
357      statement, regex, file, line, test);
358}
359
360const char* DeathTest::LastMessage() {
361  return last_death_test_message_.c_str();
362}
363
364void DeathTest::set_last_death_test_message(const std::string& message) {
365  last_death_test_message_ = message;
366}
367
368std::string DeathTest::last_death_test_message_;
369
370// Provides cross platform implementation for some death functionality.
371class DeathTestImpl : public DeathTest {
372 protected:
373  DeathTestImpl(const char* a_statement, const RE* a_regex)
374      : statement_(a_statement),
375        regex_(a_regex),
376        spawned_(false),
377        status_(-1),
378        outcome_(IN_PROGRESS),
379        read_fd_(-1),
380        write_fd_(-1) {}
381
382  // read_fd_ is expected to be closed and cleared by a derived class.
383  ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
384
385  void Abort(AbortReason reason);
386  virtual bool Passed(bool status_ok);
387
388  const char* statement() const { return statement_; }
389  const RE* regex() const { return regex_; }
390  bool spawned() const { return spawned_; }
391  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
392  int status() const { return status_; }
393  void set_status(int a_status) { status_ = a_status; }
394  DeathTestOutcome outcome() const { return outcome_; }
395  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
396  int read_fd() const { return read_fd_; }
397  void set_read_fd(int fd) { read_fd_ = fd; }
398  int write_fd() const { return write_fd_; }
399  void set_write_fd(int fd) { write_fd_ = fd; }
400
401  // Called in the parent process only. Reads the result code of the death
402  // test child process via a pipe, interprets it to set the outcome_
403  // member, and closes read_fd_.  Outputs diagnostics and terminates in
404  // case of unexpected codes.
405  void ReadAndInterpretStatusByte();
406
407 private:
408  // The textual content of the code this object is testing.  This class
409  // doesn't own this string and should not attempt to delete it.
410  const char* const statement_;
411  // The regular expression which test output must match.  DeathTestImpl
412  // doesn't own this object and should not attempt to delete it.
413  const RE* const regex_;
414  // True if the death test child process has been successfully spawned.
415  bool spawned_;
416  // The exit status of the child process.
417  int status_;
418  // How the death test concluded.
419  DeathTestOutcome outcome_;
420  // Descriptor to the read end of the pipe to the child process.  It is
421  // always -1 in the child process.  The child keeps its write end of the
422  // pipe in write_fd_.
423  int read_fd_;
424  // Descriptor to the child's write end of the pipe to the parent process.
425  // It is always -1 in the parent process.  The parent keeps its end of the
426  // pipe in read_fd_.
427  int write_fd_;
428};
429
430// Called in the parent process only. Reads the result code of the death
431// test child process via a pipe, interprets it to set the outcome_
432// member, and closes read_fd_.  Outputs diagnostics and terminates in
433// case of unexpected codes.
434void DeathTestImpl::ReadAndInterpretStatusByte() {
435  char flag;
436  int bytes_read;
437
438  // The read() here blocks until data is available (signifying the
439  // failure of the death test) or until the pipe is closed (signifying
440  // its success), so it's okay to call this in the parent before
441  // the child process has exited.
442  do {
443    bytes_read = posix::Read(read_fd(), &flag, 1);
444  } while (bytes_read == -1 && errno == EINTR);
445
446  if (bytes_read == 0) {
447    set_outcome(DIED);
448  } else if (bytes_read == 1) {
449    switch (flag) {
450      case kDeathTestReturned:
451        set_outcome(RETURNED);
452        break;
453      case kDeathTestThrew:
454        set_outcome(THREW);
455        break;
456      case kDeathTestLived:
457        set_outcome(LIVED);
458        break;
459      case kDeathTestInternalError:
460        FailFromInternalError(read_fd());  // Does not return.
461        break;
462      default:
463        GTEST_LOG_(FATAL) << "Death test child process reported "
464                          << "unexpected status byte ("
465                          << static_cast<unsigned int>(flag) << ")";
466    }
467  } else {
468    GTEST_LOG_(FATAL) << "Read from death test child process failed: "
469                      << GetLastErrnoDescription();
470  }
471  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
472  set_read_fd(-1);
473}
474
475// Signals that the death test code which should have exited, didn't.
476// Should be called only in a death test child process.
477// Writes a status byte to the child's status file descriptor, then
478// calls _exit(1).
479void DeathTestImpl::Abort(AbortReason reason) {
480  // The parent process considers the death test to be a failure if
481  // it finds any data in our pipe.  So, here we write a single flag byte
482  // to the pipe, then exit.
483  const char status_ch =
484      reason == TEST_DID_NOT_DIE ? kDeathTestLived :
485      reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
486
487  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
488  // We are leaking the descriptor here because on some platforms (i.e.,
489  // when built as Windows DLL), destructors of global objects will still
490  // run after calling _exit(). On such systems, write_fd_ will be
491  // indirectly closed from the destructor of UnitTestImpl, causing double
492  // close if it is also closed here. On debug configurations, double close
493  // may assert. As there are no in-process buffers to flush here, we are
494  // relying on the OS to close the descriptor after the process terminates
495  // when the destructors are not run.
496  _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
497}
498
499// Returns an indented copy of stderr output for a death test.
500// This makes distinguishing death test output lines from regular log lines
501// much easier.
502static ::std::string FormatDeathTestOutput(const ::std::string& output) {
503  ::std::string ret;
504  for (size_t at = 0; ; ) {
505    const size_t line_end = output.find('\n', at);
506    ret += "[  DEATH   ] ";
507    if (line_end == ::std::string::npos) {
508      ret += output.substr(at);
509      break;
510    }
511    ret += output.substr(at, line_end + 1 - at);
512    at = line_end + 1;
513  }
514  return ret;
515}
516
517// Assesses the success or failure of a death test, using both private
518// members which have previously been set, and one argument:
519//
520// Private data members:
521//   outcome:  An enumeration describing how the death test
522//             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
523//             fails in the latter three cases.
524//   status:   The exit status of the child process. On *nix, it is in the
525//             in the format specified by wait(2). On Windows, this is the
526//             value supplied to the ExitProcess() API or a numeric code
527//             of the exception that terminated the program.
528//   regex:    A regular expression object to be applied to
529//             the test's captured standard error output; the death test
530//             fails if it does not match.
531//
532// Argument:
533//   status_ok: true if exit_status is acceptable in the context of
534//              this particular death test, which fails if it is false
535//
536// Returns true iff all of the above conditions are met.  Otherwise, the
537// first failing condition, in the order given above, is the one that is
538// reported. Also sets the last death test message string.
539bool DeathTestImpl::Passed(bool status_ok) {
540  if (!spawned())
541    return false;
542
543  const std::string error_message = GetCapturedStderr();
544
545  bool success = false;
546  Message buffer;
547
548  buffer << "Death test: " << statement() << "\n";
549  switch (outcome()) {
550    case LIVED:
551      buffer << "    Result: failed to die.\n"
552             << " Error msg:\n" << FormatDeathTestOutput(error_message);
553      break;
554    case THREW:
555      buffer << "    Result: threw an exception.\n"
556             << " Error msg:\n" << FormatDeathTestOutput(error_message);
557      break;
558    case RETURNED:
559      buffer << "    Result: illegal return in test statement.\n"
560             << " Error msg:\n" << FormatDeathTestOutput(error_message);
561      break;
562    case DIED:
563      if (status_ok) {
564        const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
565        if (matched) {
566          success = true;
567        } else {
568          buffer << "    Result: died but not with expected error.\n"
569                 << "  Expected: " << regex()->pattern() << "\n"
570                 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
571        }
572      } else {
573        buffer << "    Result: died but not with expected exit code:\n"
574               << "            " << ExitSummary(status()) << "\n"
575               << "Actual msg:\n" << FormatDeathTestOutput(error_message);
576      }
577      break;
578    case IN_PROGRESS:
579    default:
580      GTEST_LOG_(FATAL)
581          << "DeathTest::Passed somehow called before conclusion of test";
582  }
583
584  DeathTest::set_last_death_test_message(buffer.GetString());
585  return success;
586}
587
588# if GTEST_OS_WINDOWS
589// WindowsDeathTest implements death tests on Windows. Due to the
590// specifics of starting new processes on Windows, death tests there are
591// always threadsafe, and Google Test considers the
592// --gtest_death_test_style=fast setting to be equivalent to
593// --gtest_death_test_style=threadsafe there.
594//
595// A few implementation notes:  Like the Linux version, the Windows
596// implementation uses pipes for child-to-parent communication. But due to
597// the specifics of pipes on Windows, some extra steps are required:
598//
599// 1. The parent creates a communication pipe and stores handles to both
600//    ends of it.
601// 2. The parent starts the child and provides it with the information
602//    necessary to acquire the handle to the write end of the pipe.
603// 3. The child acquires the write end of the pipe and signals the parent
604//    using a Windows event.
605// 4. Now the parent can release the write end of the pipe on its side. If
606//    this is done before step 3, the object's reference count goes down to
607//    0 and it is destroyed, preventing the child from acquiring it. The
608//    parent now has to release it, or read operations on the read end of
609//    the pipe will not return when the child terminates.
610// 5. The parent reads child's output through the pipe (outcome code and
611//    any possible error messages) from the pipe, and its stderr and then
612//    determines whether to fail the test.
613//
614// Note: to distinguish Win32 API calls from the local method and function
615// calls, the former are explicitly resolved in the global namespace.
616//
617class WindowsDeathTest : public DeathTestImpl {
618 public:
619  WindowsDeathTest(const char* a_statement,
620                   const RE* a_regex,
621                   const char* file,
622                   int line)
623      : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
624
625  // All of these virtual functions are inherited from DeathTest.
626  virtual int Wait();
627  virtual TestRole AssumeRole();
628
629 private:
630  // The name of the file in which the death test is located.
631  const char* const file_;
632  // The line number on which the death test is located.
633  const int line_;
634  // Handle to the write end of the pipe to the child process.
635  AutoHandle write_handle_;
636  // Child process handle.
637  AutoHandle child_handle_;
638  // Event the child process uses to signal the parent that it has
639  // acquired the handle to the write end of the pipe. After seeing this
640  // event the parent can release its own handles to make sure its
641  // ReadFile() calls return when the child terminates.
642  AutoHandle event_handle_;
643};
644
645// Waits for the child in a death test to exit, returning its exit
646// status, or 0 if no child process exists.  As a side effect, sets the
647// outcome data member.
648int WindowsDeathTest::Wait() {
649  if (!spawned())
650    return 0;
651
652  // Wait until the child either signals that it has acquired the write end
653  // of the pipe or it dies.
654  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
655  switch (::WaitForMultipleObjects(2,
656                                   wait_handles,
657                                   FALSE,  // Waits for any of the handles.
658                                   INFINITE)) {
659    case WAIT_OBJECT_0:
660    case WAIT_OBJECT_0 + 1:
661      break;
662    default:
663      GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
664  }
665
666  // The child has acquired the write end of the pipe or exited.
667  // We release the handle on our side and continue.
668  write_handle_.Reset();
669  event_handle_.Reset();
670
671  ReadAndInterpretStatusByte();
672
673  // Waits for the child process to exit if it haven't already. This
674  // returns immediately if the child has already exited, regardless of
675  // whether previous calls to WaitForMultipleObjects synchronized on this
676  // handle or not.
677  GTEST_DEATH_TEST_CHECK_(
678      WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
679                                             INFINITE));
680  DWORD status_code;
681  GTEST_DEATH_TEST_CHECK_(
682      ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
683  child_handle_.Reset();
684  set_status(static_cast<int>(status_code));
685  return status();
686}
687
688// The AssumeRole process for a Windows death test.  It creates a child
689// process with the same executable as the current process to run the
690// death test.  The child process is given the --gtest_filter and
691// --gtest_internal_run_death_test flags such that it knows to run the
692// current death test only.
693DeathTest::TestRole WindowsDeathTest::AssumeRole() {
694  const UnitTestImpl* const impl = GetUnitTestImpl();
695  const InternalRunDeathTestFlag* const flag =
696      impl->internal_run_death_test_flag();
697  const TestInfo* const info = impl->current_test_info();
698  const int death_test_index = info->result()->death_test_count();
699
700  if (flag != NULL) {
701    // ParseInternalRunDeathTestFlag() has performed all the necessary
702    // processing.
703    set_write_fd(flag->write_fd());
704    return EXECUTE_TEST;
705  }
706
707  // WindowsDeathTest uses an anonymous pipe to communicate results of
708  // a death test.
709  SECURITY_ATTRIBUTES handles_are_inheritable = {
710    sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
711  HANDLE read_handle, write_handle;
712  GTEST_DEATH_TEST_CHECK_(
713      ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
714                   0)  // Default buffer size.
715      != FALSE);
716  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
717                                O_RDONLY));
718  write_handle_.Reset(write_handle);
719  event_handle_.Reset(::CreateEvent(
720      &handles_are_inheritable,
721      TRUE,    // The event will automatically reset to non-signaled state.
722      FALSE,   // The initial state is non-signalled.
723      NULL));  // The even is unnamed.
724  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
725  const std::string filter_flag =
726      std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
727      info->test_case_name() + "." + info->name();
728  const std::string internal_flag =
729      std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
730      "=" + file_ + "|" + StreamableToString(line_) + "|" +
731      StreamableToString(death_test_index) + "|" +
732      StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
733      // size_t has the same width as pointers on both 32-bit and 64-bit
734      // Windows platforms.
735      // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
736      "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
737      "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
738
739  char executable_path[_MAX_PATH + 1];  // NOLINT
740  GTEST_DEATH_TEST_CHECK_(
741      _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
742                                            executable_path,
743                                            _MAX_PATH));
744
745  std::string command_line =
746      std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
747      internal_flag + "\"";
748
749  DeathTest::set_last_death_test_message("");
750
751  CaptureStderr();
752  // Flush the log buffers since the log streams are shared with the child.
753  FlushInfoLog();
754
755  // The child process will share the standard handles with the parent.
756  STARTUPINFOA startup_info;
757  memset(&startup_info, 0, sizeof(STARTUPINFO));
758  startup_info.dwFlags = STARTF_USESTDHANDLES;
759  startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
760  startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
761  startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
762
763  PROCESS_INFORMATION process_info;
764  GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
765      executable_path,
766      const_cast<char*>(command_line.c_str()),
767      NULL,   // Retuned process handle is not inheritable.
768      NULL,   // Retuned thread handle is not inheritable.
769      TRUE,   // Child inherits all inheritable handles (for write_handle_).
770      0x0,    // Default creation flags.
771      NULL,   // Inherit the parent's environment.
772      UnitTest::GetInstance()->original_working_dir(),
773      &startup_info,
774      &process_info) != FALSE);
775  child_handle_.Reset(process_info.hProcess);
776  ::CloseHandle(process_info.hThread);
777  set_spawned(true);
778  return OVERSEE_TEST;
779}
780# else  // We are not on Windows.
781
782// ForkingDeathTest provides implementations for most of the abstract
783// methods of the DeathTest interface.  Only the AssumeRole method is
784// left undefined.
785class ForkingDeathTest : public DeathTestImpl {
786 public:
787  ForkingDeathTest(const char* statement, const RE* regex);
788
789  // All of these virtual functions are inherited from DeathTest.
790  virtual int Wait();
791
792 protected:
793  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
794
795 private:
796  // PID of child process during death test; 0 in the child process itself.
797  pid_t child_pid_;
798};
799
800// Constructs a ForkingDeathTest.
801ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
802    : DeathTestImpl(a_statement, a_regex),
803      child_pid_(-1) {}
804
805// Waits for the child in a death test to exit, returning its exit
806// status, or 0 if no child process exists.  As a side effect, sets the
807// outcome data member.
808int ForkingDeathTest::Wait() {
809  if (!spawned())
810    return 0;
811
812  ReadAndInterpretStatusByte();
813
814  int status_value;
815  GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
816  set_status(status_value);
817  return status_value;
818}
819
820// A concrete death test class that forks, then immediately runs the test
821// in the child process.
822class NoExecDeathTest : public ForkingDeathTest {
823 public:
824  NoExecDeathTest(const char* a_statement, const RE* a_regex) :
825      ForkingDeathTest(a_statement, a_regex) { }
826  virtual TestRole AssumeRole();
827};
828
829// The AssumeRole process for a fork-and-run death test.  It implements a
830// straightforward fork, with a simple pipe to transmit the status byte.
831DeathTest::TestRole NoExecDeathTest::AssumeRole() {
832  const size_t thread_count = GetThreadCount();
833  if (thread_count != 1) {
834    GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
835  }
836
837  int pipe_fd[2];
838  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
839
840  DeathTest::set_last_death_test_message("");
841  CaptureStderr();
842  // When we fork the process below, the log file buffers are copied, but the
843  // file descriptors are shared.  We flush all log files here so that closing
844  // the file descriptors in the child process doesn't throw off the
845  // synchronization between descriptors and buffers in the parent process.
846  // This is as close to the fork as possible to avoid a race condition in case
847  // there are multiple threads running before the death test, and another
848  // thread writes to the log file.
849  FlushInfoLog();
850
851  const pid_t child_pid = fork();
852  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
853  set_child_pid(child_pid);
854  if (child_pid == 0) {
855    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
856    set_write_fd(pipe_fd[1]);
857    // Redirects all logging to stderr in the child process to prevent
858    // concurrent writes to the log files.  We capture stderr in the parent
859    // process and append the child process' output to a log.
860    LogToStderr();
861    // Event forwarding to the listeners of event listener API mush be shut
862    // down in death test subprocesses.
863    GetUnitTestImpl()->listeners()->SuppressEventForwarding();
864    g_in_fast_death_test_child = true;
865    return EXECUTE_TEST;
866  } else {
867    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
868    set_read_fd(pipe_fd[0]);
869    set_spawned(true);
870    return OVERSEE_TEST;
871  }
872}
873
874// A concrete death test class that forks and re-executes the main
875// program from the beginning, with command-line flags set that cause
876// only this specific death test to be run.
877class ExecDeathTest : public ForkingDeathTest {
878 public:
879  ExecDeathTest(const char* a_statement, const RE* a_regex,
880                const char* file, int line) :
881      ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
882  virtual TestRole AssumeRole();
883 private:
884  static ::std::vector<testing::internal::string>
885  GetArgvsForDeathTestChildProcess() {
886    ::std::vector<testing::internal::string> args = GetInjectableArgvs();
887#  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
888    ::std::vector<testing::internal::string> extra_args =
889        GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
890    args.insert(args.end(), extra_args.begin(), extra_args.end());
891#  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
892    return args;
893  }
894  // The name of the file in which the death test is located.
895  const char* const file_;
896  // The line number on which the death test is located.
897  const int line_;
898};
899
900// Utility class for accumulating command-line arguments.
901class Arguments {
902 public:
903  Arguments() {
904    args_.push_back(NULL);
905  }
906
907  ~Arguments() {
908    for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
909         ++i) {
910      free(*i);
911    }
912  }
913  void AddArgument(const char* argument) {
914    args_.insert(args_.end() - 1, posix::StrDup(argument));
915  }
916
917  template <typename Str>
918  void AddArguments(const ::std::vector<Str>& arguments) {
919    for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
920         i != arguments.end();
921         ++i) {
922      args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
923    }
924  }
925  char* const* Argv() {
926    return &args_[0];
927  }
928
929 private:
930  std::vector<char*> args_;
931};
932
933// A struct that encompasses the arguments to the child process of a
934// threadsafe-style death test process.
935struct ExecDeathTestArgs {
936  char* const* argv;  // Command-line arguments for the child's call to exec
937  int close_fd;       // File descriptor to close; the read end of a pipe
938};
939
940#  if GTEST_OS_MAC
941inline char** GetEnviron() {
942  // When Google Test is built as a framework on MacOS X, the environ variable
943  // is unavailable. Apple's documentation (man environ) recommends using
944  // _NSGetEnviron() instead.
945  return *_NSGetEnviron();
946}
947#  else
948// Some POSIX platforms expect you to declare environ. extern "C" makes
949// it reside in the global namespace.
950extern "C" char** environ;
951inline char** GetEnviron() { return environ; }
952#  endif  // GTEST_OS_MAC
953
954#  if !GTEST_OS_QNX
955// The main function for a threadsafe-style death test child process.
956// This function is called in a clone()-ed process and thus must avoid
957// any potentially unsafe operations like malloc or libc functions.
958static int ExecDeathTestChildMain(void* child_arg) {
959  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
960  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
961
962  // We need to execute the test program in the same environment where
963  // it was originally invoked.  Therefore we change to the original
964  // working directory first.
965  const char* const original_dir =
966      UnitTest::GetInstance()->original_working_dir();
967  // We can safely call chdir() as it's a direct system call.
968  if (chdir(original_dir) != 0) {
969    DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
970                   GetLastErrnoDescription());
971    return EXIT_FAILURE;
972  }
973
974  // We can safely call execve() as it's a direct system call.  We
975  // cannot use execvp() as it's a libc function and thus potentially
976  // unsafe.  Since execve() doesn't search the PATH, the user must
977  // invoke the test program via a valid path that contains at least
978  // one path separator.
979  execve(args->argv[0], args->argv, GetEnviron());
980  DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
981                 original_dir + " failed: " +
982                 GetLastErrnoDescription());
983  return EXIT_FAILURE;
984}
985#  endif  // !GTEST_OS_QNX
986
987// Two utility routines that together determine the direction the stack
988// grows.
989// This could be accomplished more elegantly by a single recursive
990// function, but we want to guard against the unlikely possibility of
991// a smart compiler optimizing the recursion away.
992//
993// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
994// StackLowerThanAddress into StackGrowsDown, which then doesn't give
995// correct answer.
996void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
997void StackLowerThanAddress(const void* ptr, bool* result) {
998  int dummy;
999  *result = (&dummy < ptr);
1000}
1001
1002// Make sure AddressSanitizer does not tamper with the stack here.
1003GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1004bool StackGrowsDown() {
1005  int dummy;
1006  bool result;
1007  StackLowerThanAddress(&dummy, &result);
1008  return result;
1009}
1010
1011// Spawns a child process with the same executable as the current process in
1012// a thread-safe manner and instructs it to run the death test.  The
1013// implementation uses fork(2) + exec.  On systems where clone(2) is
1014// available, it is used instead, being slightly more thread-safe.  On QNX,
1015// fork supports only single-threaded environments, so this function uses
1016// spawn(2) there instead.  The function dies with an error message if
1017// anything goes wrong.
1018static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
1019  ExecDeathTestArgs args = { argv, close_fd };
1020  pid_t child_pid = -1;
1021
1022#  if GTEST_OS_QNX
1023  // Obtains the current directory and sets it to be closed in the child
1024  // process.
1025  const int cwd_fd = open(".", O_RDONLY);
1026  GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
1027  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
1028  // We need to execute the test program in the same environment where
1029  // it was originally invoked.  Therefore we change to the original
1030  // working directory first.
1031  const char* const original_dir =
1032      UnitTest::GetInstance()->original_working_dir();
1033  // We can safely call chdir() as it's a direct system call.
1034  if (chdir(original_dir) != 0) {
1035    DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
1036                   GetLastErrnoDescription());
1037    return EXIT_FAILURE;
1038  }
1039
1040  int fd_flags;
1041  // Set close_fd to be closed after spawn.
1042  GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
1043  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
1044                                        fd_flags | FD_CLOEXEC));
1045  struct inheritance inherit = {0};
1046  // spawn is a system call.
1047  child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
1048  // Restores the current working directory.
1049  GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
1050  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
1051
1052#  else   // GTEST_OS_QNX
1053#   if GTEST_OS_LINUX
1054  // When a SIGPROF signal is received while fork() or clone() are executing,
1055  // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
1056  // it after the call to fork()/clone() is complete.
1057  struct sigaction saved_sigprof_action;
1058  struct sigaction ignore_sigprof_action;
1059  memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
1060  sigemptyset(&ignore_sigprof_action.sa_mask);
1061  ignore_sigprof_action.sa_handler = SIG_IGN;
1062  GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
1063      SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
1064#   endif  // GTEST_OS_LINUX
1065
1066#   if GTEST_HAS_CLONE
1067  const bool use_fork = GTEST_FLAG(death_test_use_fork);
1068
1069  if (!use_fork) {
1070    static const bool stack_grows_down = StackGrowsDown();
1071    const size_t stack_size = getpagesize();
1072    // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
1073    void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
1074                             MAP_ANON | MAP_PRIVATE, -1, 0);
1075    GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1076
1077    // Maximum stack alignment in bytes:  For a downward-growing stack, this
1078    // amount is subtracted from size of the stack space to get an address
1079    // that is within the stack space and is aligned on all systems we care
1080    // about.  As far as I know there is no ABI with stack alignment greater
1081    // than 64.  We assume stack and stack_size already have alignment of
1082    // kMaxStackAlignment.
1083    const size_t kMaxStackAlignment = 64;
1084    void* const stack_top =
1085        static_cast<char*>(stack) +
1086            (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
1087    GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
1088        reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
1089
1090    child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
1091
1092    GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
1093  }
1094#   else
1095  const bool use_fork = true;
1096#   endif  // GTEST_HAS_CLONE
1097
1098  if (use_fork && (child_pid = fork()) == 0) {
1099      ExecDeathTestChildMain(&args);
1100      _exit(0);
1101  }
1102#  endif  // GTEST_OS_QNX
1103#  if GTEST_OS_LINUX
1104  GTEST_DEATH_TEST_CHECK_SYSCALL_(
1105      sigaction(SIGPROF, &saved_sigprof_action, NULL));
1106#  endif  // GTEST_OS_LINUX
1107
1108  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1109  return child_pid;
1110}
1111
1112// The AssumeRole process for a fork-and-exec death test.  It re-executes the
1113// main program from the beginning, setting the --gtest_filter
1114// and --gtest_internal_run_death_test flags to cause only the current
1115// death test to be re-run.
1116DeathTest::TestRole ExecDeathTest::AssumeRole() {
1117  const UnitTestImpl* const impl = GetUnitTestImpl();
1118  const InternalRunDeathTestFlag* const flag =
1119      impl->internal_run_death_test_flag();
1120  const TestInfo* const info = impl->current_test_info();
1121  const int death_test_index = info->result()->death_test_count();
1122
1123  if (flag != NULL) {
1124    set_write_fd(flag->write_fd());
1125    return EXECUTE_TEST;
1126  }
1127
1128  int pipe_fd[2];
1129  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1130  // Clear the close-on-exec flag on the write end of the pipe, lest
1131  // it be closed when the child process does an exec:
1132  GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1133
1134  const std::string filter_flag =
1135      std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
1136      + info->test_case_name() + "." + info->name();
1137  const std::string internal_flag =
1138      std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
1139      + file_ + "|" + StreamableToString(line_) + "|"
1140      + StreamableToString(death_test_index) + "|"
1141      + StreamableToString(pipe_fd[1]);
1142  Arguments args;
1143  args.AddArguments(GetArgvsForDeathTestChildProcess());
1144  args.AddArgument(filter_flag.c_str());
1145  args.AddArgument(internal_flag.c_str());
1146
1147  DeathTest::set_last_death_test_message("");
1148
1149  CaptureStderr();
1150  // See the comment in NoExecDeathTest::AssumeRole for why the next line
1151  // is necessary.
1152  FlushInfoLog();
1153
1154  const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
1155  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1156  set_child_pid(child_pid);
1157  set_read_fd(pipe_fd[0]);
1158  set_spawned(true);
1159  return OVERSEE_TEST;
1160}
1161
1162# endif  // !GTEST_OS_WINDOWS
1163
1164// Creates a concrete DeathTest-derived class that depends on the
1165// --gtest_death_test_style flag, and sets the pointer pointed to
1166// by the "test" argument to its address.  If the test should be
1167// skipped, sets that pointer to NULL.  Returns true, unless the
1168// flag is set to an invalid value.
1169bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
1170                                     const char* file, int line,
1171                                     DeathTest** test) {
1172  UnitTestImpl* const impl = GetUnitTestImpl();
1173  const InternalRunDeathTestFlag* const flag =
1174      impl->internal_run_death_test_flag();
1175  const int death_test_index = impl->current_test_info()
1176      ->increment_death_test_count();
1177
1178  if (flag != NULL) {
1179    if (death_test_index > flag->index()) {
1180      DeathTest::set_last_death_test_message(
1181          "Death test count (" + StreamableToString(death_test_index)
1182          + ") somehow exceeded expected maximum ("
1183          + StreamableToString(flag->index()) + ")");
1184      return false;
1185    }
1186
1187    if (!(flag->file() == file && flag->line() == line &&
1188          flag->index() == death_test_index)) {
1189      *test = NULL;
1190      return true;
1191    }
1192  }
1193
1194# if GTEST_OS_WINDOWS
1195
1196  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
1197      GTEST_FLAG(death_test_style) == "fast") {
1198    *test = new WindowsDeathTest(statement, regex, file, line);
1199  }
1200
1201# else
1202
1203  if (GTEST_FLAG(death_test_style) == "threadsafe") {
1204    *test = new ExecDeathTest(statement, regex, file, line);
1205  } else if (GTEST_FLAG(death_test_style) == "fast") {
1206    *test = new NoExecDeathTest(statement, regex);
1207  }
1208
1209# endif  // GTEST_OS_WINDOWS
1210
1211  else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
1212    DeathTest::set_last_death_test_message(
1213        "Unknown death test style \"" + GTEST_FLAG(death_test_style)
1214        + "\" encountered");
1215    return false;
1216  }
1217
1218  return true;
1219}
1220
1221# if GTEST_OS_WINDOWS
1222// Recreates the pipe and event handles from the provided parameters,
1223// signals the event, and returns a file descriptor wrapped around the pipe
1224// handle. This function is called in the child process only.
1225int GetStatusFileDescriptor(unsigned int parent_process_id,
1226                            size_t write_handle_as_size_t,
1227                            size_t event_handle_as_size_t) {
1228  AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1229                                                   FALSE,  // Non-inheritable.
1230                                                   parent_process_id));
1231  if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1232    DeathTestAbort("Unable to open parent process " +
1233                   StreamableToString(parent_process_id));
1234  }
1235
1236  // TODO(vladl@google.com): Replace the following check with a
1237  // compile-time assertion when available.
1238  GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
1239
1240  const HANDLE write_handle =
1241      reinterpret_cast<HANDLE>(write_handle_as_size_t);
1242  HANDLE dup_write_handle;
1243
1244  // The newly initialized handle is accessible only in in the parent
1245  // process. To obtain one accessible within the child, we need to use
1246  // DuplicateHandle.
1247  if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1248                         ::GetCurrentProcess(), &dup_write_handle,
1249                         0x0,    // Requested privileges ignored since
1250                                 // DUPLICATE_SAME_ACCESS is used.
1251                         FALSE,  // Request non-inheritable handler.
1252                         DUPLICATE_SAME_ACCESS)) {
1253    DeathTestAbort("Unable to duplicate the pipe handle " +
1254                   StreamableToString(write_handle_as_size_t) +
1255                   " from the parent process " +
1256                   StreamableToString(parent_process_id));
1257  }
1258
1259  const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
1260  HANDLE dup_event_handle;
1261
1262  if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1263                         ::GetCurrentProcess(), &dup_event_handle,
1264                         0x0,
1265                         FALSE,
1266                         DUPLICATE_SAME_ACCESS)) {
1267    DeathTestAbort("Unable to duplicate the event handle " +
1268                   StreamableToString(event_handle_as_size_t) +
1269                   " from the parent process " +
1270                   StreamableToString(parent_process_id));
1271  }
1272
1273  const int write_fd =
1274      ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
1275  if (write_fd == -1) {
1276    DeathTestAbort("Unable to convert pipe handle " +
1277                   StreamableToString(write_handle_as_size_t) +
1278                   " to a file descriptor");
1279  }
1280
1281  // Signals the parent that the write end of the pipe has been acquired
1282  // so the parent can release its own write end.
1283  ::SetEvent(dup_event_handle);
1284
1285  return write_fd;
1286}
1287# endif  // GTEST_OS_WINDOWS
1288
1289// Returns a newly created InternalRunDeathTestFlag object with fields
1290// initialized from the GTEST_FLAG(internal_run_death_test) flag if
1291// the flag is specified; otherwise returns NULL.
1292InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1293  if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
1294
1295  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1296  // can use it here.
1297  int line = -1;
1298  int index = -1;
1299  ::std::vector< ::std::string> fields;
1300  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
1301  int write_fd = -1;
1302
1303# if GTEST_OS_WINDOWS
1304
1305  unsigned int parent_process_id = 0;
1306  size_t write_handle_as_size_t = 0;
1307  size_t event_handle_as_size_t = 0;
1308
1309  if (fields.size() != 6
1310      || !ParseNaturalNumber(fields[1], &line)
1311      || !ParseNaturalNumber(fields[2], &index)
1312      || !ParseNaturalNumber(fields[3], &parent_process_id)
1313      || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
1314      || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1315    DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
1316                   GTEST_FLAG(internal_run_death_test));
1317  }
1318  write_fd = GetStatusFileDescriptor(parent_process_id,
1319                                     write_handle_as_size_t,
1320                                     event_handle_as_size_t);
1321# else
1322
1323  if (fields.size() != 4
1324      || !ParseNaturalNumber(fields[1], &line)
1325      || !ParseNaturalNumber(fields[2], &index)
1326      || !ParseNaturalNumber(fields[3], &write_fd)) {
1327    DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
1328        + GTEST_FLAG(internal_run_death_test));
1329  }
1330
1331# endif  // GTEST_OS_WINDOWS
1332
1333  return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
1334}
1335
1336}  // namespace internal
1337
1338#endif  // GTEST_HAS_DEATH_TEST
1339
1340}  // namespace testing
trunk/3rdparty/googletest/googletest/src/gtest-filepath.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: keith.ray@gmail.com (Keith Ray)
31
32#include "gtest/gtest-message.h"
33#include "gtest/internal/gtest-filepath.h"
34#include "gtest/internal/gtest-port.h"
35
36#include <stdlib.h>
37
38#if GTEST_OS_WINDOWS_MOBILE
39# include <windows.h>
40#elif GTEST_OS_WINDOWS
41# include <direct.h>
42# include <io.h>
43#elif GTEST_OS_SYMBIAN
44// Symbian OpenC has PATH_MAX in sys/syslimits.h
45# include <sys/syslimits.h>
46#else
47# include <limits.h>
48# include <climits>  // Some Linux distributions define PATH_MAX here.
49#endif  // GTEST_OS_WINDOWS_MOBILE
50
51#if GTEST_OS_WINDOWS
52# define GTEST_PATH_MAX_ _MAX_PATH
53#elif defined(PATH_MAX)
54# define GTEST_PATH_MAX_ PATH_MAX
55#elif defined(_XOPEN_PATH_MAX)
56# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
57#else
58# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
59#endif  // GTEST_OS_WINDOWS
60
61#include "gtest/internal/gtest-string.h"
62
63namespace testing {
64namespace internal {
65
66#if GTEST_OS_WINDOWS
67// On Windows, '\\' is the standard path separator, but many tools and the
68// Windows API also accept '/' as an alternate path separator. Unless otherwise
69// noted, a file path can contain either kind of path separators, or a mixture
70// of them.
71const char kPathSeparator = '\\';
72const char kAlternatePathSeparator = '/';
73const char kAlternatePathSeparatorString[] = "/";
74# if GTEST_OS_WINDOWS_MOBILE
75// Windows CE doesn't have a current directory. You should not use
76// the current directory in tests on Windows CE, but this at least
77// provides a reasonable fallback.
78const char kCurrentDirectoryString[] = "\\";
79// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
80const DWORD kInvalidFileAttributes = 0xffffffff;
81# else
82const char kCurrentDirectoryString[] = ".\\";
83# endif  // GTEST_OS_WINDOWS_MOBILE
84#else
85const char kPathSeparator = '/';
86const char kCurrentDirectoryString[] = "./";
87#endif  // GTEST_OS_WINDOWS
88
89// Returns whether the given character is a valid path separator.
90static bool IsPathSeparator(char c) {
91#if GTEST_HAS_ALT_PATH_SEP_
92  return (c == kPathSeparator) || (c == kAlternatePathSeparator);
93#else
94  return c == kPathSeparator;
95#endif
96}
97
98// Returns the current working directory, or "" if unsuccessful.
99FilePath FilePath::GetCurrentDir() {
100#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
101  // Windows CE doesn't have a current directory, so we just return
102  // something reasonable.
103  return FilePath(kCurrentDirectoryString);
104#elif GTEST_OS_WINDOWS
105  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
106  return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
107#else
108  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
109  char* result = getcwd(cwd, sizeof(cwd));
110# if GTEST_OS_NACL
111  // getcwd will likely fail in NaCl due to the sandbox, so return something
112  // reasonable. The user may have provided a shim implementation for getcwd,
113  // however, so fallback only when failure is detected.
114  return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
115# endif  // GTEST_OS_NACL
116  return FilePath(result == NULL ? "" : cwd);
117#endif  // GTEST_OS_WINDOWS_MOBILE
118}
119
120// Returns a copy of the FilePath with the case-insensitive extension removed.
121// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
122// FilePath("dir/file"). If a case-insensitive extension is not
123// found, returns a copy of the original FilePath.
124FilePath FilePath::RemoveExtension(const char* extension) const {
125  const std::string dot_extension = std::string(".") + extension;
126  if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
127    return FilePath(pathname_.substr(
128        0, pathname_.length() - dot_extension.length()));
129  }
130  return *this;
131}
132
133// Returns a pointer to the last occurence of a valid path separator in
134// the FilePath. On Windows, for example, both '/' and '\' are valid path
135// separators. Returns NULL if no path separator was found.
136const char* FilePath::FindLastPathSeparator() const {
137  const char* const last_sep = strrchr(c_str(), kPathSeparator);
138#if GTEST_HAS_ALT_PATH_SEP_
139  const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
140  // Comparing two pointers of which only one is NULL is undefined.
141  if (last_alt_sep != NULL &&
142      (last_sep == NULL || last_alt_sep > last_sep)) {
143    return last_alt_sep;
144  }
145#endif
146  return last_sep;
147}
148
149// Returns a copy of the FilePath with the directory part removed.
150// Example: FilePath("path/to/file").RemoveDirectoryName() returns
151// FilePath("file"). If there is no directory part ("just_a_file"), it returns
152// the FilePath unmodified. If there is no file part ("just_a_dir/") it
153// returns an empty FilePath ("").
154// On Windows platform, '\' is the path separator, otherwise it is '/'.
155FilePath FilePath::RemoveDirectoryName() const {
156  const char* const last_sep = FindLastPathSeparator();
157  return last_sep ? FilePath(last_sep + 1) : *this;
158}
159
160// RemoveFileName returns the directory path with the filename removed.
161// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
162// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
163// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
164// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
165// On Windows platform, '\' is the path separator, otherwise it is '/'.
166FilePath FilePath::RemoveFileName() const {
167  const char* const last_sep = FindLastPathSeparator();
168  std::string dir;
169  if (last_sep) {
170    dir = std::string(c_str(), last_sep + 1 - c_str());
171  } else {
172    dir = kCurrentDirectoryString;
173  }
174  return FilePath(dir);
175}
176
177// Helper functions for naming files in a directory for xml output.
178
179// Given directory = "dir", base_name = "test", number = 0,
180// extension = "xml", returns "dir/test.xml". If number is greater
181// than zero (e.g., 12), returns "dir/test_12.xml".
182// On Windows platform, uses \ as the separator rather than /.
183FilePath FilePath::MakeFileName(const FilePath& directory,
184                                const FilePath& base_name,
185                                int number,
186                                const char* extension) {
187  std::string file;
188  if (number == 0) {
189    file = base_name.string() + "." + extension;
190  } else {
191    file = base_name.string() + "_" + StreamableToString(number)
192        + "." + extension;
193  }
194  return ConcatPaths(directory, FilePath(file));
195}
196
197// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
198// On Windows, uses \ as the separator rather than /.
199FilePath FilePath::ConcatPaths(const FilePath& directory,
200                               const FilePath& relative_path) {
201  if (directory.IsEmpty())
202    return relative_path;
203  const FilePath dir(directory.RemoveTrailingPathSeparator());
204  return FilePath(dir.string() + kPathSeparator + relative_path.string());
205}
206
207// Returns true if pathname describes something findable in the file-system,
208// either a file, directory, or whatever.
209bool FilePath::FileOrDirectoryExists() const {
210#if GTEST_OS_WINDOWS_MOBILE
211  LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
212  const DWORD attributes = GetFileAttributes(unicode);
213  delete [] unicode;
214  return attributes != kInvalidFileAttributes;
215#else
216  posix::StatStruct file_stat;
217  return posix::Stat(pathname_.c_str(), &file_stat) == 0;
218#endif  // GTEST_OS_WINDOWS_MOBILE
219}
220
221// Returns true if pathname describes a directory in the file-system
222// that exists.
223bool FilePath::DirectoryExists() const {
224  bool result = false;
225#if GTEST_OS_WINDOWS
226  // Don't strip off trailing separator if path is a root directory on
227  // Windows (like "C:\\").
228  const FilePath& path(IsRootDirectory() ? *this :
229                                           RemoveTrailingPathSeparator());
230#else
231  const FilePath& path(*this);
232#endif
233
234#if GTEST_OS_WINDOWS_MOBILE
235  LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
236  const DWORD attributes = GetFileAttributes(unicode);
237  delete [] unicode;
238  if ((attributes != kInvalidFileAttributes) &&
239      (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
240    result = true;
241  }
242#else
243  posix::StatStruct file_stat;
244  result = posix::Stat(path.c_str(), &file_stat) == 0 &&
245      posix::IsDir(file_stat);
246#endif  // GTEST_OS_WINDOWS_MOBILE
247
248  return result;
249}
250
251// Returns true if pathname describes a root directory. (Windows has one
252// root directory per disk drive.)
253bool FilePath::IsRootDirectory() const {
254#if GTEST_OS_WINDOWS
255  // TODO(wan@google.com): on Windows a network share like
256  // \\server\share can be a root directory, although it cannot be the
257  // current directory.  Handle this properly.
258  return pathname_.length() == 3 && IsAbsolutePath();
259#else
260  return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
261#endif
262}
263
264// Returns true if pathname describes an absolute path.
265bool FilePath::IsAbsolutePath() const {
266  const char* const name = pathname_.c_str();
267#if GTEST_OS_WINDOWS
268  return pathname_.length() >= 3 &&
269     ((name[0] >= 'a' && name[0] <= 'z') ||
270      (name[0] >= 'A' && name[0] <= 'Z')) &&
271     name[1] == ':' &&
272     IsPathSeparator(name[2]);
273#else
274  return IsPathSeparator(name[0]);
275#endif
276}
277
278// Returns a pathname for a file that does not currently exist. The pathname
279// will be directory/base_name.extension or
280// directory/base_name_<number>.extension if directory/base_name.extension
281// already exists. The number will be incremented until a pathname is found
282// that does not already exist.
283// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
284// There could be a race condition if two or more processes are calling this
285// function at the same time -- they could both pick the same filename.
286FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
287                                          const FilePath& base_name,
288                                          const char* extension) {
289  FilePath full_pathname;
290  int number = 0;
291  do {
292    full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
293  } while (full_pathname.FileOrDirectoryExists());
294  return full_pathname;
295}
296
297// Returns true if FilePath ends with a path separator, which indicates that
298// it is intended to represent a directory. Returns false otherwise.
299// This does NOT check that a directory (or file) actually exists.
300bool FilePath::IsDirectory() const {
301  return !pathname_.empty() &&
302         IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
303}
304
305// Create directories so that path exists. Returns true if successful or if
306// the directories already exist; returns false if unable to create directories
307// for any reason.
308bool FilePath::CreateDirectoriesRecursively() const {
309  if (!this->IsDirectory()) {
310    return false;
311  }
312
313  if (pathname_.length() == 0 || this->DirectoryExists()) {
314    return true;
315  }
316
317  const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
318  return parent.CreateDirectoriesRecursively() && this->CreateFolder();
319}
320
321// Create the directory so that path exists. Returns true if successful or
322// if the directory already exists; returns false if unable to create the
323// directory for any reason, including if the parent directory does not
324// exist. Not named "CreateDirectory" because that's a macro on Windows.
325bool FilePath::CreateFolder() const {
326#if GTEST_OS_WINDOWS_MOBILE
327  FilePath removed_sep(this->RemoveTrailingPathSeparator());
328  LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
329  int result = CreateDirectory(unicode, NULL) ? 0 : -1;
330  delete [] unicode;
331#elif GTEST_OS_WINDOWS
332  int result = _mkdir(pathname_.c_str());
333#else
334  int result = mkdir(pathname_.c_str(), 0777);
335#endif  // GTEST_OS_WINDOWS_MOBILE
336
337  if (result == -1) {
338    return this->DirectoryExists();  // An error is OK if the directory exists.
339  }
340  return true;  // No error.
341}
342
343// If input name has a trailing separator character, remove it and return the
344// name, otherwise return the name string unmodified.
345// On Windows platform, uses \ as the separator, other platforms use /.
346FilePath FilePath::RemoveTrailingPathSeparator() const {
347  return IsDirectory()
348      ? FilePath(pathname_.substr(0, pathname_.length() - 1))
349      : *this;
350}
351
352// Removes any redundant separators that might be in the pathname.
353// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
354// redundancies that might be in a pathname involving "." or "..".
355// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
356void FilePath::Normalize() {
357  if (pathname_.c_str() == NULL) {
358    pathname_ = "";
359    return;
360  }
361  const char* src = pathname_.c_str();
362  char* const dest = new char[pathname_.length() + 1];
363  char* dest_ptr = dest;
364  memset(dest_ptr, 0, pathname_.length() + 1);
365
366  while (*src != '\0') {
367    *dest_ptr = *src;
368    if (!IsPathSeparator(*src)) {
369      src++;
370    } else {
371#if GTEST_HAS_ALT_PATH_SEP_
372      if (*dest_ptr == kAlternatePathSeparator) {
373        *dest_ptr = kPathSeparator;
374      }
375#endif
376      while (IsPathSeparator(*src))
377        src++;
378    }
379    dest_ptr++;
380  }
381  *dest_ptr = '\0';
382  pathname_ = dest;
383  delete[] dest;
384}
385
386}  // namespace internal
387}  // namespace testing
trunk/3rdparty/googletest/googletest/src/gtest-internal-inl.h
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// Utility functions and classes used by the Google C++ testing framework.
31//
32// Author: wan@google.com (Zhanyong Wan)
33//
34// This file contains purely Google Test's internal implementation.  Please
35// DO NOT #INCLUDE IT IN A USER PROGRAM.
36
37#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
38#define GTEST_SRC_GTEST_INTERNAL_INL_H_
39
40// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
41// part of Google Test's implementation; otherwise it's undefined.
42#if !GTEST_IMPLEMENTATION_
43// If this file is included from the user's code, just say no.
44# error "gtest-internal-inl.h is part of Google Test's internal implementation."
45# error "It must not be included except by Google Test itself."
46#endif  // GTEST_IMPLEMENTATION_
47
48#ifndef _WIN32_WCE
49# include <errno.h>
50#endif  // !_WIN32_WCE
51#include <stddef.h>
52#include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
53#include <string.h>  // For memmove.
54
55#include <algorithm>
56#include <string>
57#include <vector>
58
59#include "gtest/internal/gtest-port.h"
60
61#if GTEST_CAN_STREAM_RESULTS_
62# include <arpa/inet.h>  // NOLINT
63# include <netdb.h>  // NOLINT
64#endif
65
66#if GTEST_OS_WINDOWS
67# include <windows.h>  // NOLINT
68#endif  // GTEST_OS_WINDOWS
69
70#include "gtest/gtest.h"  // NOLINT
71#include "gtest/gtest-spi.h"
72
73namespace testing {
74
75// Declares the flags.
76//
77// We don't want the users to modify this flag in the code, but want
78// Google Test's own unit tests to be able to access it. Therefore we
79// declare it here as opposed to in gtest.h.
80GTEST_DECLARE_bool_(death_test_use_fork);
81
82namespace internal {
83
84// The value of GetTestTypeId() as seen from within the Google Test
85// library.  This is solely for testing GetTestTypeId().
86GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
87
88// Names of the flags (needed for parsing Google Test flags).
89const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
90const char kBreakOnFailureFlag[] = "break_on_failure";
91const char kCatchExceptionsFlag[] = "catch_exceptions";
92const char kColorFlag[] = "color";
93const char kFilterFlag[] = "filter";
94const char kListTestsFlag[] = "list_tests";
95const char kOutputFlag[] = "output";
96const char kPrintTimeFlag[] = "print_time";
97const char kRandomSeedFlag[] = "random_seed";
98const char kRepeatFlag[] = "repeat";
99const char kShuffleFlag[] = "shuffle";
100const char kStackTraceDepthFlag[] = "stack_trace_depth";
101const char kStreamResultToFlag[] = "stream_result_to";
102const char kThrowOnFailureFlag[] = "throw_on_failure";
103const char kFlagfileFlag[] = "flagfile";
104
105// A valid random seed must be in [1, kMaxRandomSeed].
106const int kMaxRandomSeed = 99999;
107
108// g_help_flag is true iff the --help flag or an equivalent form is
109// specified on the command line.
110GTEST_API_ extern bool g_help_flag;
111
112// Returns the current time in milliseconds.
113GTEST_API_ TimeInMillis GetTimeInMillis();
114
115// Returns true iff Google Test should use colors in the output.
116GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
117
118// Formats the given time in milliseconds as seconds.
119GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
120
121// Converts the given time in milliseconds to a date string in the ISO 8601
122// format, without the timezone information.  N.B.: due to the use the
123// non-reentrant localtime() function, this function is not thread safe.  Do
124// not use it in any code that can be called from multiple threads.
125GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
126
127// Parses a string for an Int32 flag, in the form of "--flag=value".
128//
129// On success, stores the value of the flag in *value, and returns
130// true.  On failure, returns false without changing *value.
131GTEST_API_ bool ParseInt32Flag(
132    const char* str, const char* flag, Int32* value);
133
134// Returns a random seed in range [1, kMaxRandomSeed] based on the
135// given --gtest_random_seed flag value.
136inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
137  const unsigned int raw_seed = (random_seed_flag == 0) ?
138      static_cast<unsigned int>(GetTimeInMillis()) :
139      static_cast<unsigned int>(random_seed_flag);
140
141  // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
142  // it's easy to type.
143  const int normalized_seed =
144      static_cast<int>((raw_seed - 1U) %
145                       static_cast<unsigned int>(kMaxRandomSeed)) + 1;
146  return normalized_seed;
147}
148
149// Returns the first valid random seed after 'seed'.  The behavior is
150// undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
151// considered to be 1.
152inline int GetNextRandomSeed(int seed) {
153  GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
154      << "Invalid random seed " << seed << " - must be in [1, "
155      << kMaxRandomSeed << "].";
156  const int next_seed = seed + 1;
157  return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
158}
159
160// This class saves the values of all Google Test flags in its c'tor, and
161// restores them in its d'tor.
162class GTestFlagSaver {
163 public:
164  // The c'tor.
165  GTestFlagSaver() {
166    also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
167    break_on_failure_ = GTEST_FLAG(break_on_failure);
168    catch_exceptions_ = GTEST_FLAG(catch_exceptions);
169    color_ = GTEST_FLAG(color);
170    death_test_style_ = GTEST_FLAG(death_test_style);
171    death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
172    filter_ = GTEST_FLAG(filter);
173    internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
174    list_tests_ = GTEST_FLAG(list_tests);
175    output_ = GTEST_FLAG(output);
176    print_time_ = GTEST_FLAG(print_time);
177    random_seed_ = GTEST_FLAG(random_seed);
178    repeat_ = GTEST_FLAG(repeat);
179    shuffle_ = GTEST_FLAG(shuffle);
180    stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
181    stream_result_to_ = GTEST_FLAG(stream_result_to);
182    throw_on_failure_ = GTEST_FLAG(throw_on_failure);
183  }
184
185  // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
186  ~GTestFlagSaver() {
187    GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
188    GTEST_FLAG(break_on_failure) = break_on_failure_;
189    GTEST_FLAG(catch_exceptions) = catch_exceptions_;
190    GTEST_FLAG(color) = color_;
191    GTEST_FLAG(death_test_style) = death_test_style_;
192    GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
193    GTEST_FLAG(filter) = filter_;
194    GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
195    GTEST_FLAG(list_tests) = list_tests_;
196    GTEST_FLAG(output) = output_;
197    GTEST_FLAG(print_time) = print_time_;
198    GTEST_FLAG(random_seed) = random_seed_;
199    GTEST_FLAG(repeat) = repeat_;
200    GTEST_FLAG(shuffle) = shuffle_;
201    GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
202    GTEST_FLAG(stream_result_to) = stream_result_to_;
203    GTEST_FLAG(throw_on_failure) = throw_on_failure_;
204  }
205
206 private:
207  // Fields for saving the original values of flags.
208  bool also_run_disabled_tests_;
209  bool break_on_failure_;
210  bool catch_exceptions_;
211  std::string color_;
212  std::string death_test_style_;
213  bool death_test_use_fork_;
214  std::string filter_;
215  std::string internal_run_death_test_;
216  bool list_tests_;
217  std::string output_;
218  bool print_time_;
219  internal::Int32 random_seed_;
220  internal::Int32 repeat_;
221  bool shuffle_;
222  internal::Int32 stack_trace_depth_;
223  std::string stream_result_to_;
224  bool throw_on_failure_;
225} GTEST_ATTRIBUTE_UNUSED_;
226
227// Converts a Unicode code point to a narrow string in UTF-8 encoding.
228// code_point parameter is of type UInt32 because wchar_t may not be
229// wide enough to contain a code point.
230// If the code_point is not a valid Unicode code point
231// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
232// to "(Invalid Unicode 0xXXXXXXXX)".
233GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
234
235// Converts a wide string to a narrow string in UTF-8 encoding.
236// The wide string is assumed to have the following encoding:
237//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
238//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
239// Parameter str points to a null-terminated wide string.
240// Parameter num_chars may additionally limit the number
241// of wchar_t characters processed. -1 is used when the entire string
242// should be processed.
243// If the string contains code points that are not valid Unicode code points
244// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
245// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
246// and contains invalid UTF-16 surrogate pairs, values in those pairs
247// will be encoded as individual Unicode characters from Basic Normal Plane.
248GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
249
250// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
251// if the variable is present. If a file already exists at this location, this
252// function will write over it. If the variable is present, but the file cannot
253// be created, prints an error and exits.
254void WriteToShardStatusFileIfNeeded();
255
256// Checks whether sharding is enabled by examining the relevant
257// environment variable values. If the variables are present,
258// but inconsistent (e.g., shard_index >= total_shards), prints
259// an error and exits. If in_subprocess_for_death_test, sharding is
260// disabled because it must only be applied to the original test
261// process. Otherwise, we could filter out death tests we intended to execute.
262GTEST_API_ bool ShouldShard(const char* total_shards_str,
263                            const char* shard_index_str,
264                            bool in_subprocess_for_death_test);
265
266// Parses the environment variable var as an Int32. If it is unset,
267// returns default_val. If it is not an Int32, prints an error and
268// and aborts.
269GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
270
271// Given the total number of shards, the shard index, and the test id,
272// returns true iff the test should be run on this shard. The test id is
273// some arbitrary but unique non-negative integer assigned to each test
274// method. Assumes that 0 <= shard_index < total_shards.
275GTEST_API_ bool ShouldRunTestOnShard(
276    int total_shards, int shard_index, int test_id);
277
278// STL container utilities.
279
280// Returns the number of elements in the given container that satisfy
281// the given predicate.
282template <class Container, typename Predicate>
283inline int CountIf(const Container& c, Predicate predicate) {
284  // Implemented as an explicit loop since std::count_if() in libCstd on
285  // Solaris has a non-standard signature.
286  int count = 0;
287  for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
288    if (predicate(*it))
289      ++count;
290  }
291  return count;
292}
293
294// Applies a function/functor to each element in the container.
295template <class Container, typename Functor>
296void ForEach(const Container& c, Functor functor) {
297  std::for_each(c.begin(), c.end(), functor);
298}
299
300// Returns the i-th element of the vector, or default_value if i is not
301// in range [0, v.size()).
302template <typename E>
303inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
304  return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
305}
306
307// Performs an in-place shuffle of a range of the vector's elements.
308// 'begin' and 'end' are element indices as an STL-style range;
309// i.e. [begin, end) are shuffled, where 'end' == size() means to
310// shuffle to the end of the vector.
311template <typename E>
312void ShuffleRange(internal::Random* random, int begin, int end,
313                  std::vector<E>* v) {
314  const int size = static_cast<int>(v->size());
315  GTEST_CHECK_(0 <= begin && begin <= size)
316      << "Invalid shuffle range start " << begin << ": must be in range [0, "
317      << size << "].";
318  GTEST_CHECK_(begin <= end && end <= size)
319      << "Invalid shuffle range finish " << end << ": must be in range ["
320      << begin << ", " << size << "].";
321
322  // Fisher-Yates shuffle, from
323  // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
324  for (int range_width = end - begin; range_width >= 2; range_width--) {
325    const int last_in_range = begin + range_width - 1;
326    const int selected = begin + random->Generate(range_width);
327    std::swap((*v)[selected], (*v)[last_in_range]);
328  }
329}
330
331// Performs an in-place shuffle of the vector's elements.
332template <typename E>
333inline void Shuffle(internal::Random* random, std::vector<E>* v) {
334  ShuffleRange(random, 0, static_cast<int>(v->size()), v);
335}
336
337// A function for deleting an object.  Handy for being used as a
338// functor.
339template <typename T>
340static void Delete(T* x) {
341  delete x;
342}
343
344// A predicate that checks the key of a TestProperty against a known key.
345//
346// TestPropertyKeyIs is copyable.
347class TestPropertyKeyIs {
348 public:
349  // Constructor.
350  //
351  // TestPropertyKeyIs has NO default constructor.
352  explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
353
354  // Returns true iff the test name of test property matches on key_.
355  bool operator()(const TestProperty& test_property) const {
356    return test_property.key() == key_;
357  }
358
359 private:
360  std::string key_;
361};
362
363// Class UnitTestOptions.
364//
365// This class contains functions for processing options the user
366// specifies when running the tests.  It has only static members.
367//
368// In most cases, the user can specify an option using either an
369// environment variable or a command line flag.  E.g. you can set the
370// test filter using either GTEST_FILTER or --gtest_filter.  If both
371// the variable and the flag are present, the latter overrides the
372// former.
373class GTEST_API_ UnitTestOptions {
374 public:
375  // Functions for processing the gtest_output flag.
376
377  // Returns the output format, or "" for normal printed output.
378  static std::string GetOutputFormat();
379
380  // Returns the absolute path of the requested output file, or the
381  // default (test_detail.xml in the original working directory) if
382  // none was explicitly specified.
383  static std::string GetAbsolutePathToOutputFile();
384
385  // Functions for processing the gtest_filter flag.
386
387  // Returns true iff the wildcard pattern matches the string.  The
388  // first ':' or '\0' character in pattern marks the end of it.
389  //
390  // This recursive algorithm isn't very efficient, but is clear and
391  // works well enough for matching test names, which are short.
392  static bool PatternMatchesString(const char *pattern, const char *str);
393
394  // Returns true iff the user-specified filter matches the test case
395  // name and the test name.
396  static bool FilterMatchesTest(const std::string &test_case_name,
397                                const std::string &test_name);
398
399#if GTEST_OS_WINDOWS
400  // Function for supporting the gtest_catch_exception flag.
401
402  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
403  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
404  // This function is useful as an __except condition.
405  static int GTestShouldProcessSEH(DWORD exception_code);
406#endif  // GTEST_OS_WINDOWS
407
408  // Returns true if "name" matches the ':' separated list of glob-style
409  // filters in "filter".
410  static bool MatchesFilter(const std::string& name, const char* filter);
411};
412
413// Returns the current application's name, removing directory path if that
414// is present.  Used by UnitTestOptions::GetOutputFile.
415GTEST_API_ FilePath GetCurrentExecutableName();
416
417// The role interface for getting the OS stack trace as a string.
418class OsStackTraceGetterInterface {
419 public:
420  OsStackTraceGetterInterface() {}
421  virtual ~OsStackTraceGetterInterface() {}
422
423  // Returns the current OS stack trace as an std::string.  Parameters:
424  //
425  //   max_depth  - the maximum number of stack frames to be included
426  //                in the trace.
427  //   skip_count - the number of top frames to be skipped; doesn't count
428  //                against max_depth.
429  virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
430
431  // UponLeavingGTest() should be called immediately before Google Test calls
432  // user code. It saves some information about the current stack that
433  // CurrentStackTrace() will use to find and hide Google Test stack frames.
434  virtual void UponLeavingGTest() = 0;
435
436  // This string is inserted in place of stack frames that are part of
437  // Google Test's implementation.
438  static const char* const kElidedFramesMarker;
439
440 private:
441  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
442};
443
444// A working implementation of the OsStackTraceGetterInterface interface.
445class OsStackTraceGetter : public OsStackTraceGetterInterface {
446 public:
447  OsStackTraceGetter() {}
448
449  virtual string CurrentStackTrace(int max_depth, int skip_count);
450  virtual void UponLeavingGTest();
451
452 private:
453  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
454};
455
456// Information about a Google Test trace point.
457struct TraceInfo {
458  const char* file;
459  int line;
460  std::string message;
461};
462
463// This is the default global test part result reporter used in UnitTestImpl.
464// This class should only be used by UnitTestImpl.
465class DefaultGlobalTestPartResultReporter
466  : public TestPartResultReporterInterface {
467 public:
468  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
469  // Implements the TestPartResultReporterInterface. Reports the test part
470  // result in the current test.
471  virtual void ReportTestPartResult(const TestPartResult& result);
472
473 private:
474  UnitTestImpl* const unit_test_;
475
476  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
477};
478
479// This is the default per thread test part result reporter used in
480// UnitTestImpl. This class should only be used by UnitTestImpl.
481class DefaultPerThreadTestPartResultReporter
482    : public TestPartResultReporterInterface {
483 public:
484  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
485  // Implements the TestPartResultReporterInterface. The implementation just
486  // delegates to the current global test part result reporter of *unit_test_.
487  virtual void ReportTestPartResult(const TestPartResult& result);
488
489 private:
490  UnitTestImpl* const unit_test_;
491
492  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
493};
494
495// The private implementation of the UnitTest class.  We don't protect
496// the methods under a mutex, as this class is not accessible by a
497// user and the UnitTest class that delegates work to this class does
498// proper locking.
499class GTEST_API_ UnitTestImpl {
500 public:
501  explicit UnitTestImpl(UnitTest* parent);
502  virtual ~UnitTestImpl();
503
504  // There are two different ways to register your own TestPartResultReporter.
505  // You can register your own repoter to listen either only for test results
506  // from the current thread or for results from all threads.
507  // By default, each per-thread test result repoter just passes a new
508  // TestPartResult to the global test result reporter, which registers the
509  // test part result for the currently running test.
510
511  // Returns the global test part result reporter.
512  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
513
514  // Sets the global test part result reporter.
515  void SetGlobalTestPartResultReporter(
516      TestPartResultReporterInterface* reporter);
517
518  // Returns the test part result reporter for the current thread.
519  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
520
521  // Sets the test part result reporter for the current thread.
522  void SetTestPartResultReporterForCurrentThread(
523      TestPartResultReporterInterface* reporter);
524
525  // Gets the number of successful test cases.
526  int successful_test_case_count() const;
527
528  // Gets the number of failed test cases.
529  int failed_test_case_count() const;
530
531  // Gets the number of all test cases.
532  int total_test_case_count() const;
533
534  // Gets the number of all test cases that contain at least one test
535  // that should run.
536  int test_case_to_run_count() const;
537
538  // Gets the number of successful tests.
539  int successful_test_count() const;
540
541  // Gets the number of failed tests.
542  int failed_test_count() const;
543
544  // Gets the number of disabled tests that will be reported in the XML report.
545  int reportable_disabled_test_count() const;
546
547  // Gets the number of disabled tests.
548  int disabled_test_count() const;
549
550  // Gets the number of tests to be printed in the XML report.
551  int reportable_test_count() const;
552
553  // Gets the number of all tests.
554  int total_test_count() const;
555
556  // Gets the number of tests that should run.
557  int test_to_run_count() const;
558
559  // Gets the time of the test program start, in ms from the start of the
560  // UNIX epoch.
561  TimeInMillis start_timestamp() const { return start_timestamp_; }
562
563  // Gets the elapsed time, in milliseconds.
564  TimeInMillis elapsed_time() const { return elapsed_time_; }
565
566  // Returns true iff the unit test passed (i.e. all test cases passed).
567  bool Passed() const { return !Failed(); }
568
569  // Returns true iff the unit test failed (i.e. some test case failed
570  // or something outside of all tests failed).
571  bool Failed() const {
572    return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
573  }
574
575  // Gets the i-th test case among all the test cases. i can range from 0 to
576  // total_test_case_count() - 1. If i is not in that range, returns NULL.
577  const TestCase* GetTestCase(int i) const {
578    const int index = GetElementOr(test_case_indices_, i, -1);
579    return index < 0 ? NULL : test_cases_[i];
580  }
581
582  // Gets the i-th test case among all the test cases. i can range from 0 to
583  // total_test_case_count() - 1. If i is not in that range, returns NULL.
584  TestCase* GetMutableTestCase(int i) {
585    const int index = GetElementOr(test_case_indices_, i, -1);
586    return index < 0 ? NULL : test_cases_[index];
587  }
588
589  // Provides access to the event listener list.
590  TestEventListeners* listeners() { return &listeners_; }
591
592  // Returns the TestResult for the test that's currently running, or
593  // the TestResult for the ad hoc test if no test is running.
594  TestResult* current_test_result();
595
596  // Returns the TestResult for the ad hoc test.
597  const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
598
599  // Sets the OS stack trace getter.
600  //
601  // Does nothing if the input and the current OS stack trace getter
602  // are the same; otherwise, deletes the old getter and makes the
603  // input the current getter.
604  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
605
606  // Returns the current OS stack trace getter if it is not NULL;
607  // otherwise, creates an OsStackTraceGetter, makes it the current
608  // getter, and returns it.
609  OsStackTraceGetterInterface* os_stack_trace_getter();
610
611  // Returns the current OS stack trace as an std::string.
612  //
613  // The maximum number of stack frames to be included is specified by
614  // the gtest_stack_trace_depth flag.  The skip_count parameter
615  // specifies the number of top frames to be skipped, which doesn't
616  // count against the number of frames to be included.
617  //
618  // For example, if Foo() calls Bar(), which in turn calls
619  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
620  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
621  std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
622
623  // Finds and returns a TestCase with the given name.  If one doesn't
624  // exist, creates one and returns it.
625  //
626  // Arguments:
627  //
628  //   test_case_name: name of the test case
629  //   type_param:     the name of the test's type parameter, or NULL if
630  //                   this is not a typed or a type-parameterized test.
631  //   set_up_tc:      pointer to the function that sets up the test case
632  //   tear_down_tc:   pointer to the function that tears down the test case
633  TestCase* GetTestCase(const char* test_case_name,
634                        const char* type_param,
635                        Test::SetUpTestCaseFunc set_up_tc,
636                        Test::TearDownTestCaseFunc tear_down_tc);
637
638  // Adds a TestInfo to the unit test.
639  //
640  // Arguments:
641  //
642  //   set_up_tc:    pointer to the function that sets up the test case
643  //   tear_down_tc: pointer to the function that tears down the test case
644  //   test_info:    the TestInfo object
645  void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
646                   Test::TearDownTestCaseFunc tear_down_tc,
647                   TestInfo* test_info) {
648    // In order to support thread-safe death tests, we need to
649    // remember the original working directory when the test program
650    // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
651    // the user may have changed the current directory before calling
652    // RUN_ALL_TESTS().  Therefore we capture the current directory in
653    // AddTestInfo(), which is called to register a TEST or TEST_F
654    // before main() is reached.
655    if (original_working_dir_.IsEmpty()) {
656      original_working_dir_.Set(FilePath::GetCurrentDir());
657      GTEST_CHECK_(!original_working_dir_.IsEmpty())
658          << "Failed to get the current working directory.";
659    }
660
661    GetTestCase(test_info->test_case_name(),
662                test_info->type_param(),
663                set_up_tc,
664                tear_down_tc)->AddTestInfo(test_info);
665  }
666
667#if GTEST_HAS_PARAM_TEST
668  // Returns ParameterizedTestCaseRegistry object used to keep track of
669  // value-parameterized tests and instantiate and register them.
670  internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
671    return parameterized_test_registry_;
672  }
673#endif  // GTEST_HAS_PARAM_TEST
674
675  // Sets the TestCase object for the test that's currently running.
676  void set_current_test_case(TestCase* a_current_test_case) {
677    current_test_case_ = a_current_test_case;
678  }
679
680  // Sets the TestInfo object for the test that's currently running.  If
681  // current_test_info is NULL, the assertion results will be stored in
682  // ad_hoc_test_result_.
683  void set_current_test_info(TestInfo* a_current_test_info) {
684    current_test_info_ = a_current_test_info;
685  }
686
687  // Registers all parameterized tests defined using TEST_P and
688  // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
689  // combination. This method can be called more then once; it has guards
690  // protecting from registering the tests more then once.  If
691  // value-parameterized tests are disabled, RegisterParameterizedTests is
692  // present but does nothing.
693  void RegisterParameterizedTests();
694
695  // Runs all tests in this UnitTest object, prints the result, and
696  // returns true if all tests are successful.  If any exception is
697  // thrown during a test, this test is considered to be failed, but
698  // the rest of the tests will still be run.
699  bool RunAllTests();
700
701  // Clears the results of all tests, except the ad hoc tests.
702  void ClearNonAdHocTestResult() {
703    ForEach(test_cases_, TestCase::ClearTestCaseResult);
704  }
705
706  // Clears the results of ad-hoc test assertions.
707  void ClearAdHocTestResult() {
708    ad_hoc_test_result_.Clear();
709  }
710
711  // Adds a TestProperty to the current TestResult object when invoked in a
712  // context of a test or a test case, or to the global property set. If the
713  // result already contains a property with the same key, the value will be
714  // updated.
715  void RecordProperty(const TestProperty& test_property);
716
717  enum ReactionToSharding {
718    HONOR_SHARDING_PROTOCOL,
719    IGNORE_SHARDING_PROTOCOL
720  };
721
722  // Matches the full name of each test against the user-specified
723  // filter to decide whether the test should run, then records the
724  // result in each TestCase and TestInfo object.
725  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
726  // based on sharding variables in the environment.
727  // Returns the number of tests that should run.
728  int FilterTests(ReactionToSharding shard_tests);
729
730  // Prints the names of the tests matching the user-specified filter flag.
731  void ListTestsMatchingFilter();
732
733  const TestCase* current_test_case() const { return current_test_case_; }
734  TestInfo* current_test_info() { return current_test_info_; }
735  const TestInfo* current_test_info() const { return current_test_info_; }
736
737  // Returns the vector of environments that need to be set-up/torn-down
738  // before/after the tests are run.
739  std::vector<Environment*>& environments() { return environments_; }
740
741  // Getters for the per-thread Google Test trace stack.
742  std::vector<TraceInfo>& gtest_trace_stack() {
743    return *(gtest_trace_stack_.pointer());
744  }
745  const std::vector<TraceInfo>& gtest_trace_stack() const {
746    return gtest_trace_stack_.get();
747  }
748
749#if GTEST_HAS_DEATH_TEST
750  void InitDeathTestSubprocessControlInfo() {
751    internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
752  }
753  // Returns a pointer to the parsed --gtest_internal_run_death_test
754  // flag, or NULL if that flag was not specified.
755  // This information is useful only in a death test child process.
756  // Must not be called before a call to InitGoogleTest.
757  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
758    return internal_run_death_test_flag_.get();
759  }
760
761  // Returns a pointer to the current death test factory.
762  internal::DeathTestFactory* death_test_factory() {
763    return death_test_factory_.get();
764  }
765
766  void SuppressTestEventsIfInSubprocess();
767
768  friend class ReplaceDeathTestFactory;
769#endif  // GTEST_HAS_DEATH_TEST
770
771  // Initializes the event listener performing XML output as specified by
772  // UnitTestOptions. Must not be called before InitGoogleTest.
773  void ConfigureXmlOutput();
774
775#if GTEST_CAN_STREAM_RESULTS_
776  // Initializes the event listener for streaming test results to a socket.
777  // Must not be called before InitGoogleTest.
778  void ConfigureStreamingOutput();
779#endif
780
781  // Performs initialization dependent upon flag values obtained in
782  // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
783  // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
784  // this function is also called from RunAllTests.  Since this function can be
785  // called more than once, it has to be idempotent.
786  void PostFlagParsingInit();
787
788  // Gets the random seed used at the start of the current test iteration.
789  int random_seed() const { return random_seed_; }
790
791  // Gets the random number generator.
792  internal::Random* random() { return &random_; }
793
794  // Shuffles all test cases, and the tests within each test case,
795  // making sure that death tests are still run first.
796  void ShuffleTests();
797
798  // Restores the test cases and tests to their order before the first shuffle.
799  void UnshuffleTests();
800
801  // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
802  // UnitTest::Run() starts.
803  bool catch_exceptions() const { return catch_exceptions_; }
804
805 private:
806  friend class ::testing::UnitTest;
807
808  // Used by UnitTest::Run() to capture the state of
809  // GTEST_FLAG(catch_exceptions) at the moment it starts.
810  void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
811
812  // The UnitTest object that owns this implementation object.
813  UnitTest* const parent_;
814
815  // The working directory when the first TEST() or TEST_F() was
816  // executed.
817  internal::FilePath original_working_dir_;
818
819  // The default test part result reporters.
820  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
821  DefaultPerThreadTestPartResultReporter
822      default_per_thread_test_part_result_reporter_;
823
824  // Points to (but doesn't own) the global test part result reporter.
825  TestPartResultReporterInterface* global_test_part_result_repoter_;
826
827  // Protects read and write access to global_test_part_result_reporter_.
828  internal::Mutex global_test_part_result_reporter_mutex_;
829
830  // Points to (but doesn't own) the per-thread test part result reporter.
831  internal::ThreadLocal<TestPartResultReporterInterface*>
832      per_thread_test_part_result_reporter_;
833
834  // The vector of environments that need to be set-up/torn-down
835  // before/after the tests are run.
836  std::vector<Environment*> environments_;
837
838  // The vector of TestCases in their original order.  It owns the
839  // elements in the vector.
840  std::vector<TestCase*> test_cases_;
841
842  // Provides a level of indirection for the test case list to allow
843  // easy shuffling and restoring the test case order.  The i-th
844  // element of this vector is the index of the i-th test case in the
845  // shuffled order.
846  std::vector<int> test_case_indices_;
847
848#if GTEST_HAS_PARAM_TEST
849  // ParameterizedTestRegistry object used to register value-parameterized
850  // tests.
851  internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
852
853  // Indicates whether RegisterParameterizedTests() has been called already.
854  bool parameterized_tests_registered_;
855#endif  // GTEST_HAS_PARAM_TEST
856
857  // Index of the last death test case registered.  Initially -1.
858  int last_death_test_case_;
859
860  // This points to the TestCase for the currently running test.  It
861  // changes as Google Test goes through one test case after another.
862  // When no test is running, this is set to NULL and Google Test
863  // stores assertion results in ad_hoc_test_result_.  Initially NULL.
864  TestCase* current_test_case_;
865
866  // This points to the TestInfo for the currently running test.  It
867  // changes as Google Test goes through one test after another.  When
868  // no test is running, this is set to NULL and Google Test stores
869  // assertion results in ad_hoc_test_result_.  Initially NULL.
870  TestInfo* current_test_info_;
871
872  // Normally, a user only writes assertions inside a TEST or TEST_F,
873  // or inside a function called by a TEST or TEST_F.  Since Google
874  // Test keeps track of which test is current running, it can
875  // associate such an assertion with the test it belongs to.
876  //
877  // If an assertion is encountered when no TEST or TEST_F is running,
878  // Google Test attributes the assertion result to an imaginary "ad hoc"
879  // test, and records the result in ad_hoc_test_result_.
880  TestResult ad_hoc_test_result_;
881
882  // The list of event listeners that can be used to track events inside
883  // Google Test.
884  TestEventListeners listeners_;
885
886  // The OS stack trace getter.  Will be deleted when the UnitTest
887  // object is destructed.  By default, an OsStackTraceGetter is used,
888  // but the user can set this field to use a custom getter if that is
889  // desired.
890  OsStackTraceGetterInterface* os_stack_trace_getter_;
891
892  // True iff PostFlagParsingInit() has been called.
893  bool post_flag_parse_init_performed_;
894
895  // The random number seed used at the beginning of the test run.
896  int random_seed_;
897
898  // Our random number generator.
899  internal::Random random_;
900
901  // The time of the test program start, in ms from the start of the
902  // UNIX epoch.
903  TimeInMillis start_timestamp_;
904
905  // How long the test took to run, in milliseconds.
906  TimeInMillis elapsed_time_;
907
908#if GTEST_HAS_DEATH_TEST
909  // The decomposed components of the gtest_internal_run_death_test flag,
910  // parsed when RUN_ALL_TESTS is called.
911  internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
912  internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
913#endif  // GTEST_HAS_DEATH_TEST
914
915  // A per-thread stack of traces created by the SCOPED_TRACE() macro.
916  internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
917
918  // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
919  // starts.
920  bool catch_exceptions_;
921
922  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
923};  // class UnitTestImpl
924
925// Convenience function for accessing the global UnitTest
926// implementation object.
927inline UnitTestImpl* GetUnitTestImpl() {
928  return UnitTest::GetInstance()->impl();
929}
930
931#if GTEST_USES_SIMPLE_RE
932
933// Internal helper functions for implementing the simple regular
934// expression matcher.
935GTEST_API_ bool IsInSet(char ch, const char* str);
936GTEST_API_ bool IsAsciiDigit(char ch);
937GTEST_API_ bool IsAsciiPunct(char ch);
938GTEST_API_ bool IsRepeat(char ch);
939GTEST_API_ bool IsAsciiWhiteSpace(char ch);
940GTEST_API_ bool IsAsciiWordChar(char ch);
941GTEST_API_ bool IsValidEscape(char ch);
942GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
943GTEST_API_ bool ValidateRegex(const char* regex);
944GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
945GTEST_API_ bool MatchRepetitionAndRegexAtHead(
946    bool escaped, char ch, char repeat, const char* regex, const char* str);
947GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
948
949#endif  // GTEST_USES_SIMPLE_RE
950
951// Parses the command line for Google Test flags, without initializing
952// other parts of Google Test.
953GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
954GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
955
956#if GTEST_HAS_DEATH_TEST
957
958// Returns the message describing the last system error, regardless of the
959// platform.
960GTEST_API_ std::string GetLastErrnoDescription();
961
962// Attempts to parse a string into a positive integer pointed to by the
963// number parameter.  Returns true if that is possible.
964// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
965// it here.
966template <typename Integer>
967bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
968  // Fail fast if the given string does not begin with a digit;
969  // this bypasses strtoXXX's "optional leading whitespace and plus
970  // or minus sign" semantics, which are undesirable here.
971  if (str.empty() || !IsDigit(str[0])) {
972    return false;
973  }
974  errno = 0;
975
976  char* end;
977  // BiggestConvertible is the largest integer type that system-provided
978  // string-to-number conversion routines can return.
979
980# if GTEST_OS_WINDOWS && !defined(__GNUC__)
981
982  // MSVC and C++ Builder define __int64 instead of the standard long long.
983  typedef unsigned __int64 BiggestConvertible;
984  const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
985
986# else
987
988  typedef unsigned long long BiggestConvertible;  // NOLINT
989  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
990
991# endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
992
993  const bool parse_success = *end == '\0' && errno == 0;
994
995  // TODO(vladl@google.com): Convert this to compile time assertion when it is
996  // available.
997  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
998
999  const Integer result = static_cast<Integer>(parsed);
1000  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1001    *number = result;
1002    return true;
1003  }
1004  return false;
1005}
1006#endif  // GTEST_HAS_DEATH_TEST
1007
1008// TestResult contains some private methods that should be hidden from
1009// Google Test user but are required for testing. This class allow our tests
1010// to access them.
1011//
1012// This class is supplied only for the purpose of testing Google Test's own
1013// constructs. Do not use it in user tests, either directly or indirectly.
1014class TestResultAccessor {
1015 public:
1016  static void RecordProperty(TestResult* test_result,
1017                             const std::string& xml_element,
1018                             const TestProperty& property) {
1019    test_result->RecordProperty(xml_element, property);
1020  }
1021
1022  static void ClearTestPartResults(TestResult* test_result) {
1023    test_result->ClearTestPartResults();
1024  }
1025
1026  static const std::vector<testing::TestPartResult>& test_part_results(
1027      const TestResult& test_result) {
1028    return test_result.test_part_results();
1029  }
1030};
1031
1032#if GTEST_CAN_STREAM_RESULTS_
1033
1034// Streams test results to the given port on the given host machine.
1035class StreamingListener : public EmptyTestEventListener {
1036 public:
1037  // Abstract base class for writing strings to a socket.
1038  class AbstractSocketWriter {
1039   public:
1040    virtual ~AbstractSocketWriter() {}
1041
1042    // Sends a string to the socket.
1043    virtual void Send(const string& message) = 0;
1044
1045    // Closes the socket.
1046    virtual void CloseConnection() {}
1047
1048    // Sends a string and a newline to the socket.
1049    void SendLn(const string& message) {
1050      Send(message + "\n");
1051    }
1052  };
1053
1054  // Concrete class for actually writing strings to a socket.
1055  class SocketWriter : public AbstractSocketWriter {
1056   public:
1057    SocketWriter(const string& host, const string& port)
1058        : sockfd_(-1), host_name_(host), port_num_(port) {
1059      MakeConnection();
1060    }
1061
1062    virtual ~SocketWriter() {
1063      if (sockfd_ != -1)
1064        CloseConnection();
1065    }
1066
1067    // Sends a string to the socket.
1068    virtual void Send(const string& message) {
1069      GTEST_CHECK_(sockfd_ != -1)
1070          << "Send() can be called only when there is a connection.";
1071
1072      const int len = static_cast<int>(message.length());
1073      if (write(sockfd_, message.c_str(), len) != len) {
1074        GTEST_LOG_(WARNING)
1075            << "stream_result_to: failed to stream to "
1076            << host_name_ << ":" << port_num_;
1077      }
1078    }
1079
1080   private:
1081    // Creates a client socket and connects to the server.
1082    void MakeConnection();
1083
1084    // Closes the socket.
1085    void CloseConnection() {
1086      GTEST_CHECK_(sockfd_ != -1)
1087          << "CloseConnection() can be called only when there is a connection.";
1088
1089      close(sockfd_);
1090      sockfd_ = -1;
1091    }
1092
1093    int sockfd_;  // socket file descriptor
1094    const string host_name_;
1095    const string port_num_;
1096
1097    GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1098  };  // class SocketWriter
1099
1100  // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1101  static string UrlEncode(const char* str);
1102
1103  StreamingListener(const string& host, const string& port)
1104      : socket_writer_(new SocketWriter(host, port)) { Start(); }
1105
1106  explicit StreamingListener(AbstractSocketWriter* socket_writer)
1107      : socket_writer_(socket_writer) { Start(); }
1108
1109  void OnTestProgramStart(const UnitTest& /* unit_test */) {
1110    SendLn("event=TestProgramStart");
1111  }
1112
1113  void OnTestProgramEnd(const UnitTest& unit_test) {
1114    // Note that Google Test current only report elapsed time for each
1115    // test iteration, not for the entire test program.
1116    SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1117
1118    // Notify the streaming server to stop.
1119    socket_writer_->CloseConnection();
1120  }
1121
1122  void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1123    SendLn("event=TestIterationStart&iteration=" +
1124           StreamableToString(iteration));
1125  }
1126
1127  void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1128    SendLn("event=TestIterationEnd&passed=" +
1129           FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1130           StreamableToString(unit_test.elapsed_time()) + "ms");
1131  }
1132
1133  void OnTestCaseStart(const TestCase& test_case) {
1134    SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1135  }
1136
1137  void OnTestCaseEnd(const TestCase& test_case) {
1138    SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1139           + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1140           + "ms");
1141  }
1142
1143  void OnTestStart(const TestInfo& test_info) {
1144    SendLn(std::string("event=TestStart&name=") + test_info.name());
1145  }
1146
1147  void OnTestEnd(const TestInfo& test_info) {
1148    SendLn("event=TestEnd&passed=" +
1149           FormatBool((test_info.result())->Passed()) +
1150           "&elapsed_time=" +
1151           StreamableToString((test_info.result())->elapsed_time()) + "ms");
1152  }
1153
1154  void OnTestPartResult(const TestPartResult& test_part_result) {
1155    const char* file_name = test_part_result.file_name();
1156    if (file_name == NULL)
1157      file_name = "";
1158    SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1159           "&line=" + StreamableToString(test_part_result.line_number()) +
1160           "&message=" + UrlEncode(test_part_result.message()));
1161  }
1162
1163 private:
1164  // Sends the given message and a newline to the socket.
1165  void SendLn(const string& message) { socket_writer_->SendLn(message); }
1166
1167  // Called at the start of streaming to notify the receiver what
1168  // protocol we are using.
1169  void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1170
1171  string FormatBool(bool value) { return value ? "1" : "0"; }
1172
1173  const scoped_ptr<AbstractSocketWriter> socket_writer_;
1174
1175  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1176};  // class StreamingListener
1177
1178#endif  // GTEST_CAN_STREAM_RESULTS_
1179
1180}  // namespace internal
1181}  // namespace testing
1182
1183#endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
trunk/3rdparty/googletest/googletest/src/gtest-port.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gtest/internal/gtest-port.h"
33
34#include <limits.h>
35#include <stdlib.h>
36#include <stdio.h>
37#include <string.h>
38#include <fstream>
39
40#if GTEST_OS_WINDOWS
41# include <windows.h>
42# include <io.h>
43# include <sys/stat.h>
44# include <map>  // Used in ThreadLocal.
45#else
46# include <unistd.h>
47#endif  // GTEST_OS_WINDOWS
48
49#if GTEST_OS_MAC
50# include <mach/mach_init.h>
51# include <mach/task.h>
52# include <mach/vm_map.h>
53#endif  // GTEST_OS_MAC
54
55#if GTEST_OS_QNX
56# include <devctl.h>
57# include <fcntl.h>
58# include <sys/procfs.h>
59#endif  // GTEST_OS_QNX
60
61#include "gtest/gtest-spi.h"
62#include "gtest/gtest-message.h"
63#include "gtest/internal/gtest-internal.h"
64#include "gtest/internal/gtest-string.h"
65
66// Indicates that this translation unit is part of Google Test's
67// implementation.  It must come before gtest-internal-inl.h is
68// included, or there will be a compiler error.  This trick exists to
69// prevent the accidental inclusion of gtest-internal-inl.h in the
70// user's code.
71#define GTEST_IMPLEMENTATION_ 1
72#include "src/gtest-internal-inl.h"
73#undef GTEST_IMPLEMENTATION_
74
75namespace testing {
76namespace internal {
77
78#if defined(_MSC_VER) || defined(__BORLANDC__)
79// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
80const int kStdOutFileno = 1;
81const int kStdErrFileno = 2;
82#else
83const int kStdOutFileno = STDOUT_FILENO;
84const int kStdErrFileno = STDERR_FILENO;
85#endif  // _MSC_VER
86
87#if GTEST_OS_LINUX
88
89namespace {
90template <typename T>
91T ReadProcFileField(const string& filename, int field) {
92  std::string dummy;
93  std::ifstream file(filename.c_str());
94  while (field-- > 0) {
95    file >> dummy;
96  }
97  T output = 0;
98  file >> output;
99  return output;
100}
101}  // namespace
102
103// Returns the number of active threads, or 0 when there is an error.
104size_t GetThreadCount() {
105  const string filename =
106      (Message() << "/proc/" << getpid() << "/stat").GetString();
107  return ReadProcFileField<int>(filename, 19);
108}
109
110#elif GTEST_OS_MAC
111
112size_t GetThreadCount() {
113  const task_t task = mach_task_self();
114  mach_msg_type_number_t thread_count;
115  thread_act_array_t thread_list;
116  const kern_return_t status = task_threads(task, &thread_list, &thread_count);
117  if (status == KERN_SUCCESS) {
118    // task_threads allocates resources in thread_list and we need to free them
119    // to avoid leaks.
120    vm_deallocate(task,
121                  reinterpret_cast<vm_address_t>(thread_list),
122                  sizeof(thread_t) * thread_count);
123    return static_cast<size_t>(thread_count);
124  } else {
125    return 0;
126  }
127}
128
129#elif GTEST_OS_QNX
130
131// Returns the number of threads running in the process, or 0 to indicate that
132// we cannot detect it.
133size_t GetThreadCount() {
134  const int fd = open("/proc/self/as", O_RDONLY);
135  if (fd < 0) {
136    return 0;
137  }
138  procfs_info process_info;
139  const int status =
140      devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
141  close(fd);
142  if (status == EOK) {
143    return static_cast<size_t>(process_info.num_threads);
144  } else {
145    return 0;
146  }
147}
148
149#else
150
151size_t GetThreadCount() {
152  // There's no portable way to detect the number of threads, so we just
153  // return 0 to indicate that we cannot detect it.
154  return 0;
155}
156
157#endif  // GTEST_OS_LINUX
158
159#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
160
161void SleepMilliseconds(int n) {
162  ::Sleep(n);
163}
164
165AutoHandle::AutoHandle()
166    : handle_(INVALID_HANDLE_VALUE) {}
167
168AutoHandle::AutoHandle(Handle handle)
169    : handle_(handle) {}
170
171AutoHandle::~AutoHandle() {
172  Reset();
173}
174
175AutoHandle::Handle AutoHandle::Get() const {
176  return handle_;
177}
178
179void AutoHandle::Reset() {
180  Reset(INVALID_HANDLE_VALUE);
181}
182
183void AutoHandle::Reset(HANDLE handle) {
184  // Resetting with the same handle we already own is invalid.
185  if (handle_ != handle) {
186    if (IsCloseable()) {
187      ::CloseHandle(handle_);
188    }
189    handle_ = handle;
190  } else {
191    GTEST_CHECK_(!IsCloseable())
192        << "Resetting a valid handle to itself is likely a programmer error "
193            "and thus not allowed.";
194  }
195}
196
197bool AutoHandle::IsCloseable() const {
198  // Different Windows APIs may use either of these values to represent an
199  // invalid handle.
200  return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
201}
202
203Notification::Notification()
204    : event_(::CreateEvent(NULL,   // Default security attributes.
205                           TRUE,   // Do not reset automatically.
206                           FALSE,  // Initially unset.
207                           NULL)) {  // Anonymous event.
208  GTEST_CHECK_(event_.Get() != NULL);
209}
210
211void Notification::Notify() {
212  GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
213}
214
215void Notification::WaitForNotification() {
216  GTEST_CHECK_(
217      ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
218}
219
220Mutex::Mutex()
221    : owner_thread_id_(0),
222      type_(kDynamic),
223      critical_section_init_phase_(0),
224      critical_section_(new CRITICAL_SECTION) {
225  ::InitializeCriticalSection(critical_section_);
226}
227
228Mutex::~Mutex() {
229  // Static mutexes are leaked intentionally. It is not thread-safe to try
230  // to clean them up.
231  // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
232  // nothing to clean it up but is available only on Vista and later.
233  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
234  if (type_ == kDynamic) {
235    ::DeleteCriticalSection(critical_section_);
236    delete critical_section_;
237    critical_section_ = NULL;
238  }
239}
240
241void Mutex::Lock() {
242  ThreadSafeLazyInit();
243  ::EnterCriticalSection(critical_section_);
244  owner_thread_id_ = ::GetCurrentThreadId();
245}
246
247void Mutex::Unlock() {
248  ThreadSafeLazyInit();
249  // We don't protect writing to owner_thread_id_ here, as it's the
250  // caller's responsibility to ensure that the current thread holds the
251  // mutex when this is called.
252  owner_thread_id_ = 0;
253  ::LeaveCriticalSection(critical_section_);
254}
255
256// Does nothing if the current thread holds the mutex. Otherwise, crashes
257// with high probability.
258void Mutex::AssertHeld() {
259  ThreadSafeLazyInit();
260  GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
261      << "The current thread is not holding the mutex @" << this;
262}
263
264// Initializes owner_thread_id_ and critical_section_ in static mutexes.
265void Mutex::ThreadSafeLazyInit() {
266  // Dynamic mutexes are initialized in the constructor.
267  if (type_ == kStatic) {
268    switch (
269        ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
270      case 0:
271        // If critical_section_init_phase_ was 0 before the exchange, we
272        // are the first to test it and need to perform the initialization.
273        owner_thread_id_ = 0;
274        critical_section_ = new CRITICAL_SECTION;
275        ::InitializeCriticalSection(critical_section_);
276        // Updates the critical_section_init_phase_ to 2 to signal
277        // initialization complete.
278        GTEST_CHECK_(::InterlockedCompareExchange(
279                          &critical_section_init_phase_, 2L, 1L) ==
280                      1L);
281        break;
282      case 1:
283        // Somebody else is already initializing the mutex; spin until they
284        // are done.
285        while (::InterlockedCompareExchange(&critical_section_init_phase_,
286                                            2L,
287                                            2L) != 2L) {
288          // Possibly yields the rest of the thread's time slice to other
289          // threads.
290          ::Sleep(0);
291        }
292        break;
293
294      case 2:
295        break;  // The mutex is already initialized and ready for use.
296
297      default:
298        GTEST_CHECK_(false)
299            << "Unexpected value of critical_section_init_phase_ "
300            << "while initializing a static mutex.";
301    }
302  }
303}
304
305namespace {
306
307class ThreadWithParamSupport : public ThreadWithParamBase {
308 public:
309  static HANDLE CreateThread(Runnable* runnable,
310                             Notification* thread_can_start) {
311    ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
312    DWORD thread_id;
313    // TODO(yukawa): Consider to use _beginthreadex instead.
314    HANDLE thread_handle = ::CreateThread(
315        NULL,    // Default security.
316        0,       // Default stack size.
317        &ThreadWithParamSupport::ThreadMain,
318        param,   // Parameter to ThreadMainStatic
319        0x0,     // Default creation flags.
320        &thread_id);  // Need a valid pointer for the call to work under Win98.
321    GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
322                                        << ::GetLastError() << ".";
323    if (thread_handle == NULL) {
324      delete param;
325    }
326    return thread_handle;
327  }
328
329 private:
330  struct ThreadMainParam {
331    ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
332        : runnable_(runnable),
333          thread_can_start_(thread_can_start) {
334    }
335    scoped_ptr<Runnable> runnable_;
336    // Does not own.
337    Notification* thread_can_start_;
338  };
339
340  static DWORD WINAPI ThreadMain(void* ptr) {
341    // Transfers ownership.
342    scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
343    if (param->thread_can_start_ != NULL)
344      param->thread_can_start_->WaitForNotification();
345    param->runnable_->Run();
346    return 0;
347  }
348
349  // Prohibit instantiation.
350  ThreadWithParamSupport();
351
352  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
353};
354
355}  // namespace
356
357ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
358                                         Notification* thread_can_start)
359      : thread_(ThreadWithParamSupport::CreateThread(runnable,
360                                                     thread_can_start)) {
361}
362
363ThreadWithParamBase::~ThreadWithParamBase() {
364  Join();
365}
366
367void ThreadWithParamBase::Join() {
368  GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
369      << "Failed to join the thread with error " << ::GetLastError() << ".";
370}
371
372// Maps a thread to a set of ThreadIdToThreadLocals that have values
373// instantiated on that thread and notifies them when the thread exits.  A
374// ThreadLocal instance is expected to persist until all threads it has
375// values on have terminated.
376class ThreadLocalRegistryImpl {
377 public:
378  // Registers thread_local_instance as having value on the current thread.
379  // Returns a value that can be used to identify the thread from other threads.
380  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
381      const ThreadLocalBase* thread_local_instance) {
382    DWORD current_thread = ::GetCurrentThreadId();
383    MutexLock lock(&mutex_);
384    ThreadIdToThreadLocals* const thread_to_thread_locals =
385        GetThreadLocalsMapLocked();
386    ThreadIdToThreadLocals::iterator thread_local_pos =
387        thread_to_thread_locals->find(current_thread);
388    if (thread_local_pos == thread_to_thread_locals->end()) {
389      thread_local_pos = thread_to_thread_locals->insert(
390          std::make_pair(current_thread, ThreadLocalValues())).first;
391      StartWatcherThreadFor(current_thread);
392    }
393    ThreadLocalValues& thread_local_values = thread_local_pos->second;
394    ThreadLocalValues::iterator value_pos =
395        thread_local_values.find(thread_local_instance);
396    if (value_pos == thread_local_values.end()) {
397      value_pos =
398          thread_local_values
399              .insert(std::make_pair(
400                  thread_local_instance,
401                  linked_ptr<ThreadLocalValueHolderBase>(
402                      thread_local_instance->NewValueForCurrentThread())))
403              .first;
404    }
405    return value_pos->second.get();
406  }
407
408  static void OnThreadLocalDestroyed(
409      const ThreadLocalBase* thread_local_instance) {
410    std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
411    // Clean up the ThreadLocalValues data structure while holding the lock, but
412    // defer the destruction of the ThreadLocalValueHolderBases.
413    {
414      MutexLock lock(&mutex_);
415      ThreadIdToThreadLocals* const thread_to_thread_locals =
416          GetThreadLocalsMapLocked();
417      for (ThreadIdToThreadLocals::iterator it =
418          thread_to_thread_locals->begin();
419          it != thread_to_thread_locals->end();
420          ++it) {
421        ThreadLocalValues& thread_local_values = it->second;
422        ThreadLocalValues::iterator value_pos =
423            thread_local_values.find(thread_local_instance);
424        if (value_pos != thread_local_values.end()) {
425          value_holders.push_back(value_pos->second);
426          thread_local_values.erase(value_pos);
427          // This 'if' can only be successful at most once, so theoretically we
428          // could break out of the loop here, but we don't bother doing so.
429        }
430      }
431    }
432    // Outside the lock, let the destructor for 'value_holders' deallocate the
433    // ThreadLocalValueHolderBases.
434  }
435
436  static void OnThreadExit(DWORD thread_id) {
437    GTEST_CHECK_(thread_id != 0) << ::GetLastError();
438    std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
439    // Clean up the ThreadIdToThreadLocals data structure while holding the
440    // lock, but defer the destruction of the ThreadLocalValueHolderBases.
441    {
442      MutexLock lock(&mutex_);
443      ThreadIdToThreadLocals* const thread_to_thread_locals =
444          GetThreadLocalsMapLocked();
445      ThreadIdToThreadLocals::iterator thread_local_pos =
446          thread_to_thread_locals->find(thread_id);
447      if (thread_local_pos != thread_to_thread_locals->end()) {
448        ThreadLocalValues& thread_local_values = thread_local_pos->second;
449        for (ThreadLocalValues::iterator value_pos =
450            thread_local_values.begin();
451            value_pos != thread_local_values.end();
452            ++value_pos) {
453          value_holders.push_back(value_pos->second);
454        }
455        thread_to_thread_locals->erase(thread_local_pos);
456      }
457    }
458    // Outside the lock, let the destructor for 'value_holders' deallocate the
459    // ThreadLocalValueHolderBases.
460  }
461
462 private:
463  // In a particular thread, maps a ThreadLocal object to its value.
464  typedef std::map<const ThreadLocalBase*,
465                   linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
466  // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
467  // thread's ID.
468  typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
469
470  // Holds the thread id and thread handle that we pass from
471  // StartWatcherThreadFor to WatcherThreadFunc.
472  typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
473
474  static void StartWatcherThreadFor(DWORD thread_id) {
475    // The returned handle will be kept in thread_map and closed by
476    // watcher_thread in WatcherThreadFunc.
477    HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
478                                 FALSE,
479                                 thread_id);
480    GTEST_CHECK_(thread != NULL);
481    // We need to to pass a valid thread ID pointer into CreateThread for it
482    // to work correctly under Win98.
483    DWORD watcher_thread_id;
484    HANDLE watcher_thread = ::CreateThread(
485        NULL,   // Default security.
486        0,      // Default stack size
487        &ThreadLocalRegistryImpl::WatcherThreadFunc,
488        reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
489        CREATE_SUSPENDED,
490        &watcher_thread_id);
491    GTEST_CHECK_(watcher_thread != NULL);
492    // Give the watcher thread the same priority as ours to avoid being
493    // blocked by it.
494    ::SetThreadPriority(watcher_thread,
495                        ::GetThreadPriority(::GetCurrentThread()));
496    ::ResumeThread(watcher_thread);
497    ::CloseHandle(watcher_thread);
498  }
499
500  // Monitors exit from a given thread and notifies those
501  // ThreadIdToThreadLocals about thread termination.
502  static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
503    const ThreadIdAndHandle* tah =
504        reinterpret_cast<const ThreadIdAndHandle*>(param);
505    GTEST_CHECK_(
506        ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
507    OnThreadExit(tah->first);
508    ::CloseHandle(tah->second);
509    delete tah;
510    return 0;
511  }
512
513  // Returns map of thread local instances.
514  static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
515    mutex_.AssertHeld();
516    static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;
517    return map;
518  }
519
520  // Protects access to GetThreadLocalsMapLocked() and its return value.
521  static Mutex mutex_;
522  // Protects access to GetThreadMapLocked() and its return value.
523  static Mutex thread_map_mutex_;
524};
525
526Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
527Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
528
529ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
530      const ThreadLocalBase* thread_local_instance) {
531  return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
532      thread_local_instance);
533}
534
535void ThreadLocalRegistry::OnThreadLocalDestroyed(
536      const ThreadLocalBase* thread_local_instance) {
537  ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
538}
539
540#endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
541
542#if GTEST_USES_POSIX_RE
543
544// Implements RE.  Currently only needed for death tests.
545
546RE::~RE() {
547  if (is_valid_) {
548    // regfree'ing an invalid regex might crash because the content
549    // of the regex is undefined. Since the regex's are essentially
550    // the same, one cannot be valid (or invalid) without the other
551    // being so too.
552    regfree(&partial_regex_);
553    regfree(&full_regex_);
554  }
555  free(const_cast<char*>(pattern_));
556}
557
558// Returns true iff regular expression re matches the entire str.
559bool RE::FullMatch(const char* str, const RE& re) {
560  if (!re.is_valid_) return false;
561
562  regmatch_t match;
563  return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
564}
565
566// Returns true iff regular expression re matches a substring of str
567// (including str itself).
568bool RE::PartialMatch(const char* str, const RE& re) {
569  if (!re.is_valid_) return false;
570
571  regmatch_t match;
572  return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
573}
574
575// Initializes an RE from its string representation.
576void RE::Init(const char* regex) {
577  pattern_ = posix::StrDup(regex);
578
579  // Reserves enough bytes to hold the regular expression used for a
580  // full match.
581  const size_t full_regex_len = strlen(regex) + 10;
582  char* const full_pattern = new char[full_regex_len];
583
584  snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
585  is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
586  // We want to call regcomp(&partial_regex_, ...) even if the
587  // previous expression returns false.  Otherwise partial_regex_ may
588  // not be properly initialized can may cause trouble when it's
589  // freed.
590  //
591  // Some implementation of POSIX regex (e.g. on at least some
592  // versions of Cygwin) doesn't accept the empty string as a valid
593  // regex.  We change it to an equivalent form "()" to be safe.
594  if (is_valid_) {
595    const char* const partial_regex = (*regex == '\0') ? "()" : regex;
596    is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
597  }
598  EXPECT_TRUE(is_valid_)
599      << "Regular expression \"" << regex
600      << "\" is not a valid POSIX Extended regular expression.";
601
602  delete[] full_pattern;
603}
604
605#elif GTEST_USES_SIMPLE_RE
606
607// Returns true iff ch appears anywhere in str (excluding the
608// terminating '\0' character).
609bool IsInSet(char ch, const char* str) {
610  return ch != '\0' && strchr(str, ch) != NULL;
611}
612
613// Returns true iff ch belongs to the given classification.  Unlike
614// similar functions in <ctype.h>, these aren't affected by the
615// current locale.
616bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
617bool IsAsciiPunct(char ch) {
618  return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
619}
620bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
621bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
622bool IsAsciiWordChar(char ch) {
623  return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
624      ('0' <= ch && ch <= '9') || ch == '_';
625}
626
627// Returns true iff "\\c" is a supported escape sequence.
628bool IsValidEscape(char c) {
629  return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
630}
631
632// Returns true iff the given atom (specified by escaped and pattern)
633// matches ch.  The result is undefined if the atom is invalid.
634bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
635  if (escaped) {  // "\\p" where p is pattern_char.
636    switch (pattern_char) {
637      case 'd': return IsAsciiDigit(ch);
638      case 'D': return !IsAsciiDigit(ch);
639      case 'f': return ch == '\f';
640      case 'n': return ch == '\n';
641      case 'r': return ch == '\r';
642      case 's': return IsAsciiWhiteSpace(ch);
643      case 'S': return !IsAsciiWhiteSpace(ch);
644      case 't': return ch == '\t';
645      case 'v': return ch == '\v';
646      case 'w': return IsAsciiWordChar(ch);
647      case 'W': return !IsAsciiWordChar(ch);
648    }
649    return IsAsciiPunct(pattern_char) && pattern_char == ch;
650  }
651
652  return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
653}
654
655// Helper function used by ValidateRegex() to format error messages.
656std::string FormatRegexSyntaxError(const char* regex, int index) {
657  return (Message() << "Syntax error at index " << index
658          << " in simple regular expression \"" << regex << "\": ").GetString();
659}
660
661// Generates non-fatal failures and returns false if regex is invalid;
662// otherwise returns true.
663bool ValidateRegex(const char* regex) {
664  if (regex == NULL) {
665    // TODO(wan@google.com): fix the source file location in the
666    // assertion failures to match where the regex is used in user
667    // code.
668    ADD_FAILURE() << "NULL is not a valid simple regular expression.";
669    return false;
670  }
671
672  bool is_valid = true;
673
674  // True iff ?, *, or + can follow the previous atom.
675  bool prev_repeatable = false;
676  for (int i = 0; regex[i]; i++) {
677    if (regex[i] == '\\') {  // An escape sequence
678      i++;
679      if (regex[i] == '\0') {
680        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
681                      << "'\\' cannot appear at the end.";
682        return false;
683      }
684
685      if (!IsValidEscape(regex[i])) {
686        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
687                      << "invalid escape sequence \"\\" << regex[i] << "\".";
688        is_valid = false;
689      }
690      prev_repeatable = true;
691    } else {  // Not an escape sequence.
692      const char ch = regex[i];
693
694      if (ch == '^' && i > 0) {
695        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
696                      << "'^' can only appear at the beginning.";
697        is_valid = false;
698      } else if (ch == '$' && regex[i + 1] != '\0') {
699        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
700                      << "'$' can only appear at the end.";
701        is_valid = false;
702      } else if (IsInSet(ch, "()[]{}|")) {
703        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
704                      << "'" << ch << "' is unsupported.";
705        is_valid = false;
706      } else if (IsRepeat(ch) && !prev_repeatable) {
707        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
708                      << "'" << ch << "' can only follow a repeatable token.";
709        is_valid = false;
710      }
711
712      prev_repeatable = !IsInSet(ch, "^$?*+");
713    }
714  }
715
716  return is_valid;
717}
718
719// Matches a repeated regex atom followed by a valid simple regular
720// expression.  The regex atom is defined as c if escaped is false,
721// or \c otherwise.  repeat is the repetition meta character (?, *,
722// or +).  The behavior is undefined if str contains too many
723// characters to be indexable by size_t, in which case the test will
724// probably time out anyway.  We are fine with this limitation as
725// std::string has it too.
726bool MatchRepetitionAndRegexAtHead(
727    bool escaped, char c, char repeat, const char* regex,
728    const char* str) {
729  const size_t min_count = (repeat == '+') ? 1 : 0;
730  const size_t max_count = (repeat == '?') ? 1 :
731      static_cast<size_t>(-1) - 1;
732  // We cannot call numeric_limits::max() as it conflicts with the
733  // max() macro on Windows.
734
735  for (size_t i = 0; i <= max_count; ++i) {
736    // We know that the atom matches each of the first i characters in str.
737    if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
738      // We have enough matches at the head, and the tail matches too.
739      // Since we only care about *whether* the pattern matches str
740      // (as opposed to *how* it matches), there is no need to find a
741      // greedy match.
742      return true;
743    }
744    if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
745      return false;
746  }
747  return false;
748}
749
750// Returns true iff regex matches a prefix of str.  regex must be a
751// valid simple regular expression and not start with "^", or the
752// result is undefined.
753bool MatchRegexAtHead(const char* regex, const char* str) {
754  if (*regex == '\0')  // An empty regex matches a prefix of anything.
755    return true;
756
757  // "$" only matches the end of a string.  Note that regex being
758  // valid guarantees that there's nothing after "$" in it.
759  if (*regex == '$')
760    return *str == '\0';
761
762  // Is the first thing in regex an escape sequence?
763  const bool escaped = *regex == '\\';
764  if (escaped)
765    ++regex;
766  if (IsRepeat(regex[1])) {
767    // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
768    // here's an indirect recursion.  It terminates as the regex gets
769    // shorter in each recursion.
770    return MatchRepetitionAndRegexAtHead(
771        escaped, regex[0], regex[1], regex + 2, str);
772  } else {
773    // regex isn't empty, isn't "$", and doesn't start with a
774    // repetition.  We match the first atom of regex with the first
775    // character of str and recurse.
776    return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
777        MatchRegexAtHead(regex + 1, str + 1);
778  }
779}
780
781// Returns true iff regex matches any substring of str.  regex must be
782// a valid simple regular expression, or the result is undefined.
783//
784// The algorithm is recursive, but the recursion depth doesn't exceed
785// the regex length, so we won't need to worry about running out of
786// stack space normally.  In rare cases the time complexity can be
787// exponential with respect to the regex length + the string length,
788// but usually it's must faster (often close to linear).
789bool MatchRegexAnywhere(const char* regex, const char* str) {
790  if (regex == NULL || str == NULL)
791    return false;
792
793  if (*regex == '^')
794    return MatchRegexAtHead(regex + 1, str);
795
796  // A successful match can be anywhere in str.
797  do {
798    if (MatchRegexAtHead(regex, str))
799      return true;
800  } while (*str++ != '\0');
801  return false;
802}
803
804// Implements the RE class.
805
806RE::~RE() {
807  free(const_cast<char*>(pattern_));
808  free(const_cast<char*>(full_pattern_));
809}
810
811// Returns true iff regular expression re matches the entire str.
812bool RE::FullMatch(const char* str, const RE& re) {
813  return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
814}
815
816// Returns true iff regular expression re matches a substring of str
817// (including str itself).
818bool RE::PartialMatch(const char* str, const RE& re) {
819  return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
820}
821
822// Initializes an RE from its string representation.
823void RE::Init(const char* regex) {
824  pattern_ = full_pattern_ = NULL;
825  if (regex != NULL) {
826    pattern_ = posix::StrDup(regex);
827  }
828
829  is_valid_ = ValidateRegex(regex);
830  if (!is_valid_) {
831    // No need to calculate the full pattern when the regex is invalid.
832    return;
833  }
834
835  const size_t len = strlen(regex);
836  // Reserves enough bytes to hold the regular expression used for a
837  // full match: we need space to prepend a '^', append a '$', and
838  // terminate the string with '\0'.
839  char* buffer = static_cast<char*>(malloc(len + 3));
840  full_pattern_ = buffer;
841
842  if (*regex != '^')
843    *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
844
845  // We don't use snprintf or strncpy, as they trigger a warning when
846  // compiled with VC++ 8.0.
847  memcpy(buffer, regex, len);
848  buffer += len;
849
850  if (len == 0 || regex[len - 1] != '$')
851    *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
852
853  *buffer = '\0';
854}
855
856#endif  // GTEST_USES_POSIX_RE
857
858const char kUnknownFile[] = "unknown file";
859
860// Formats a source file path and a line number as they would appear
861// in an error message from the compiler used to compile this code.
862GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
863  const std::string file_name(file == NULL ? kUnknownFile : file);
864
865  if (line < 0) {
866    return file_name + ":";
867  }
868#ifdef _MSC_VER
869  return file_name + "(" + StreamableToString(line) + "):";
870#else
871  return file_name + ":" + StreamableToString(line) + ":";
872#endif  // _MSC_VER
873}
874
875// Formats a file location for compiler-independent XML output.
876// Although this function is not platform dependent, we put it next to
877// FormatFileLocation in order to contrast the two functions.
878// Note that FormatCompilerIndependentFileLocation() does NOT append colon
879// to the file location it produces, unlike FormatFileLocation().
880GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
881    const char* file, int line) {
882  const std::string file_name(file == NULL ? kUnknownFile : file);
883
884  if (line < 0)
885    return file_name;
886  else
887    return file_name + ":" + StreamableToString(line);
888}
889
890GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
891    : severity_(severity) {
892  const char* const marker =
893      severity == GTEST_INFO ?    "[  INFO ]" :
894      severity == GTEST_WARNING ? "[WARNING]" :
895      severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
896  GetStream() << ::std::endl << marker << " "
897              << FormatFileLocation(file, line).c_str() << ": ";
898}
899
900// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
901GTestLog::~GTestLog() {
902  GetStream() << ::std::endl;
903  if (severity_ == GTEST_FATAL) {
904    fflush(stderr);
905    posix::Abort();
906  }
907}
908// Disable Microsoft deprecation warnings for POSIX functions called from
909// this class (creat, dup, dup2, and close)
910GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
911
912#if GTEST_HAS_STREAM_REDIRECTION
913
914// Object that captures an output stream (stdout/stderr).
915class CapturedStream {
916 public:
917  // The ctor redirects the stream to a temporary file.
918  explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
919# if GTEST_OS_WINDOWS
920    char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
921    char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
922
923    ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
924    const UINT success = ::GetTempFileNameA(temp_dir_path,
925                                            "gtest_redir",
926                                            0,  // Generate unique file name.
927                                            temp_file_path);
928    GTEST_CHECK_(success != 0)
929        << "Unable to create a temporary file in " << temp_dir_path;
930    const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
931    GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
932                                    << temp_file_path;
933    filename_ = temp_file_path;
934# else
935    // There's no guarantee that a test has write access to the current
936    // directory, so we create the temporary file in the /tmp directory
937    // instead. We use /tmp on most systems, and /sdcard on Android.
938    // That's because Android doesn't have /tmp.
939#  if GTEST_OS_LINUX_ANDROID
940    // Note: Android applications are expected to call the framework's
941    // Context.getExternalStorageDirectory() method through JNI to get
942    // the location of the world-writable SD Card directory. However,
943    // this requires a Context handle, which cannot be retrieved
944    // globally from native code. Doing so also precludes running the
945    // code as part of a regular standalone executable, which doesn't
946    // run in a Dalvik process (e.g. when running it through 'adb shell').
947    //
948    // The location /sdcard is directly accessible from native code
949    // and is the only location (unofficially) supported by the Android
950    // team. It's generally a symlink to the real SD Card mount point
951    // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
952    // other OEM-customized locations. Never rely on these, and always
953    // use /sdcard.
954    char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
955#  else
956    char name_template[] = "/tmp/captured_stream.XXXXXX";
957#  endif  // GTEST_OS_LINUX_ANDROID
958    const int captured_fd = mkstemp(name_template);
959    filename_ = name_template;
960# endif  // GTEST_OS_WINDOWS
961    fflush(NULL);
962    dup2(captured_fd, fd_);
963    close(captured_fd);
964  }
965
966  ~CapturedStream() {
967    remove(filename_.c_str());
968  }
969
970  std::string GetCapturedString() {
971    if (uncaptured_fd_ != -1) {
972      // Restores the original stream.
973      fflush(NULL);
974      dup2(uncaptured_fd_, fd_);
975      close(uncaptured_fd_);
976      uncaptured_fd_ = -1;
977    }
978
979    FILE* const file = posix::FOpen(filename_.c_str(), "r");
980    const std::string content = ReadEntireFile(file);
981    posix::FClose(file);
982    return content;
983  }
984
985 private:
986  const int fd_;  // A stream to capture.
987  int uncaptured_fd_;
988  // Name of the temporary file holding the stderr output.
989  ::std::string filename_;
990
991  GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
992};
993
994GTEST_DISABLE_MSC_WARNINGS_POP_()
995
996static CapturedStream* g_captured_stderr = NULL;
997static CapturedStream* g_captured_stdout = NULL;
998
999// Starts capturing an output stream (stdout/stderr).
1000void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
1001  if (*stream != NULL) {
1002    GTEST_LOG_(FATAL) << "Only one " << stream_name
1003                      << " capturer can exist at a time.";
1004  }
1005  *stream = new CapturedStream(fd);
1006}
1007
1008// Stops capturing the output stream and returns the captured string.
1009std::string GetCapturedStream(CapturedStream** captured_stream) {
1010  const std::string content = (*captured_stream)->GetCapturedString();
1011
1012  delete *captured_stream;
1013  *captured_stream = NULL;
1014
1015  return content;
1016}
1017
1018// Starts capturing stdout.
1019void CaptureStdout() {
1020  CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
1021}
1022
1023// Starts capturing stderr.
1024void CaptureStderr() {
1025  CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
1026}
1027
1028// Stops capturing stdout and returns the captured string.
1029std::string GetCapturedStdout() {
1030  return GetCapturedStream(&g_captured_stdout);
1031}
1032
1033// Stops capturing stderr and returns the captured string.
1034std::string GetCapturedStderr() {
1035  return GetCapturedStream(&g_captured_stderr);
1036}
1037
1038#endif  // GTEST_HAS_STREAM_REDIRECTION
1039
1040std::string TempDir() {
1041#if GTEST_OS_WINDOWS_MOBILE
1042  return "\\temp\\";
1043#elif GTEST_OS_WINDOWS
1044  const char* temp_dir = posix::GetEnv("TEMP");
1045  if (temp_dir == NULL || temp_dir[0] == '\0')
1046    return "\\temp\\";
1047  else if (temp_dir[strlen(temp_dir) - 1] == '\\')
1048    return temp_dir;
1049  else
1050    return std::string(temp_dir) + "\\";
1051#elif GTEST_OS_LINUX_ANDROID
1052  return "/sdcard/";
1053#else
1054  return "/tmp/";
1055#endif  // GTEST_OS_WINDOWS_MOBILE
1056}
1057
1058size_t GetFileSize(FILE* file) {
1059  fseek(file, 0, SEEK_END);
1060  return static_cast<size_t>(ftell(file));
1061}
1062
1063std::string ReadEntireFile(FILE* file) {
1064  const size_t file_size = GetFileSize(file);
1065  char* const buffer = new char[file_size];
1066
1067  size_t bytes_last_read = 0;  // # of bytes read in the last fread()
1068  size_t bytes_read = 0;       // # of bytes read so far
1069
1070  fseek(file, 0, SEEK_SET);
1071
1072  // Keeps reading the file until we cannot read further or the
1073  // pre-determined file size is reached.
1074  do {
1075    bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
1076    bytes_read += bytes_last_read;
1077  } while (bytes_last_read > 0 && bytes_read < file_size);
1078
1079  const std::string content(buffer, bytes_read);
1080  delete[] buffer;
1081
1082  return content;
1083}
1084
1085#if GTEST_HAS_DEATH_TEST
1086
1087static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
1088                                        NULL;  // Owned.
1089
1090void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
1091  if (g_injected_test_argvs != argvs)
1092    delete g_injected_test_argvs;
1093  g_injected_test_argvs = argvs;
1094}
1095
1096const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
1097  if (g_injected_test_argvs != NULL) {
1098    return *g_injected_test_argvs;
1099  }
1100  return GetArgvs();
1101}
1102#endif  // GTEST_HAS_DEATH_TEST
1103
1104#if GTEST_OS_WINDOWS_MOBILE
1105namespace posix {
1106void Abort() {
1107  DebugBreak();
1108  TerminateProcess(GetCurrentProcess(), 1);
1109}
1110}  // namespace posix
1111#endif  // GTEST_OS_WINDOWS_MOBILE
1112
1113// Returns the name of the environment variable corresponding to the
1114// given flag.  For example, FlagToEnvVar("foo") will return
1115// "GTEST_FOO" in the open-source version.
1116static std::string FlagToEnvVar(const char* flag) {
1117  const std::string full_flag =
1118      (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
1119
1120  Message env_var;
1121  for (size_t i = 0; i != full_flag.length(); i++) {
1122    env_var << ToUpper(full_flag.c_str()[i]);
1123  }
1124
1125  return env_var.GetString();
1126}
1127
1128// Parses 'str' for a 32-bit signed integer.  If successful, writes
1129// the result to *value and returns true; otherwise leaves *value
1130// unchanged and returns false.
1131bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
1132  // Parses the environment variable as a decimal integer.
1133  char* end = NULL;
1134  const long long_value = strtol(str, &end, 10);  // NOLINT
1135
1136  // Has strtol() consumed all characters in the string?
1137  if (*end != '\0') {
1138    // No - an invalid character was encountered.
1139    Message msg;
1140    msg << "WARNING: " << src_text
1141        << " is expected to be a 32-bit integer, but actually"
1142        << " has value \"" << str << "\".\n";
1143    printf("%s", msg.GetString().c_str());
1144    fflush(stdout);
1145    return false;
1146  }
1147
1148  // Is the parsed value in the range of an Int32?
1149  const Int32 result = static_cast<Int32>(long_value);
1150  if (long_value == LONG_MAX || long_value == LONG_MIN ||
1151      // The parsed value overflows as a long.  (strtol() returns
1152      // LONG_MAX or LONG_MIN when the input overflows.)
1153      result != long_value
1154      // The parsed value overflows as an Int32.
1155      ) {
1156    Message msg;
1157    msg << "WARNING: " << src_text
1158        << " is expected to be a 32-bit integer, but actually"
1159        << " has value " << str << ", which overflows.\n";
1160    printf("%s", msg.GetString().c_str());
1161    fflush(stdout);
1162    return false;
1163  }
1164
1165  *value = result;
1166  return true;
1167}
1168
1169// Reads and returns the Boolean environment variable corresponding to
1170// the given flag; if it's not set, returns default_value.
1171//
1172// The value is considered true iff it's not "0".
1173bool BoolFromGTestEnv(const char* flag, bool default_value) {
1174#if defined(GTEST_GET_BOOL_FROM_ENV_)
1175  return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1176#endif  // defined(GTEST_GET_BOOL_FROM_ENV_)
1177  const std::string env_var = FlagToEnvVar(flag);
1178  const char* const string_value = posix::GetEnv(env_var.c_str());
1179  return string_value == NULL ?
1180      default_value : strcmp(string_value, "0") != 0;
1181}
1182
1183// Reads and returns a 32-bit integer stored in the environment
1184// variable corresponding to the given flag; if it isn't set or
1185// doesn't represent a valid 32-bit integer, returns default_value.
1186Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
1187#if defined(GTEST_GET_INT32_FROM_ENV_)
1188  return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1189#endif  // defined(GTEST_GET_INT32_FROM_ENV_)
1190  const std::string env_var = FlagToEnvVar(flag);
1191  const char* const string_value = posix::GetEnv(env_var.c_str());
1192  if (string_value == NULL) {
1193    // The environment variable is not set.
1194    return default_value;
1195  }
1196
1197  Int32 result = default_value;
1198  if (!ParseInt32(Message() << "Environment variable " << env_var,
1199                  string_value, &result)) {
1200    printf("The default value %s is used.\n",
1201           (Message() << default_value).GetString().c_str());
1202    fflush(stdout);
1203    return default_value;
1204  }
1205
1206  return result;
1207}
1208
1209// Reads and returns the string environment variable corresponding to
1210// the given flag; if it's not set, returns default_value.
1211const char* StringFromGTestEnv(const char* flag, const char* default_value) {
1212#if defined(GTEST_GET_STRING_FROM_ENV_)
1213  return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1214#endif  // defined(GTEST_GET_STRING_FROM_ENV_)
1215  const std::string env_var = FlagToEnvVar(flag);
1216  const char* const value = posix::GetEnv(env_var.c_str());
1217  return value == NULL ? default_value : value;
1218}
1219
1220}  // namespace internal
1221}  // namespace testing
trunk/3rdparty/googletest/googletest/src/gtest-printers.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Test - The Google C++ Testing Framework
33//
34// This file implements a universal value printer that can print a
35// value of any type T:
36//
37//   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
38//
39// It uses the << operator when possible, and prints the bytes in the
40// object otherwise.  A user can override its behavior for a class
41// type Foo by defining either operator<<(::std::ostream&, const Foo&)
42// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
43// defines Foo.
44
45#include "gtest/gtest-printers.h"
46#include <ctype.h>
47#include <stdio.h>
48#include <cwchar>
49#include <ostream>  // NOLINT
50#include <string>
51#include "gtest/internal/gtest-port.h"
52
53namespace testing {
54
55namespace {
56
57using ::std::ostream;
58
59// Prints a segment of bytes in the given object.
60GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
61GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
62GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
63void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
64                                size_t count, ostream* os) {
65  char text[5] = "";
66  for (size_t i = 0; i != count; i++) {
67    const size_t j = start + i;
68    if (i != 0) {
69      // Organizes the bytes into groups of 2 for easy parsing by
70      // human.
71      if ((j % 2) == 0)
72        *os << ' ';
73      else
74        *os << '-';
75    }
76    GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
77    *os << text;
78  }
79}
80
81// Prints the bytes in the given value to the given ostream.
82void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
83                              ostream* os) {
84  // Tells the user how big the object is.
85  *os << count << "-byte object <";
86
87  const size_t kThreshold = 132;
88  const size_t kChunkSize = 64;
89  // If the object size is bigger than kThreshold, we'll have to omit
90  // some details by printing only the first and the last kChunkSize
91  // bytes.
92  // TODO(wan): let the user control the threshold using a flag.
93  if (count < kThreshold) {
94    PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
95  } else {
96    PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
97    *os << " ... ";
98    // Rounds up to 2-byte boundary.
99    const size_t resume_pos = (count - kChunkSize + 1)/2*2;
100    PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
101  }
102  *os << ">";
103}
104
105}  // namespace
106
107namespace internal2 {
108
109// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
110// given object.  The delegation simplifies the implementation, which
111// uses the << operator and thus is easier done outside of the
112// ::testing::internal namespace, which contains a << operator that
113// sometimes conflicts with the one in STL.
114void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
115                          ostream* os) {
116  PrintBytesInObjectToImpl(obj_bytes, count, os);
117}
118
119}  // namespace internal2
120
121namespace internal {
122
123// Depending on the value of a char (or wchar_t), we print it in one
124// of three formats:
125//   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
126//   - as a hexidecimal escape sequence (e.g. '\x7F'), or
127//   - as a special escape sequence (e.g. '\r', '\n').
128enum CharFormat {
129  kAsIs,
130  kHexEscape,
131  kSpecialEscape
132};
133
134// Returns true if c is a printable ASCII character.  We test the
135// value of c directly instead of calling isprint(), which is buggy on
136// Windows Mobile.
137inline bool IsPrintableAscii(wchar_t c) {
138  return 0x20 <= c && c <= 0x7E;
139}
140
141// Prints a wide or narrow char c as a character literal without the
142// quotes, escaping it when necessary; returns how c was formatted.
143// The template argument UnsignedChar is the unsigned version of Char,
144// which is the type of c.
145template <typename UnsignedChar, typename Char>
146static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
147  switch (static_cast<wchar_t>(c)) {
148    case L'\0':
149      *os << "\\0";
150      break;
151    case L'\'':
152      *os << "\\'";
153      break;
154    case L'\\':
155      *os << "\\\\";
156      break;
157    case L'\a':
158      *os << "\\a";
159      break;
160    case L'\b':
161      *os << "\\b";
162      break;
163    case L'\f':
164      *os << "\\f";
165      break;
166    case L'\n':
167      *os << "\\n";
168      break;
169    case L'\r':
170      *os << "\\r";
171      break;
172    case L'\t':
173      *os << "\\t";
174      break;
175    case L'\v':
176      *os << "\\v";
177      break;
178    default:
179      if (IsPrintableAscii(c)) {
180        *os << static_cast<char>(c);
181        return kAsIs;
182      } else {
183        *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
184        return kHexEscape;
185      }
186  }
187  return kSpecialEscape;
188}
189
190// Prints a wchar_t c as if it's part of a string literal, escaping it when
191// necessary; returns how c was formatted.
192static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
193  switch (c) {
194    case L'\'':
195      *os << "'";
196      return kAsIs;
197    case L'"':
198      *os << "\\\"";
199      return kSpecialEscape;
200    default:
201      return PrintAsCharLiteralTo<wchar_t>(c, os);
202  }
203}
204
205// Prints a char c as if it's part of a string literal, escaping it when
206// necessary; returns how c was formatted.
207static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
208  return PrintAsStringLiteralTo(
209      static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
210}
211
212// Prints a wide or narrow character c and its code.  '\0' is printed
213// as "'\\0'", other unprintable characters are also properly escaped
214// using the standard C++ escape sequence.  The template argument
215// UnsignedChar is the unsigned version of Char, which is the type of c.
216template <typename UnsignedChar, typename Char>
217void PrintCharAndCodeTo(Char c, ostream* os) {
218  // First, print c as a literal in the most readable form we can find.
219  *os << ((sizeof(c) > 1) ? "L'" : "'");
220  const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
221  *os << "'";
222
223  // To aid user debugging, we also print c's code in decimal, unless
224  // it's 0 (in which case c was printed as '\\0', making the code
225  // obvious).
226  if (c == 0)
227    return;
228  *os << " (" << static_cast<int>(c);
229
230  // For more convenience, we print c's code again in hexidecimal,
231  // unless c was already printed in the form '\x##' or the code is in
232  // [1, 9].
233  if (format == kHexEscape || (1 <= c && c <= 9)) {
234    // Do nothing.
235  } else {
236    *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
237  }
238  *os << ")";
239}
240
241void PrintTo(unsigned char c, ::std::ostream* os) {
242  PrintCharAndCodeTo<unsigned char>(c, os);
243}
244void PrintTo(signed char c, ::std::ostream* os) {
245  PrintCharAndCodeTo<unsigned char>(c, os);
246}
247
248// Prints a wchar_t as a symbol if it is printable or as its internal
249// code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
250void PrintTo(wchar_t wc, ostream* os) {
251  PrintCharAndCodeTo<wchar_t>(wc, os);
252}
253
254// Prints the given array of characters to the ostream.  CharType must be either
255// char or wchar_t.
256// The array starts at begin, the length is len, it may include '\0' characters
257// and may not be NUL-terminated.
258template <typename CharType>
259GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
260GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
261GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
262static void PrintCharsAsStringTo(
263    const CharType* begin, size_t len, ostream* os) {
264  const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
265  *os << kQuoteBegin;
266  bool is_previous_hex = false;
267  for (size_t index = 0; index < len; ++index) {
268    const CharType cur = begin[index];
269    if (is_previous_hex && IsXDigit(cur)) {
270      // Previous character is of '\x..' form and this character can be
271      // interpreted as another hexadecimal digit in its number. Break string to
272      // disambiguate.
273      *os << "\" " << kQuoteBegin;
274    }
275    is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
276  }
277  *os << "\"";
278}
279
280// Prints a (const) char/wchar_t array of 'len' elements, starting at address
281// 'begin'.  CharType must be either char or wchar_t.
282template <typename CharType>
283GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
284GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
285GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
286static void UniversalPrintCharArray(
287    const CharType* begin, size_t len, ostream* os) {
288  // The code
289  //   const char kFoo[] = "foo";
290  // generates an array of 4, not 3, elements, with the last one being '\0'.
291  //
292  // Therefore when printing a char array, we don't print the last element if
293  // it's '\0', such that the output matches the string literal as it's
294  // written in the source code.
295  if (len > 0 && begin[len - 1] == '\0') {
296    PrintCharsAsStringTo(begin, len - 1, os);
297    return;
298  }
299
300  // If, however, the last element in the array is not '\0', e.g.
301  //    const char kFoo[] = { 'f', 'o', 'o' };
302  // we must print the entire array.  We also print a message to indicate
303  // that the array is not NUL-terminated.
304  PrintCharsAsStringTo(begin, len, os);
305  *os << " (no terminating NUL)";
306}
307
308// Prints a (const) char array of 'len' elements, starting at address 'begin'.
309void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
310  UniversalPrintCharArray(begin, len, os);
311}
312
313// Prints a (const) wchar_t array of 'len' elements, starting at address
314// 'begin'.
315void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
316  UniversalPrintCharArray(begin, len, os);
317}
318
319// Prints the given C string to the ostream.
320void PrintTo(const char* s, ostream* os) {
321  if (s == NULL) {
322    *os << "NULL";
323  } else {
324    *os << ImplicitCast_<const void*>(s) << " pointing to ";
325    PrintCharsAsStringTo(s, strlen(s), os);
326  }
327}
328
329// MSVC compiler can be configured to define whar_t as a typedef
330// of unsigned short. Defining an overload for const wchar_t* in that case
331// would cause pointers to unsigned shorts be printed as wide strings,
332// possibly accessing more memory than intended and causing invalid
333// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
334// wchar_t is implemented as a native type.
335#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
336// Prints the given wide C string to the ostream.
337void PrintTo(const wchar_t* s, ostream* os) {
338  if (s == NULL) {
339    *os << "NULL";
340  } else {
341    *os << ImplicitCast_<const void*>(s) << " pointing to ";
342    PrintCharsAsStringTo(s, std::wcslen(s), os);
343  }
344}
345#endif  // wchar_t is native
346
347// Prints a ::string object.
348#if GTEST_HAS_GLOBAL_STRING
349void PrintStringTo(const ::string& s, ostream* os) {
350  PrintCharsAsStringTo(s.data(), s.size(), os);
351}
352#endif  // GTEST_HAS_GLOBAL_STRING
353
354void PrintStringTo(const ::std::string& s, ostream* os) {
355  PrintCharsAsStringTo(s.data(), s.size(), os);
356}
357
358// Prints a ::wstring object.
359#if GTEST_HAS_GLOBAL_WSTRING
360void PrintWideStringTo(const ::wstring& s, ostream* os) {
361  PrintCharsAsStringTo(s.data(), s.size(), os);
362}
363#endif  // GTEST_HAS_GLOBAL_WSTRING
364
365#if GTEST_HAS_STD_WSTRING
366void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
367  PrintCharsAsStringTo(s.data(), s.size(), os);
368}
369#endif  // GTEST_HAS_STD_WSTRING
370
371}  // namespace internal
372
373}  // namespace testing
trunk/3rdparty/googletest/googletest/src/gtest-test-part.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: mheule@google.com (Markus Heule)
31//
32// The Google C++ Testing Framework (Google Test)
33
34#include "gtest/gtest-test-part.h"
35
36// Indicates that this translation unit is part of Google Test's
37// implementation.  It must come before gtest-internal-inl.h is
38// included, or there will be a compiler error.  This trick exists to
39// prevent the accidental inclusion of gtest-internal-inl.h in the
40// user's code.
41#define GTEST_IMPLEMENTATION_ 1
42#include "src/gtest-internal-inl.h"
43#undef GTEST_IMPLEMENTATION_
44
45namespace testing {
46
47using internal::GetUnitTestImpl;
48
49// Gets the summary of the failure message by omitting the stack trace
50// in it.
51std::string TestPartResult::ExtractSummary(const char* message) {
52  const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
53  return stack_trace == NULL ? message :
54      std::string(message, stack_trace);
55}
56
57// Prints a TestPartResult object.
58std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
59  return os
60      << result.file_name() << ":" << result.line_number() << ": "
61      << (result.type() == TestPartResult::kSuccess ? "Success" :
62          result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
63          "Non-fatal failure") << ":\n"
64      << result.message() << std::endl;
65}
66
67// Appends a TestPartResult to the array.
68void TestPartResultArray::Append(const TestPartResult& result) {
69  array_.push_back(result);
70}
71
72// Returns the TestPartResult at the given index (0-based).
73const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
74  if (index < 0 || index >= size()) {
75    printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
76    internal::posix::Abort();
77  }
78
79  return array_[index];
80}
81
82// Returns the number of TestPartResult objects in the array.
83int TestPartResultArray::size() const {
84  return static_cast<int>(array_.size());
85}
86
87namespace internal {
88
89HasNewFatalFailureHelper::HasNewFatalFailureHelper()
90    : has_new_fatal_failure_(false),
91      original_reporter_(GetUnitTestImpl()->
92                         GetTestPartResultReporterForCurrentThread()) {
93  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
94}
95
96HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
97  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
98      original_reporter_);
99}
100
101void HasNewFatalFailureHelper::ReportTestPartResult(
102    const TestPartResult& result) {
103  if (result.fatally_failed())
104    has_new_fatal_failure_ = true;
105  original_reporter_->ReportTestPartResult(result);
106}
107
108}  // namespace internal
109
110}  // namespace testing
trunk/3rdparty/googletest/googletest/src/gtest-typed-test.cc
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gtest/gtest-typed-test.h"
33#include "gtest/gtest.h"
34
35namespace testing {
36namespace internal {
37
38#if GTEST_HAS_TYPED_TEST_P
39
40// Skips to the first non-space char in str. Returns an empty string if str
41// contains only whitespace characters.
42static const char* SkipSpaces(const char* str) {
43  while (IsSpace(*str))
44    str++;
45  return str;
46}
47
48static std::vector<std::string> SplitIntoTestNames(const char* src) {
49  std::vector<std::string> name_vec;
50  src = SkipSpaces(src);
51  for (; src != NULL; src = SkipComma(src)) {
52    name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
53  }
54  return name_vec;
55}
56
57// Verifies that registered_tests match the test names in
58// registered_tests_; returns registered_tests if successful, or
59// aborts the program otherwise.
60const char* TypedTestCasePState::VerifyRegisteredTestNames(
61    const char* file, int line, const char* registered_tests) {
62  typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
63  registered_ = true;
64
65  std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
66
67  Message errors;
68
69  std::set<std::string> tests;
70  for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
71       name_it != name_vec.end(); ++name_it) {
72    const std::string& name = *name_it;
73    if (tests.count(name) != 0) {
74      errors << "Test " << name << " is listed more than once.\n";
75      continue;
76    }
77
78    bool found = false;
79    for (RegisteredTestIter it = registered_tests_.begin();
80         it != registered_tests_.end();
81         ++it) {
82      if (name == it->first) {
83        found = true;
84        break;
85      }
86    }
87
88    if (found) {
89      tests.insert(name);
90    } else {
91      errors << "No test named " << name
92             << " can be found in this test case.\n";
93    }
94  }
95
96  for (RegisteredTestIter it = registered_tests_.begin();
97       it != registered_tests_.end();
98       ++it) {
99    if (tests.count(it->first) == 0) {
100      errors << "You forgot to list test " << it->first << ".\n";
101    }
102  }
103
104  const std::string& errors_str = errors.GetString();
105  if (errors_str != "") {
106    fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
107            errors_str.c_str());
108    fflush(stderr);
109    posix::Abort();
110  }
111
112  return registered_tests;
113}
114
115#endif  // GTEST_HAS_TYPED_TEST_P
116
117}  // namespace internal
118}  // namespace testing
trunk/3rdparty/googletest/googletest/src/gtest.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// The Google C++ Testing Framework (Google Test)
33
34#include "gtest/gtest.h"
35#include "gtest/internal/custom/gtest.h"
36#include "gtest/gtest-spi.h"
37
38#include <ctype.h>
39#include <math.h>
40#include <stdarg.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <time.h>
44#include <wchar.h>
45#include <wctype.h>
46
47#include <algorithm>
48#include <iomanip>
49#include <limits>
50#include <list>
51#include <map>
52#include <ostream>  // NOLINT
53#include <sstream>
54#include <vector>
55
56#if GTEST_OS_LINUX
57
58// TODO(kenton@google.com): Use autoconf to detect availability of
59// gettimeofday().
60# define GTEST_HAS_GETTIMEOFDAY_ 1
61
62# include <fcntl.h>  // NOLINT
63# include <limits.h>  // NOLINT
64# include <sched.h>  // NOLINT
65// Declares vsnprintf().  This header is not available on Windows.
66# include <strings.h>  // NOLINT
67# include <sys/mman.h>  // NOLINT
68# include <sys/time.h>  // NOLINT
69# include <unistd.h>  // NOLINT
70# include <string>
71
72#elif GTEST_OS_SYMBIAN
73# define GTEST_HAS_GETTIMEOFDAY_ 1
74# include <sys/time.h>  // NOLINT
75
76#elif GTEST_OS_ZOS
77# define GTEST_HAS_GETTIMEOFDAY_ 1
78# include <sys/time.h>  // NOLINT
79
80// On z/OS we additionally need strings.h for strcasecmp.
81# include <strings.h>  // NOLINT
82
83#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
84
85# include <windows.h>  // NOLINT
86# undef min
87
88#elif GTEST_OS_WINDOWS  // We are on Windows proper.
89
90# include <io.h>  // NOLINT
91# include <sys/timeb.h>  // NOLINT
92# include <sys/types.h>  // NOLINT
93# include <sys/stat.h>  // NOLINT
94
95# if GTEST_OS_WINDOWS_MINGW
96// MinGW has gettimeofday() but not _ftime64().
97// TODO(kenton@google.com): Use autoconf to detect availability of
98//   gettimeofday().
99// TODO(kenton@google.com): There are other ways to get the time on
100//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
101//   supports these.  consider using them instead.
102#  define GTEST_HAS_GETTIMEOFDAY_ 1
103#  include <sys/time.h>  // NOLINT
104# endif  // GTEST_OS_WINDOWS_MINGW
105
106// cpplint thinks that the header is already included, so we want to
107// silence it.
108# include <windows.h>  // NOLINT
109# undef min
110
111#else
112
113// Assume other platforms have gettimeofday().
114// TODO(kenton@google.com): Use autoconf to detect availability of
115//   gettimeofday().
116# define GTEST_HAS_GETTIMEOFDAY_ 1
117
118// cpplint thinks that the header is already included, so we want to
119// silence it.
120# include <sys/time.h>  // NOLINT
121# include <unistd.h>  // NOLINT
122
123#endif  // GTEST_OS_LINUX
124
125#if GTEST_HAS_EXCEPTIONS
126# include <stdexcept>
127#endif
128
129#if GTEST_CAN_STREAM_RESULTS_
130# include <arpa/inet.h>  // NOLINT
131# include <netdb.h>  // NOLINT
132# include <sys/socket.h>  // NOLINT
133# include <sys/types.h>  // NOLINT
134#endif
135
136// Indicates that this translation unit is part of Google Test's
137// implementation.  It must come before gtest-internal-inl.h is
138// included, or there will be a compiler error.  This trick is to
139// prevent a user from accidentally including gtest-internal-inl.h in
140// his code.
141#define GTEST_IMPLEMENTATION_ 1
142#include "src/gtest-internal-inl.h"
143#undef GTEST_IMPLEMENTATION_
144
145#if GTEST_OS_WINDOWS
146# define vsnprintf _vsnprintf
147#endif  // GTEST_OS_WINDOWS
148
149namespace testing {
150
151using internal::CountIf;
152using internal::ForEach;
153using internal::GetElementOr;
154using internal::Shuffle;
155
156// Constants.
157
158// A test whose test case name or test name matches this filter is
159// disabled and not run.
160static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
161
162// A test case whose name matches this filter is considered a death
163// test case and will be run before test cases whose name doesn't
164// match this filter.
165static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
166
167// A test filter that matches everything.
168static const char kUniversalFilter[] = "*";
169
170// The default output file for XML output.
171static const char kDefaultOutputFile[] = "test_detail.xml";
172
173// The environment variable name for the test shard index.
174static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
175// The environment variable name for the total number of test shards.
176static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
177// The environment variable name for the test shard status file.
178static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
179
180namespace internal {
181
182// The text used in failure messages to indicate the start of the
183// stack trace.
184const char kStackTraceMarker[] = "\nStack trace:\n";
185
186// g_help_flag is true iff the --help flag or an equivalent form is
187// specified on the command line.
188bool g_help_flag = false;
189
190}  // namespace internal
191
192static const char* GetDefaultFilter() {
193#ifdef GTEST_TEST_FILTER_ENV_VAR_
194  const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);
195  if (testbridge_test_only != NULL) {
196    return testbridge_test_only;
197  }
198#endif  // GTEST_TEST_FILTER_ENV_VAR_
199  return kUniversalFilter;
200}
201
202GTEST_DEFINE_bool_(
203    also_run_disabled_tests,
204    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
205    "Run disabled tests too, in addition to the tests normally being run.");
206
207GTEST_DEFINE_bool_(
208    break_on_failure,
209    internal::BoolFromGTestEnv("break_on_failure", false),
210    "True iff a failed assertion should be a debugger break-point.");
211
212GTEST_DEFINE_bool_(
213    catch_exceptions,
214    internal::BoolFromGTestEnv("catch_exceptions", true),
215    "True iff " GTEST_NAME_
216    " should catch exceptions and treat them as test failures.");
217
218GTEST_DEFINE_string_(
219    color,
220    internal::StringFromGTestEnv("color", "auto"),
221    "Whether to use colors in the output.  Valid values: yes, no, "
222    "and auto.  'auto' means to use colors if the output is "
223    "being sent to a terminal and the TERM environment variable "
224    "is set to a terminal type that supports colors.");
225
226GTEST_DEFINE_string_(
227    filter,
228    internal::StringFromGTestEnv("filter", GetDefaultFilter()),
229    "A colon-separated list of glob (not regex) patterns "
230    "for filtering the tests to run, optionally followed by a "
231    "'-' and a : separated list of negative patterns (tests to "
232    "exclude).  A test is run if it matches one of the positive "
233    "patterns and does not match any of the negative patterns.");
234
235GTEST_DEFINE_bool_(list_tests, false,
236                   "List all tests without running them.");
237
238GTEST_DEFINE_string_(
239    output,
240    internal::StringFromGTestEnv("output", ""),
241    "A format (currently must be \"xml\"), optionally followed "
242    "by a colon and an output file name or directory. A directory "
243    "is indicated by a trailing pathname separator. "
244    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
245    "If a directory is specified, output files will be created "
246    "within that directory, with file-names based on the test "
247    "executable's name and, if necessary, made unique by adding "
248    "digits.");
249
250GTEST_DEFINE_bool_(
251    print_time,
252    internal::BoolFromGTestEnv("print_time", true),
253    "True iff " GTEST_NAME_
254    " should display elapsed time in text output.");
255
256GTEST_DEFINE_int32_(
257    random_seed,
258    internal::Int32FromGTestEnv("random_seed", 0),
259    "Random number seed to use when shuffling test orders.  Must be in range "
260    "[1, 99999], or 0 to use a seed based on the current time.");
261
262GTEST_DEFINE_int32_(
263    repeat,
264    internal::Int32FromGTestEnv("repeat", 1),
265    "How many times to repeat each test.  Specify a negative number "
266    "for repeating forever.  Useful for shaking out flaky tests.");
267
268GTEST_DEFINE_bool_(
269    show_internal_stack_frames, false,
270    "True iff " GTEST_NAME_ " should include internal stack frames when "
271    "printing test failure stack traces.");
272
273GTEST_DEFINE_bool_(
274    shuffle,
275    internal::BoolFromGTestEnv("shuffle", false),
276    "True iff " GTEST_NAME_
277    " should randomize tests' order on every run.");
278
279GTEST_DEFINE_int32_(
280    stack_trace_depth,
281    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
282    "The maximum number of stack frames to print when an "
283    "assertion fails.  The valid range is 0 through 100, inclusive.");
284
285GTEST_DEFINE_string_(
286    stream_result_to,
287    internal::StringFromGTestEnv("stream_result_to", ""),
288    "This flag specifies the host name and the port number on which to stream "
289    "test results. Example: \"localhost:555\". The flag is effective only on "
290    "Linux.");
291
292GTEST_DEFINE_bool_(
293    throw_on_failure,
294    internal::BoolFromGTestEnv("throw_on_failure", false),
295    "When this flag is specified, a failed assertion will throw an exception "
296    "if exceptions are enabled or exit the program with a non-zero code "
297    "otherwise.");
298
299#if GTEST_USE_OWN_FLAGFILE_FLAG_
300GTEST_DEFINE_string_(
301    flagfile,
302    internal::StringFromGTestEnv("flagfile", ""),
303    "This flag specifies the flagfile to read command-line flags from.");
304#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
305
306namespace internal {
307
308// Generates a random number from [0, range), using a Linear
309// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
310// than kMaxRange.
311UInt32 Random::Generate(UInt32 range) {
312  // These constants are the same as are used in glibc's rand(3).
313  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
314
315  GTEST_CHECK_(range > 0)
316      << "Cannot generate a number in the range [0, 0).";
317  GTEST_CHECK_(range <= kMaxRange)
318      << "Generation of a number in [0, " << range << ") was requested, "
319      << "but this can only generate numbers in [0, " << kMaxRange << ").";
320
321  // Converting via modulus introduces a bit of downward bias, but
322  // it's simple, and a linear congruential generator isn't too good
323  // to begin with.
324  return state_ % range;
325}
326
327// GTestIsInitialized() returns true iff the user has initialized
328// Google Test.  Useful for catching the user mistake of not initializing
329// Google Test before calling RUN_ALL_TESTS().
330static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
331
332// Iterates over a vector of TestCases, keeping a running sum of the
333// results of calling a given int-returning method on each.
334// Returns the sum.
335static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
336                               int (TestCase::*method)() const) {
337  int sum = 0;
338  for (size_t i = 0; i < case_list.size(); i++) {
339    sum += (case_list[i]->*method)();
340  }
341  return sum;
342}
343
344// Returns true iff the test case passed.
345static bool TestCasePassed(const TestCase* test_case) {
346  return test_case->should_run() && test_case->Passed();
347}
348
349// Returns true iff the test case failed.
350static bool TestCaseFailed(const TestCase* test_case) {
351  return test_case->should_run() && test_case->Failed();
352}
353
354// Returns true iff test_case contains at least one test that should
355// run.
356static bool ShouldRunTestCase(const TestCase* test_case) {
357  return test_case->should_run();
358}
359
360// AssertHelper constructor.
361AssertHelper::AssertHelper(TestPartResult::Type type,
362                           const char* file,
363                           int line,
364                           const char* message)
365    : data_(new AssertHelperData(type, file, line, message)) {
366}
367
368AssertHelper::~AssertHelper() {
369  delete data_;
370}
371
372// Message assignment, for assertion streaming support.
373void AssertHelper::operator=(const Message& message) const {
374  UnitTest::GetInstance()->
375    AddTestPartResult(data_->type, data_->file, data_->line,
376                      AppendUserMessage(data_->message, message),
377                      UnitTest::GetInstance()->impl()
378                      ->CurrentOsStackTraceExceptTop(1)
379                      // Skips the stack frame for this function itself.
380                      );  // NOLINT
381}
382
383// Mutex for linked pointers.
384GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
385
386// A copy of all command line arguments.  Set by InitGoogleTest().
387::std::vector<testing::internal::string> g_argvs;
388
389const ::std::vector<testing::internal::string>& GetArgvs() {
390#if defined(GTEST_CUSTOM_GET_ARGVS_)
391  return GTEST_CUSTOM_GET_ARGVS_();
392#else  // defined(GTEST_CUSTOM_GET_ARGVS_)
393  return g_argvs;
394#endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
395}
396
397// Returns the current application's name, removing directory path if that
398// is present.
399FilePath GetCurrentExecutableName() {
400  FilePath result;
401
402#if GTEST_OS_WINDOWS
403  result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
404#else
405  result.Set(FilePath(GetArgvs()[0]));
406#endif  // GTEST_OS_WINDOWS
407
408  return result.RemoveDirectoryName();
409}
410
411// Functions for processing the gtest_output flag.
412
413// Returns the output format, or "" for normal printed output.
414std::string UnitTestOptions::GetOutputFormat() {
415  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
416  if (gtest_output_flag == NULL) return std::string("");
417
418  const char* const colon = strchr(gtest_output_flag, ':');
419  return (colon == NULL) ?
420      std::string(gtest_output_flag) :
421      std::string(gtest_output_flag, colon - gtest_output_flag);
422}
423
424// Returns the name of the requested output file, or the default if none
425// was explicitly specified.
426std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
427  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
428  if (gtest_output_flag == NULL)
429    return "";
430
431  const char* const colon = strchr(gtest_output_flag, ':');
432  if (colon == NULL)
433    return internal::FilePath::ConcatPaths(
434        internal::FilePath(
435            UnitTest::GetInstance()->original_working_dir()),
436        internal::FilePath(kDefaultOutputFile)).string();
437
438  internal::FilePath output_name(colon + 1);
439  if (!output_name.IsAbsolutePath())
440    // TODO(wan@google.com): on Windows \some\path is not an absolute
441    // path (as its meaning depends on the current drive), yet the
442    // following logic for turning it into an absolute path is wrong.
443    // Fix it.
444    output_name = internal::FilePath::ConcatPaths(
445        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
446        internal::FilePath(colon + 1));
447
448  if (!output_name.IsDirectory())
449    return output_name.string();
450
451  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
452      output_name, internal::GetCurrentExecutableName(),
453      GetOutputFormat().c_str()));
454  return result.string();
455}
456
457// Returns true iff the wildcard pattern matches the string.  The
458// first ':' or '\0' character in pattern marks the end of it.
459//
460// This recursive algorithm isn't very efficient, but is clear and
461// works well enough for matching test names, which are short.
462bool UnitTestOptions::PatternMatchesString(const char *pattern,
463                                           const char *str) {
464  switch (*pattern) {
465    case '\0':
466    case ':':  // Either ':' or '\0' marks the end of the pattern.
467      return *str == '\0';
468    case '?':  // Matches any single character.
469      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
470    case '*':  // Matches any string (possibly empty) of characters.
471      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
472          PatternMatchesString(pattern + 1, str);
473    default:  // Non-special character.  Matches itself.
474      return *pattern == *str &&
475          PatternMatchesString(pattern + 1, str + 1);
476  }
477}
478
479bool UnitTestOptions::MatchesFilter(
480    const std::string& name, const char* filter) {
481  const char *cur_pattern = filter;
482  for (;;) {
483    if (PatternMatchesString(cur_pattern, name.c_str())) {
484      return true;
485    }
486
487    // Finds the next pattern in the filter.
488    cur_pattern = strchr(cur_pattern, ':');
489
490    // Returns if no more pattern can be found.
491    if (cur_pattern == NULL) {
492      return false;
493    }
494
495    // Skips the pattern separater (the ':' character).
496    cur_pattern++;
497  }
498}
499
500// Returns true iff the user-specified filter matches the test case
501// name and the test name.
502bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
503                                        const std::string &test_name) {
504  const std::string& full_name = test_case_name + "." + test_name.c_str();
505
506  // Split --gtest_filter at '-', if there is one, to separate into
507  // positive filter and negative filter portions
508  const char* const p = GTEST_FLAG(filter).c_str();
509  const char* const dash = strchr(p, '-');
510  std::string positive;
511  std::string negative;
512  if (dash == NULL) {
513    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
514    negative = "";
515  } else {
516    positive = std::string(p, dash);   // Everything up to the dash
517    negative = std::string(dash + 1);  // Everything after the dash
518    if (positive.empty()) {
519      // Treat '-test1' as the same as '*-test1'
520      positive = kUniversalFilter;
521    }
522  }
523
524  // A filter is a colon-separated list of patterns.  It matches a
525  // test if any pattern in it matches the test.
526  return (MatchesFilter(full_name, positive.c_str()) &&
527          !MatchesFilter(full_name, negative.c_str()));
528}
529
530#if GTEST_HAS_SEH
531// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
532// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
533// This function is useful as an __except condition.
534int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
535  // Google Test should handle a SEH exception if:
536  //   1. the user wants it to, AND
537  //   2. this is not a breakpoint exception, AND
538  //   3. this is not a C++ exception (VC++ implements them via SEH,
539  //      apparently).
540  //
541  // SEH exception code for C++ exceptions.
542  // (see http://support.microsoft.com/kb/185294 for more information).
543  const DWORD kCxxExceptionCode = 0xe06d7363;
544
545  bool should_handle = true;
546
547  if (!GTEST_FLAG(catch_exceptions))
548    should_handle = false;
549  else if (exception_code == EXCEPTION_BREAKPOINT)
550    should_handle = false;
551  else if (exception_code == kCxxExceptionCode)
552    should_handle = false;
553
554  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
555}
556#endif  // GTEST_HAS_SEH
557
558}  // namespace internal
559
560// The c'tor sets this object as the test part result reporter used by
561// Google Test.  The 'result' parameter specifies where to report the
562// results. Intercepts only failures from the current thread.
563ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
564    TestPartResultArray* result)
565    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
566      result_(result) {
567  Init();
568}
569
570// The c'tor sets this object as the test part result reporter used by
571// Google Test.  The 'result' parameter specifies where to report the
572// results.
573ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
574    InterceptMode intercept_mode, TestPartResultArray* result)
575    : intercept_mode_(intercept_mode),
576      result_(result) {
577  Init();
578}
579
580void ScopedFakeTestPartResultReporter::Init() {
581  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
582  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
583    old_reporter_ = impl->GetGlobalTestPartResultReporter();
584    impl->SetGlobalTestPartResultReporter(this);
585  } else {
586    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
587    impl->SetTestPartResultReporterForCurrentThread(this);
588  }
589}
590
591// The d'tor restores the test part result reporter used by Google Test
592// before.
593ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
594  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
595  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
596    impl->SetGlobalTestPartResultReporter(old_reporter_);
597  } else {
598    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
599  }
600}
601
602// Increments the test part result count and remembers the result.
603// This method is from the TestPartResultReporterInterface interface.
604void ScopedFakeTestPartResultReporter::ReportTestPartResult(
605    const TestPartResult& result) {
606  result_->Append(result);
607}
608
609namespace internal {
610
611// Returns the type ID of ::testing::Test.  We should always call this
612// instead of GetTypeId< ::testing::Test>() to get the type ID of
613// testing::Test.  This is to work around a suspected linker bug when
614// using Google Test as a framework on Mac OS X.  The bug causes
615// GetTypeId< ::testing::Test>() to return different values depending
616// on whether the call is from the Google Test framework itself or
617// from user test code.  GetTestTypeId() is guaranteed to always
618// return the same value, as it always calls GetTypeId<>() from the
619// gtest.cc, which is within the Google Test framework.
620TypeId GetTestTypeId() {
621  return GetTypeId<Test>();
622}
623
624// The value of GetTestTypeId() as seen from within the Google Test
625// library.  This is solely for testing GetTestTypeId().
626extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
627
628// This predicate-formatter checks that 'results' contains a test part
629// failure of the given type and that the failure message contains the
630// given substring.
631AssertionResult HasOneFailure(const char* /* results_expr */,
632                              const char* /* type_expr */,
633                              const char* /* substr_expr */,
634                              const TestPartResultArray& results,
635                              TestPartResult::Type type,
636                              const string& substr) {
637  const std::string expected(type == TestPartResult::kFatalFailure ?
638                        "1 fatal failure" :
639                        "1 non-fatal failure");
640  Message msg;
641  if (results.size() != 1) {
642    msg << "Expected: " << expected << "\n"
643        << "  Actual: " << results.size() << " failures";
644    for (int i = 0; i < results.size(); i++) {
645      msg << "\n" << results.GetTestPartResult(i);
646    }
647    return AssertionFailure() << msg;
648  }
649
650  const TestPartResult& r = results.GetTestPartResult(0);
651  if (r.type() != type) {
652    return AssertionFailure() << "Expected: " << expected << "\n"
653                              << "  Actual:\n"
654                              << r;
655  }
656
657  if (strstr(r.message(), substr.c_str()) == NULL) {
658    return AssertionFailure() << "Expected: " << expected << " containing \""
659                              << substr << "\"\n"
660                              << "  Actual:\n"
661                              << r;
662  }
663
664  return AssertionSuccess();
665}
666
667// The constructor of SingleFailureChecker remembers where to look up
668// test part results, what type of failure we expect, and what
669// substring the failure message should contain.
670SingleFailureChecker:: SingleFailureChecker(
671    const TestPartResultArray* results,
672    TestPartResult::Type type,
673    const string& substr)
674    : results_(results),
675      type_(type),
676      substr_(substr) {}
677
678// The destructor of SingleFailureChecker verifies that the given
679// TestPartResultArray contains exactly one failure that has the given
680// type and contains the given substring.  If that's not the case, a
681// non-fatal failure will be generated.
682SingleFailureChecker::~SingleFailureChecker() {
683  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
684}
685
686DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
687    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
688
689void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
690    const TestPartResult& result) {
691  unit_test_->current_test_result()->AddTestPartResult(result);
692  unit_test_->listeners()->repeater()->OnTestPartResult(result);
693}
694
695DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
696    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
697
698void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
699    const TestPartResult& result) {
700  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
701}
702
703// Returns the global test part result reporter.
704TestPartResultReporterInterface*
705UnitTestImpl::GetGlobalTestPartResultReporter() {
706  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
707  return global_test_part_result_repoter_;
708}
709
710// Sets the global test part result reporter.
711void UnitTestImpl::SetGlobalTestPartResultReporter(
712    TestPartResultReporterInterface* reporter) {
713  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
714  global_test_part_result_repoter_ = reporter;
715}
716
717// Returns the test part result reporter for the current thread.
718TestPartResultReporterInterface*
719UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
720  return per_thread_test_part_result_reporter_.get();
721}
722
723// Sets the test part result reporter for the current thread.
724void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
725    TestPartResultReporterInterface* reporter) {
726  per_thread_test_part_result_reporter_.set(reporter);
727}
728
729// Gets the number of successful test cases.
730int UnitTestImpl::successful_test_case_count() const {
731  return CountIf(test_cases_, TestCasePassed);
732}
733
734// Gets the number of failed test cases.
735int UnitTestImpl::failed_test_case_count() const {
736  return CountIf(test_cases_, TestCaseFailed);
737}
738
739// Gets the number of all test cases.
740int UnitTestImpl::total_test_case_count() const {
741  return static_cast<int>(test_cases_.size());
742}
743
744// Gets the number of all test cases that contain at least one test
745// that should run.
746int UnitTestImpl::test_case_to_run_count() const {
747  return CountIf(test_cases_, ShouldRunTestCase);
748}
749
750// Gets the number of successful tests.
751int UnitTestImpl::successful_test_count() const {
752  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
753}
754
755// Gets the number of failed tests.
756int UnitTestImpl::failed_test_count() const {
757  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
758}
759
760// Gets the number of disabled tests that will be reported in the XML report.
761int UnitTestImpl::reportable_disabled_test_count() const {
762  return SumOverTestCaseList(test_cases_,
763                             &TestCase::reportable_disabled_test_count);
764}
765
766// Gets the number of disabled tests.
767int UnitTestImpl::disabled_test_count() const {
768  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
769}
770
771// Gets the number of tests to be printed in the XML report.
772int UnitTestImpl::reportable_test_count() const {
773  return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
774}
775
776// Gets the number of all tests.
777int UnitTestImpl::total_test_count() const {
778  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
779}
780
781// Gets the number of tests that should run.
782int UnitTestImpl::test_to_run_count() const {
783  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
784}
785
786// Returns the current OS stack trace as an std::string.
787//
788// The maximum number of stack frames to be included is specified by
789// the gtest_stack_trace_depth flag.  The skip_count parameter
790// specifies the number of top frames to be skipped, which doesn't
791// count against the number of frames to be included.
792//
793// For example, if Foo() calls Bar(), which in turn calls
794// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
795// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
796std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
797  return os_stack_trace_getter()->CurrentStackTrace(
798      static_cast<int>(GTEST_FLAG(stack_trace_depth)),
799      skip_count + 1
800      // Skips the user-specified number of frames plus this function
801      // itself.
802      );  // NOLINT
803}
804
805// Returns the current time in milliseconds.
806TimeInMillis GetTimeInMillis() {
807#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
808  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
809  // http://analogous.blogspot.com/2005/04/epoch.html
810  const TimeInMillis kJavaEpochToWinFileTimeDelta =
811    static_cast<TimeInMillis>(116444736UL) * 100000UL;
812  const DWORD kTenthMicrosInMilliSecond = 10000;
813
814  SYSTEMTIME now_systime;
815  FILETIME now_filetime;
816  ULARGE_INTEGER now_int64;
817  // TODO(kenton@google.com): Shouldn't this just use
818  //   GetSystemTimeAsFileTime()?
819  GetSystemTime(&now_systime);
820  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
821    now_int64.LowPart = now_filetime.dwLowDateTime;
822    now_int64.HighPart = now_filetime.dwHighDateTime;
823    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
824      kJavaEpochToWinFileTimeDelta;
825    return now_int64.QuadPart;
826  }
827  return 0;
828#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
829  __timeb64 now;
830
831  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
832  // (deprecated function) there.
833  // TODO(kenton@google.com): Use GetTickCount()?  Or use
834  //   SystemTimeToFileTime()
835  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
836  _ftime64(&now);
837  GTEST_DISABLE_MSC_WARNINGS_POP_()
838
839  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
840#elif GTEST_HAS_GETTIMEOFDAY_
841  struct timeval now;
842  gettimeofday(&now, NULL);
843  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
844#else
845# error "Don't know how to get the current time on your system."
846#endif
847}
848
849// Utilities
850
851// class String.
852
853#if GTEST_OS_WINDOWS_MOBILE
854// Creates a UTF-16 wide string from the given ANSI string, allocating
855// memory using new. The caller is responsible for deleting the return
856// value using delete[]. Returns the wide string, or NULL if the
857// input is NULL.
858LPCWSTR String::AnsiToUtf16(const char* ansi) {
859  if (!ansi) return NULL;
860  const int length = strlen(ansi);
861  const int unicode_length =
862      MultiByteToWideChar(CP_ACP, 0, ansi, length,
863                          NULL, 0);
864  WCHAR* unicode = new WCHAR[unicode_length + 1];
865  MultiByteToWideChar(CP_ACP, 0, ansi, length,
866                      unicode, unicode_length);
867  unicode[unicode_length] = 0;
868  return unicode;
869}
870
871// Creates an ANSI string from the given wide string, allocating
872// memory using new. The caller is responsible for deleting the return
873// value using delete[]. Returns the ANSI string, or NULL if the
874// input is NULL.
875const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
876  if (!utf16_str) return NULL;
877  const int ansi_length =
878      WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
879                          NULL, 0, NULL, NULL);
880  char* ansi = new char[ansi_length + 1];
881  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
882                      ansi, ansi_length, NULL, NULL);
883  ansi[ansi_length] = 0;
884  return ansi;
885}
886
887#endif  // GTEST_OS_WINDOWS_MOBILE
888
889// Compares two C strings.  Returns true iff they have the same content.
890//
891// Unlike strcmp(), this function can handle NULL argument(s).  A NULL
892// C string is considered different to any non-NULL C string,
893// including the empty string.
894bool String::CStringEquals(const char * lhs, const char * rhs) {
895  if ( lhs == NULL ) return rhs == NULL;
896
897  if ( rhs == NULL ) return false;
898
899  return strcmp(lhs, rhs) == 0;
900}
901
902#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
903
904// Converts an array of wide chars to a narrow string using the UTF-8
905// encoding, and streams the result to the given Message object.
906static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
907                                     Message* msg) {
908  for (size_t i = 0; i != length; ) {  // NOLINT
909    if (wstr[i] != L'\0') {
910      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
911      while (i != length && wstr[i] != L'\0')
912        i++;
913    } else {
914      *msg << '\0';
915      i++;
916    }
917  }
918}
919
920#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
921
922void SplitString(const ::std::string& str, char delimiter,
923                 ::std::vector< ::std::string>* dest) {
924  ::std::vector< ::std::string> parsed;
925  ::std::string::size_type pos = 0;
926  while (::testing::internal::AlwaysTrue()) {
927    const ::std::string::size_type colon = str.find(delimiter, pos);
928    if (colon == ::std::string::npos) {
929      parsed.push_back(str.substr(pos));
930      break;
931    } else {
932      parsed.push_back(str.substr(pos, colon - pos));
933      pos = colon + 1;
934    }
935  }
936  dest->swap(parsed);
937}
938
939}  // namespace internal
940
941// Constructs an empty Message.
942// We allocate the stringstream separately because otherwise each use of
943// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
944// stack frame leading to huge stack frames in some cases; gcc does not reuse
945// the stack space.
946Message::Message() : ss_(new ::std::stringstream) {
947  // By default, we want there to be enough precision when printing
948  // a double to a Message.
949  *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
950}
951
952// These two overloads allow streaming a wide C string to a Message
953// using the UTF-8 encoding.
954Message& Message::operator <<(const wchar_t* wide_c_str) {
955  return *this << internal::String::ShowWideCString(wide_c_str);
956}
957Message& Message::operator <<(wchar_t* wide_c_str) {
958  return *this << internal::String::ShowWideCString(wide_c_str);
959}
960
961#if GTEST_HAS_STD_WSTRING
962// Converts the given wide string to a narrow string using the UTF-8
963// encoding, and streams the result to this Message object.
964Message& Message::operator <<(const ::std::wstring& wstr) {
965  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
966  return *this;
967}
968#endif  // GTEST_HAS_STD_WSTRING
969
970#if GTEST_HAS_GLOBAL_WSTRING
971// Converts the given wide string to a narrow string using the UTF-8
972// encoding, and streams the result to this Message object.
973Message& Message::operator <<(const ::wstring& wstr) {
974  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
975  return *this;
976}
977#endif  // GTEST_HAS_GLOBAL_WSTRING
978
979// Gets the text streamed to this object so far as an std::string.
980// Each '\0' character in the buffer is replaced with "\\0".
981std::string Message::GetString() const {
982  return internal::StringStreamToString(ss_.get());
983}
984
985// AssertionResult constructors.
986// Used in EXPECT_TRUE/FALSE(assertion_result).
987AssertionResult::AssertionResult(const AssertionResult& other)
988    : success_(other.success_),
989      message_(other.message_.get() != NULL ?
990               new ::std::string(*other.message_) :
991               static_cast< ::std::string*>(NULL)) {
992}
993
994// Swaps two AssertionResults.
995void AssertionResult::swap(AssertionResult& other) {
996  using std::swap;
997  swap(success_, other.success_);
998  swap(message_, other.message_);
999}
1000
1001// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
1002AssertionResult AssertionResult::operator!() const {
1003  AssertionResult negation(!success_);
1004  if (message_.get() != NULL)
1005    negation << *message_;
1006  return negation;
1007}
1008
1009// Makes a successful assertion result.
1010AssertionResult AssertionSuccess() {
1011  return AssertionResult(true);
1012}
1013
1014// Makes a failed assertion result.
1015AssertionResult AssertionFailure() {
1016  return AssertionResult(false);
1017}
1018
1019// Makes a failed assertion result with the given failure message.
1020// Deprecated; use AssertionFailure() << message.
1021AssertionResult AssertionFailure(const Message& message) {
1022  return AssertionFailure() << message;
1023}
1024
1025namespace internal {
1026
1027namespace edit_distance {
1028std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
1029                                            const std::vector<size_t>& right) {
1030  std::vector<std::vector<double> > costs(
1031      left.size() + 1, std::vector<double>(right.size() + 1));
1032  std::vector<std::vector<EditType> > best_move(
1033      left.size() + 1, std::vector<EditType>(right.size() + 1));
1034
1035  // Populate for empty right.
1036  for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
1037    costs[l_i][0] = static_cast<double>(l_i);
1038    best_move[l_i][0] = kRemove;
1039  }
1040  // Populate for empty left.
1041  for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1042    costs[0][r_i] = static_cast<double>(r_i);
1043    best_move[0][r_i] = kAdd;
1044  }
1045
1046  for (size_t l_i = 0; l_i < left.size(); ++l_i) {
1047    for (size_t r_i = 0; r_i < right.size(); ++r_i) {
1048      if (left[l_i] == right[r_i]) {
1049        // Found a match. Consume it.
1050        costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1051        best_move[l_i + 1][r_i + 1] = kMatch;
1052        continue;
1053      }
1054
1055      const double add = costs[l_i + 1][r_i];
1056      const double remove = costs[l_i][r_i + 1];
1057      const double replace = costs[l_i][r_i];
1058      if (add < remove && add < replace) {
1059        costs[l_i + 1][r_i + 1] = add + 1;
1060        best_move[l_i + 1][r_i + 1] = kAdd;
1061      } else if (remove < add && remove < replace) {
1062        costs[l_i + 1][r_i + 1] = remove + 1;
1063        best_move[l_i + 1][r_i + 1] = kRemove;
1064      } else {
1065        // We make replace a little more expensive than add/remove to lower
1066        // their priority.
1067        costs[l_i + 1][r_i + 1] = replace + 1.00001;
1068        best_move[l_i + 1][r_i + 1] = kReplace;
1069      }
1070    }
1071  }
1072
1073  // Reconstruct the best path. We do it in reverse order.
1074  std::vector<EditType> best_path;
1075  for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1076    EditType move = best_move[l_i][r_i];
1077    best_path.push_back(move);
1078    l_i -= move != kAdd;
1079    r_i -= move != kRemove;
1080  }
1081  std::reverse(best_path.begin(), best_path.end());
1082  return best_path;
1083}
1084
1085namespace {
1086
1087// Helper class to convert string into ids with deduplication.
1088class InternalStrings {
1089 public:
1090  size_t GetId(const std::string& str) {
1091    IdMap::iterator it = ids_.find(str);
1092    if (it != ids_.end()) return it->second;
1093    size_t id = ids_.size();
1094    return ids_[str] = id;
1095  }
1096
1097 private:
1098  typedef std::map<std::string, size_t> IdMap;
1099  IdMap ids_;
1100};
1101
1102}  // namespace
1103
1104std::vector<EditType> CalculateOptimalEdits(
1105    const std::vector<std::string>& left,
1106    const std::vector<std::string>& right) {
1107  std::vector<size_t> left_ids, right_ids;
1108  {
1109    InternalStrings intern_table;
1110    for (size_t i = 0; i < left.size(); ++i) {
1111      left_ids.push_back(intern_table.GetId(left[i]));
1112    }
1113    for (size_t i = 0; i < right.size(); ++i) {
1114      right_ids.push_back(intern_table.GetId(right[i]));
1115    }
1116  }
1117  return CalculateOptimalEdits(left_ids, right_ids);
1118}
1119
1120namespace {
1121
1122// Helper class that holds the state for one hunk and prints it out to the
1123// stream.
1124// It reorders adds/removes when possible to group all removes before all
1125// adds. It also adds the hunk header before printint into the stream.
1126class Hunk {
1127 public:
1128  Hunk(size_t left_start, size_t right_start)
1129      : left_start_(left_start),
1130        right_start_(right_start),
1131        adds_(),
1132        removes_(),
1133        common_() {}
1134
1135  void PushLine(char edit, const char* line) {
1136    switch (edit) {
1137      case ' ':
1138        ++common_;
1139        FlushEdits();
1140        hunk_.push_back(std::make_pair(' ', line));
1141        break;
1142      case '-':
1143        ++removes_;
1144        hunk_removes_.push_back(std::make_pair('-', line));
1145        break;
1146      case '+':
1147        ++adds_;
1148        hunk_adds_.push_back(std::make_pair('+', line));
1149        break;
1150    }
1151  }
1152
1153  void PrintTo(std::ostream* os) {
1154    PrintHeader(os);
1155    FlushEdits();
1156    for (std::list<std::pair<char, const char*> >::const_iterator it =
1157             hunk_.begin();
1158         it != hunk_.end(); ++it) {
1159      *os << it->first << it->second << "\n";
1160    }
1161  }
1162
1163  bool has_edits() const { return adds_ || removes_; }
1164
1165 private:
1166  void FlushEdits() {
1167    hunk_.splice(hunk_.end(), hunk_removes_);
1168    hunk_.splice(hunk_.end(), hunk_adds_);
1169  }
1170
1171  // Print a unified diff header for one hunk.
1172  // The format is
1173  //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1174  // where the left/right parts are ommitted if unnecessary.
1175  void PrintHeader(std::ostream* ss) const {
1176    *ss << "@@ ";
1177    if (removes_) {
1178      *ss << "-" << left_start_ << "," << (removes_ + common_);
1179    }
1180    if (removes_ && adds_) {
1181      *ss << " ";
1182    }
1183    if (adds_) {
1184      *ss << "+" << right_start_ << "," << (adds_ + common_);
1185    }
1186    *ss << " @@\n";
1187  }
1188
1189  size_t left_start_, right_start_;
1190  size_t adds_, removes_, common_;
1191  std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1192};
1193
1194}  // namespace
1195
1196// Create a list of diff hunks in Unified diff format.
1197// Each hunk has a header generated by PrintHeader above plus a body with
1198// lines prefixed with ' ' for no change, '-' for deletion and '+' for
1199// addition.
1200// 'context' represents the desired unchanged prefix/suffix around the diff.
1201// If two hunks are close enough that their contexts overlap, then they are
1202// joined into one hunk.
1203std::string CreateUnifiedDiff(const std::vector<std::string>& left,
1204                              const std::vector<std::string>& right,
1205                              size_t context) {
1206  const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
1207
1208  size_t l_i = 0, r_i = 0, edit_i = 0;
1209  std::stringstream ss;
1210  while (edit_i < edits.size()) {
1211    // Find first edit.
1212    while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1213      ++l_i;
1214      ++r_i;
1215      ++edit_i;
1216    }
1217
1218    // Find the first line to include in the hunk.
1219    const size_t prefix_context = std::min(l_i, context);
1220    Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1221    for (size_t i = prefix_context; i > 0; --i) {
1222      hunk.PushLine(' ', left[l_i - i].c_str());
1223    }
1224
1225    // Iterate the edits until we found enough suffix for the hunk or the input
1226    // is over.
1227    size_t n_suffix = 0;
1228    for (; edit_i < edits.size(); ++edit_i) {
1229      if (n_suffix >= context) {
1230        // Continue only if the next hunk is very close.
1231        std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
1232        while (it != edits.end() && *it == kMatch) ++it;
1233        if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
1234          // There is no next edit or it is too far away.
1235          break;
1236        }
1237      }
1238
1239      EditType edit = edits[edit_i];
1240      // Reset count when a non match is found.
1241      n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1242
1243      if (edit == kMatch || edit == kRemove || edit == kReplace) {
1244        hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
1245      }
1246      if (edit == kAdd || edit == kReplace) {
1247        hunk.PushLine('+', right[r_i].c_str());
1248      }
1249
1250      // Advance indices, depending on edit type.
1251      l_i += edit != kAdd;
1252      r_i += edit != kRemove;
1253    }
1254
1255    if (!hunk.has_edits()) {
1256      // We are done. We don't want this hunk.
1257      break;
1258    }
1259
1260    hunk.PrintTo(&ss);
1261  }
1262  return ss.str();
1263}
1264
1265}  // namespace edit_distance
1266
1267namespace {
1268
1269// The string representation of the values received in EqFailure() are already
1270// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1271// characters the same.
1272std::vector<std::string> SplitEscapedString(const std::string& str) {
1273  std::vector<std::string> lines;
1274  size_t start = 0, end = str.size();
1275  if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
1276    ++start;
1277    --end;
1278  }
1279  bool escaped = false;
1280  for (size_t i = start; i + 1 < end; ++i) {
1281    if (escaped) {
1282      escaped = false;
1283      if (str[i] == 'n') {
1284        lines.push_back(str.substr(start, i - start - 1));
1285        start = i + 1;
1286      }
1287    } else {
1288      escaped = str[i] == '\\';
1289    }
1290  }
1291  lines.push_back(str.substr(start, end - start));
1292  return lines;
1293}
1294
1295}  // namespace
1296
1297// Constructs and returns the message for an equality assertion
1298// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1299//
1300// The first four parameters are the expressions used in the assertion
1301// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
1302// where foo is 5 and bar is 6, we have:
1303//
1304//   expected_expression: "foo"
1305//   actual_expression:   "bar"
1306//   expected_value:      "5"
1307//   actual_value:        "6"
1308//
1309// The ignoring_case parameter is true iff the assertion is a
1310// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
1311// be inserted into the message.
1312AssertionResult EqFailure(const char* expected_expression,
1313                          const char* actual_expression,
1314                          const std::string& expected_value,
1315                          const std::string& actual_value,
1316                          bool ignoring_case) {
1317  Message msg;
1318  msg << "Value of: " << actual_expression;
1319  if (actual_value != actual_expression) {
1320    msg << "\n  Actual: " << actual_value;
1321  }
1322
1323  msg << "\nExpected: " << expected_expression;
1324  if (ignoring_case) {
1325    msg << " (ignoring case)";
1326  }
1327  if (expected_value != expected_expression) {
1328    msg << "\nWhich is: " << expected_value;
1329  }
1330
1331  if (!expected_value.empty() && !actual_value.empty()) {
1332    const std::vector<std::string> expected_lines =
1333        SplitEscapedString(expected_value);
1334    const std::vector<std::string> actual_lines =
1335        SplitEscapedString(actual_value);
1336    if (expected_lines.size() > 1 || actual_lines.size() > 1) {
1337      msg << "\nWith diff:\n"
1338          << edit_distance::CreateUnifiedDiff(expected_lines, actual_lines);
1339    }
1340  }
1341
1342  return AssertionFailure() << msg;
1343}
1344
1345// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1346std::string GetBoolAssertionFailureMessage(
1347    const AssertionResult& assertion_result,
1348    const char* expression_text,
1349    const char* actual_predicate_value,
1350    const char* expected_predicate_value) {
1351  const char* actual_message = assertion_result.message();
1352  Message msg;
1353  msg << "Value of: " << expression_text
1354      << "\n  Actual: " << actual_predicate_value;
1355  if (actual_message[0] != '\0')
1356    msg << " (" << actual_message << ")";
1357  msg << "\nExpected: " << expected_predicate_value;
1358  return msg.GetString();
1359}
1360
1361// Helper function for implementing ASSERT_NEAR.
1362AssertionResult DoubleNearPredFormat(const char* expr1,
1363                                     const char* expr2,
1364                                     const char* abs_error_expr,
1365                                     double val1,
1366                                     double val2,
1367                                     double abs_error) {
1368  const double diff = fabs(val1 - val2);
1369  if (diff <= abs_error) return AssertionSuccess();
1370
1371  // TODO(wan): do not print the value of an expression if it's
1372  // already a literal.
1373  return AssertionFailure()
1374      << "The difference between " << expr1 << " and " << expr2
1375      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1376      << expr1 << " evaluates to " << val1 << ",\n"
1377      << expr2 << " evaluates to " << val2 << ", and\n"
1378      << abs_error_expr << " evaluates to " << abs_error << ".";
1379}
1380
1381
1382// Helper template for implementing FloatLE() and DoubleLE().
1383template <typename RawType>
1384AssertionResult FloatingPointLE(const char* expr1,
1385                                const char* expr2,
1386                                RawType val1,
1387                                RawType val2) {
1388  // Returns success if val1 is less than val2,
1389  if (val1 < val2) {
1390    return AssertionSuccess();
1391  }
1392
1393  // or if val1 is almost equal to val2.
1394  const FloatingPoint<RawType> lhs(val1), rhs(val2);
1395  if (lhs.AlmostEquals(rhs)) {
1396    return AssertionSuccess();
1397  }
1398
1399  // Note that the above two checks will both fail if either val1 or
1400  // val2 is NaN, as the IEEE floating-point standard requires that
1401  // any predicate involving a NaN must return false.
1402
1403  ::std::stringstream val1_ss;
1404  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1405          << val1;
1406
1407  ::std::stringstream val2_ss;
1408  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1409          << val2;
1410
1411  return AssertionFailure()
1412      << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1413      << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
1414      << StringStreamToString(&val2_ss);
1415}
1416
1417}  // namespace internal
1418
1419// Asserts that val1 is less than, or almost equal to, val2.  Fails
1420// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1421AssertionResult FloatLE(const char* expr1, const char* expr2,
1422                        float val1, float val2) {
1423  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1424}
1425
1426// Asserts that val1 is less than, or almost equal to, val2.  Fails
1427// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1428AssertionResult DoubleLE(const char* expr1, const char* expr2,
1429                         double val1, double val2) {
1430  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1431}
1432
1433namespace internal {
1434
1435// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1436// arguments.
1437AssertionResult CmpHelperEQ(const char* expected_expression,
1438                            const char* actual_expression,
1439                            BiggestInt expected,
1440                            BiggestInt actual) {
1441  if (expected == actual) {
1442    return AssertionSuccess();
1443  }
1444
1445  return EqFailure(expected_expression,
1446                   actual_expression,
1447                   FormatForComparisonFailureMessage(expected, actual),
1448                   FormatForComparisonFailureMessage(actual, expected),
1449                   false);
1450}
1451
1452// A macro for implementing the helper functions needed to implement
1453// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
1454// just to avoid copy-and-paste of similar code.
1455#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1456AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1457                                   BiggestInt val1, BiggestInt val2) {\
1458  if (val1 op val2) {\
1459    return AssertionSuccess();\
1460  } else {\
1461    return AssertionFailure() \
1462        << "Expected: (" << expr1 << ") " #op " (" << expr2\
1463        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1464        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1465  }\
1466}
1467
1468// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1469// enum arguments.
1470GTEST_IMPL_CMP_HELPER_(NE, !=)
1471// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1472// enum arguments.
1473GTEST_IMPL_CMP_HELPER_(LE, <=)
1474// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1475// enum arguments.
1476GTEST_IMPL_CMP_HELPER_(LT, < )
1477// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1478// enum arguments.
1479GTEST_IMPL_CMP_HELPER_(GE, >=)
1480// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1481// enum arguments.
1482GTEST_IMPL_CMP_HELPER_(GT, > )
1483
1484#undef GTEST_IMPL_CMP_HELPER_
1485
1486// The helper function for {ASSERT|EXPECT}_STREQ.
1487AssertionResult CmpHelperSTREQ(const char* expected_expression,
1488                               const char* actual_expression,
1489                               const char* expected,
1490                               const char* actual) {
1491  if (String::CStringEquals(expected, actual)) {
1492    return AssertionSuccess();
1493  }
1494
1495  return EqFailure(expected_expression,
1496                   actual_expression,
1497                   PrintToString(expected),
1498                   PrintToString(actual),
1499                   false);
1500}
1501
1502// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1503AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1504                                   const char* actual_expression,
1505                                   const char* expected,
1506                                   const char* actual) {
1507  if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1508    return AssertionSuccess();
1509  }
1510
1511  return EqFailure(expected_expression,
1512                   actual_expression,
1513                   PrintToString(expected),
1514                   PrintToString(actual),
1515                   true);
1516}
1517
1518// The helper function for {ASSERT|EXPECT}_STRNE.
1519AssertionResult CmpHelperSTRNE(const char* s1_expression,
1520                               const char* s2_expression,
1521                               const char* s1,
1522                               const char* s2) {
1523  if (!String::CStringEquals(s1, s2)) {
1524    return AssertionSuccess();
1525  } else {
1526    return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1527                              << s2_expression << "), actual: \""
1528                              << s1 << "\" vs \"" << s2 << "\"";
1529  }
1530}
1531
1532// The helper function for {ASSERT|EXPECT}_STRCASENE.
1533AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1534                                   const char* s2_expression,
1535                                   const char* s1,
1536                                   const char* s2) {
1537  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1538    return AssertionSuccess();
1539  } else {
1540    return AssertionFailure()
1541        << "Expected: (" << s1_expression << ") != ("
1542        << s2_expression << ") (ignoring case), actual: \""
1543        << s1 << "\" vs \"" << s2 << "\"";
1544  }
1545}
1546
1547}  // namespace internal
1548
1549namespace {
1550
1551// Helper functions for implementing IsSubString() and IsNotSubstring().
1552
1553// This group of overloaded functions return true iff needle is a
1554// substring of haystack.  NULL is considered a substring of itself
1555// only.
1556
1557bool IsSubstringPred(const char* needle, const char* haystack) {
1558  if (needle == NULL || haystack == NULL)
1559    return needle == haystack;
1560
1561  return strstr(haystack, needle) != NULL;
1562}
1563
1564bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1565  if (needle == NULL || haystack == NULL)
1566    return needle == haystack;
1567
1568  return wcsstr(haystack, needle) != NULL;
1569}
1570
1571// StringType here can be either ::std::string or ::std::wstring.
1572template <typename StringType>
1573bool IsSubstringPred(const StringType& needle,
1574                     const StringType& haystack) {
1575  return haystack.find(needle) != StringType::npos;
1576}
1577
1578// This function implements either IsSubstring() or IsNotSubstring(),
1579// depending on the value of the expected_to_be_substring parameter.
1580// StringType here can be const char*, const wchar_t*, ::std::string,
1581// or ::std::wstring.
1582template <typename StringType>
1583AssertionResult IsSubstringImpl(
1584    bool expected_to_be_substring,
1585    const char* needle_expr, const char* haystack_expr,
1586    const StringType& needle, const StringType& haystack) {
1587  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1588    return AssertionSuccess();
1589
1590  const bool is_wide_string = sizeof(needle[0]) > 1;
1591  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1592  return AssertionFailure()
1593      << "Value of: " << needle_expr << "\n"
1594      << "  Actual: " << begin_string_quote << needle << "\"\n"
1595      << "Expected: " << (expected_to_be_substring ? "" : "not ")
1596      << "a substring of " << haystack_expr << "\n"
1597      << "Which is: " << begin_string_quote << haystack << "\"";
1598}
1599
1600}  // namespace
1601
1602// IsSubstring() and IsNotSubstring() check whether needle is a
1603// substring of haystack (NULL is considered a substring of itself
1604// only), and return an appropriate error message when they fail.
1605
1606AssertionResult IsSubstring(
1607    const char* needle_expr, const char* haystack_expr,
1608    const char* needle, const char* haystack) {
1609  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1610}
1611
1612AssertionResult IsSubstring(
1613    const char* needle_expr, const char* haystack_expr,
1614    const wchar_t* needle, const wchar_t* haystack) {
1615  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1616}
1617
1618AssertionResult IsNotSubstring(
1619    const char* needle_expr, const char* haystack_expr,
1620    const char* needle, const char* haystack) {
1621  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1622}
1623
1624AssertionResult IsNotSubstring(
1625    const char* needle_expr, const char* haystack_expr,
1626    const wchar_t* needle, const wchar_t* haystack) {
1627  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1628}
1629
1630AssertionResult IsSubstring(
1631    const char* needle_expr, const char* haystack_expr,
1632    const ::std::string& needle, const ::std::string& haystack) {
1633  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1634}
1635
1636AssertionResult IsNotSubstring(
1637    const char* needle_expr, const char* haystack_expr,
1638    const ::std::string& needle, const ::std::string& haystack) {
1639  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1640}
1641
1642#if GTEST_HAS_STD_WSTRING
1643AssertionResult IsSubstring(
1644    const char* needle_expr, const char* haystack_expr,
1645    const ::std::wstring& needle, const ::std::wstring& haystack) {
1646  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1647}
1648
1649AssertionResult IsNotSubstring(
1650    const char* needle_expr, const char* haystack_expr,
1651    const ::std::wstring& needle, const ::std::wstring& haystack) {
1652  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1653}
1654#endif  // GTEST_HAS_STD_WSTRING
1655
1656namespace internal {
1657
1658#if GTEST_OS_WINDOWS
1659
1660namespace {
1661
1662// Helper function for IsHRESULT{SuccessFailure} predicates
1663AssertionResult HRESULTFailureHelper(const char* expr,
1664                                     const char* expected,
1665                                     long hr) {  // NOLINT
1666# if GTEST_OS_WINDOWS_MOBILE
1667
1668  // Windows CE doesn't support FormatMessage.
1669  const char error_text[] = "";
1670
1671# else
1672
1673  // Looks up the human-readable system message for the HRESULT code
1674  // and since we're not passing any params to FormatMessage, we don't
1675  // want inserts expanded.
1676  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1677                       FORMAT_MESSAGE_IGNORE_INSERTS;
1678  const DWORD kBufSize = 4096;
1679  // Gets the system's human readable message string for this HRESULT.
1680  char error_text[kBufSize] = { '\0' };
1681  DWORD message_length = ::FormatMessageA(kFlags,
1682                                          0,  // no source, we're asking system
1683                                          hr,  // the error
1684                                          0,  // no line width restrictions
1685                                          error_text,  // output buffer
1686                                          kBufSize,  // buf size
1687                                          NULL);  // no arguments for inserts
1688  // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1689  for (; message_length && IsSpace(error_text[message_length - 1]);
1690          --message_length) {
1691    error_text[message_length - 1] = '\0';
1692  }
1693
1694# endif  // GTEST_OS_WINDOWS_MOBILE
1695
1696  const std::string error_hex("0x" + String::FormatHexInt(hr));
1697  return ::testing::AssertionFailure()
1698      << "Expected: " << expr << " " << expected << ".\n"
1699      << "  Actual: " << error_hex << " " << error_text << "\n";
1700}
1701
1702}  // namespace
1703
1704AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
1705  if (SUCCEEDED(hr)) {
1706    return AssertionSuccess();
1707  }
1708  return HRESULTFailureHelper(expr, "succeeds", hr);
1709}
1710
1711AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
1712  if (FAILED(hr)) {
1713    return AssertionSuccess();
1714  }
1715  return HRESULTFailureHelper(expr, "fails", hr);
1716}
1717
1718#endif  // GTEST_OS_WINDOWS
1719
1720// Utility functions for encoding Unicode text (wide strings) in
1721// UTF-8.
1722
1723// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1724// like this:
1725//
1726// Code-point length   Encoding
1727//   0 -  7 bits       0xxxxxxx
1728//   8 - 11 bits       110xxxxx 10xxxxxx
1729//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
1730//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1731
1732// The maximum code-point a one-byte UTF-8 sequence can represent.
1733const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
1734
1735// The maximum code-point a two-byte UTF-8 sequence can represent.
1736const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1737
1738// The maximum code-point a three-byte UTF-8 sequence can represent.
1739const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1740
1741// The maximum code-point a four-byte UTF-8 sequence can represent.
1742const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1743
1744// Chops off the n lowest bits from a bit pattern.  Returns the n
1745// lowest bits.  As a side effect, the original bit pattern will be
1746// shifted to the right by n bits.
1747inline UInt32 ChopLowBits(UInt32* bits, int n) {
1748  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1749  *bits >>= n;
1750  return low_bits;
1751}
1752
1753// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1754// code_point parameter is of type UInt32 because wchar_t may not be
1755// wide enough to contain a code point.
1756// If the code_point is not a valid Unicode code point
1757// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1758// to "(Invalid Unicode 0xXXXXXXXX)".
1759std::string CodePointToUtf8(UInt32 code_point) {
1760  if (code_point > kMaxCodePoint4) {
1761    return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
1762  }
1763
1764  char str[5];  // Big enough for the largest valid code point.
1765  if (code_point <= kMaxCodePoint1) {
1766    str[1] = '\0';
1767    str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
1768  } else if (code_point <= kMaxCodePoint2) {
1769    str[2] = '\0';
1770    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1771    str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
1772  } else if (code_point <= kMaxCodePoint3) {
1773    str[3] = '\0';
1774    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1775    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1776    str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
1777  } else {  // code_point <= kMaxCodePoint4
1778    str[4] = '\0';
1779    str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1780    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1781    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1782    str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
1783  }
1784  return str;
1785}
1786
1787// The following two functions only make sense if the the system
1788// uses UTF-16 for wide string encoding. All supported systems
1789// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1790
1791// Determines if the arguments constitute UTF-16 surrogate pair
1792// and thus should be combined into a single Unicode code point
1793// using CreateCodePointFromUtf16SurrogatePair.
1794inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1795  return sizeof(wchar_t) == 2 &&
1796      (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1797}
1798
1799// Creates a Unicode code point from UTF16 surrogate pair.
1800inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1801                                                    wchar_t second) {
1802  const UInt32 mask = (1 << 10) - 1;
1803  return (sizeof(wchar_t) == 2) ?
1804      (((first & mask) << 10) | (second & mask)) + 0x10000 :
1805      // This function should not be called when the condition is
1806      // false, but we provide a sensible default in case it is.
1807      static_cast<UInt32>(first);
1808}
1809
1810// Converts a wide string to a narrow string in UTF-8 encoding.
1811// The wide string is assumed to have the following encoding:
1812//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1813//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1814// Parameter str points to a null-terminated wide string.
1815// Parameter num_chars may additionally limit the number
1816// of wchar_t characters processed. -1 is used when the entire string
1817// should be processed.
1818// If the string contains code points that are not valid Unicode code points
1819// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1820// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1821// and contains invalid UTF-16 surrogate pairs, values in those pairs
1822// will be encoded as individual Unicode characters from Basic Normal Plane.
1823std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
1824  if (num_chars == -1)
1825    num_chars = static_cast<int>(wcslen(str));
1826
1827  ::std::stringstream stream;
1828  for (int i = 0; i < num_chars; ++i) {
1829    UInt32 unicode_code_point;
1830
1831    if (str[i] == L'\0') {
1832      break;
1833    } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1834      unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1835                                                                 str[i + 1]);
1836      i++;
1837    } else {
1838      unicode_code_point = static_cast<UInt32>(str[i]);
1839    }
1840
1841    stream << CodePointToUtf8(unicode_code_point);
1842  }
1843  return StringStreamToString(&stream);
1844}
1845
1846// Converts a wide C string to an std::string using the UTF-8 encoding.
1847// NULL will be converted to "(null)".
1848std::string String::ShowWideCString(const wchar_t * wide_c_str) {
1849  if (wide_c_str == NULL)  return "(null)";
1850
1851  return internal::WideStringToUtf8(wide_c_str, -1);
1852}
1853
1854// Compares two wide C strings.  Returns true iff they have the same
1855// content.
1856//
1857// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
1858// C string is considered different to any non-NULL C string,
1859// including the empty string.
1860bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1861  if (lhs == NULL) return rhs == NULL;
1862
1863  if (rhs == NULL) return false;
1864
1865  return wcscmp(lhs, rhs) == 0;
1866}
1867
1868// Helper function for *_STREQ on wide strings.
1869AssertionResult CmpHelperSTREQ(const char* expected_expression,
1870                               const char* actual_expression,
1871                               const wchar_t* expected,
1872                               const wchar_t* actual) {
1873  if (String::WideCStringEquals(expected, actual)) {
1874    return AssertionSuccess();
1875  }
1876
1877  return EqFailure(expected_expression,
1878                   actual_expression,
1879                   PrintToString(expected),
1880                   PrintToString(actual),
1881                   false);
1882}
1883
1884// Helper function for *_STRNE on wide strings.
1885AssertionResult CmpHelperSTRNE(const char* s1_expression,
1886                               const char* s2_expression,
1887                               const wchar_t* s1,
1888                               const wchar_t* s2) {
1889  if (!String::WideCStringEquals(s1, s2)) {
1890    return AssertionSuccess();
1891  }
1892
1893  return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1894                            << s2_expression << "), actual: "
1895                            << PrintToString(s1)
1896                            << " vs " << PrintToString(s2);
1897}
1898
1899// Compares two C strings, ignoring case.  Returns true iff they have
1900// the same content.
1901//
1902// Unlike strcasecmp(), this function can handle NULL argument(s).  A
1903// NULL C string is considered different to any non-NULL C string,
1904// including the empty string.
1905bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1906  if (lhs == NULL)
1907    return rhs == NULL;
1908  if (rhs == NULL)
1909    return false;
1910  return posix::StrCaseCmp(lhs, rhs) == 0;
1911}
1912
1913  // Compares two wide C strings, ignoring case.  Returns true iff they
1914  // have the same content.
1915  //
1916  // Unlike wcscasecmp(), this function can handle NULL argument(s).
1917  // A NULL C string is considered different to any non-NULL wide C string,
1918  // including the empty string.
1919  // NB: The implementations on different platforms slightly differ.
1920  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1921  // environment variable. On GNU platform this method uses wcscasecmp
1922  // which compares according to LC_CTYPE category of the current locale.
1923  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1924  // current locale.
1925bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1926                                              const wchar_t* rhs) {
1927  if (lhs == NULL) return rhs == NULL;
1928
1929  if (rhs == NULL) return false;
1930
1931#if GTEST_OS_WINDOWS
1932  return _wcsicmp(lhs, rhs) == 0;
1933#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
1934  return wcscasecmp(lhs, rhs) == 0;
1935#else
1936  // Android, Mac OS X and Cygwin don't define wcscasecmp.
1937  // Other unknown OSes may not define it either.
1938  wint_t left, right;
1939  do {
1940    left = towlower(*lhs++);
1941    right = towlower(*rhs++);
1942  } while (left && left == right);
1943  return left == right;
1944#endif  // OS selector
1945}
1946
1947// Returns true iff str ends with the given suffix, ignoring case.
1948// Any string is considered to end with an empty suffix.
1949bool String::EndsWithCaseInsensitive(
1950    const std::string& str, const std::string& suffix) {
1951  const size_t str_len = str.length();
1952  const size_t suffix_len = suffix.length();
1953  return (str_len >= suffix_len) &&
1954         CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
1955                                      suffix.c_str());
1956}
1957
1958// Formats an int value as "%02d".
1959std::string String::FormatIntWidth2(int value) {
1960  std::stringstream ss;
1961  ss << std::setfill('0') << std::setw(2) << value;
1962  return ss.str();
1963}
1964
1965// Formats an int value as "%X".
1966std::string String::FormatHexInt(int value) {
1967  std::stringstream ss;
1968  ss << std::hex << std::uppercase << value;
1969  return ss.str();
1970}
1971
1972// Formats a byte as "%02X".
1973std::string String::FormatByte(unsigned char value) {
1974  std::stringstream ss;
1975  ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
1976     << static_cast<unsigned int>(value);
1977  return ss.str();
1978}
1979
1980// Converts the buffer in a stringstream to an std::string, converting NUL
1981// bytes to "\\0" along the way.
1982std::string StringStreamToString(::std::stringstream* ss) {
1983  const ::std::string& str = ss->str();
1984  const char* const start = str.c_str();
1985  const char* const end = start + str.length();
1986
1987  std::string result;
1988  result.reserve(2 * (end - start));
1989  for (const char* ch = start; ch != end; ++ch) {
1990    if (*ch == '\0') {
1991      result += "\\0";  // Replaces NUL with "\\0";
1992    } else {
1993      result += *ch;
1994    }
1995  }
1996
1997  return result;
1998}
1999
2000// Appends the user-supplied message to the Google-Test-generated message.
2001std::string AppendUserMessage(const std::string& gtest_msg,
2002                              const Message& user_msg) {
2003  // Appends the user message if it's non-empty.
2004  const std::string user_msg_string = user_msg.GetString();
2005  if (user_msg_string.empty()) {
2006    return gtest_msg;
2007  }
2008
2009  return gtest_msg + "\n" + user_msg_string;
2010}
2011
2012}  // namespace internal
2013
2014// class TestResult
2015
2016// Creates an empty TestResult.
2017TestResult::TestResult()
2018    : death_test_count_(0),
2019      elapsed_time_(0) {
2020}
2021
2022// D'tor.
2023TestResult::~TestResult() {
2024}
2025
2026// Returns the i-th test part result among all the results. i can
2027// range from 0 to total_part_count() - 1. If i is not in that range,
2028// aborts the program.
2029const TestPartResult& TestResult::GetTestPartResult(int i) const {
2030  if (i < 0 || i >= total_part_count())
2031    internal::posix::Abort();
2032  return test_part_results_.at(i);
2033}
2034
2035// Returns the i-th test property. i can range from 0 to
2036// test_property_count() - 1. If i is not in that range, aborts the
2037// program.
2038const TestProperty& TestResult::GetTestProperty(int i) const {
2039  if (i < 0 || i >= test_property_count())
2040    internal::posix::Abort();
2041  return test_properties_.at(i);
2042}
2043
2044// Clears the test part results.
2045void TestResult::ClearTestPartResults() {
2046  test_part_results_.clear();
2047}
2048
2049// Adds a test part result to the list.
2050void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
2051  test_part_results_.push_back(test_part_result);
2052}
2053
2054// Adds a test property to the list. If a property with the same key as the
2055// supplied property is already represented, the value of this test_property
2056// replaces the old value for that key.
2057void TestResult::RecordProperty(const std::string& xml_element,
2058                                const TestProperty& test_property) {
2059  if (!ValidateTestProperty(xml_element, test_property)) {
2060    return;
2061  }
2062  internal::MutexLock lock(&test_properites_mutex_);
2063  const std::vector<TestProperty>::iterator property_with_matching_key =
2064      std::find_if(test_properties_.begin(), test_properties_.end(),
2065                   internal::TestPropertyKeyIs(test_property.key()));
2066  if (property_with_matching_key == test_properties_.end()) {
2067    test_properties_.push_back(test_property);
2068    return;
2069  }
2070  property_with_matching_key->SetValue(test_property.value());
2071}
2072
2073// The list of reserved attributes used in the <testsuites> element of XML
2074// output.
2075static const char* const kReservedTestSuitesAttributes[] = {
2076  "disabled",
2077  "errors",
2078  "failures",
2079  "name",
2080  "random_seed",
2081  "tests",
2082  "time",
2083  "timestamp"
2084};
2085
2086// The list of reserved attributes used in the <testsuite> element of XML
2087// output.
2088static const char* const kReservedTestSuiteAttributes[] = {
2089  "disabled",
2090  "errors",
2091  "failures",
2092  "name",
2093  "tests",
2094  "time"
2095};
2096
2097// The list of reserved attributes used in the <testcase> element of XML output.
2098static const char* const kReservedTestCaseAttributes[] = {
2099  "classname",
2100  "name",
2101  "status",
2102  "time",
2103  "type_param",
2104  "value_param"
2105};
2106
2107template <int kSize>
2108std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
2109  return std::vector<std::string>(array, array + kSize);
2110}
2111
2112static std::vector<std::string> GetReservedAttributesForElement(
2113    const std::string& xml_element) {
2114  if (xml_element == "testsuites") {
2115    return ArrayAsVector(kReservedTestSuitesAttributes);
2116  } else if (xml_element == "testsuite") {
2117    return ArrayAsVector(kReservedTestSuiteAttributes);
2118  } else if (xml_element == "testcase") {
2119    return ArrayAsVector(kReservedTestCaseAttributes);
2120  } else {
2121    GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2122  }
2123  // This code is unreachable but some compilers may not realizes that.
2124  return std::vector<std::string>();
2125}
2126
2127static std::string FormatWordList(const std::vector<std::string>& words) {
2128  Message word_list;
2129  for (size_t i = 0; i < words.size(); ++i) {
2130    if (i > 0 && words.size() > 2) {
2131      word_list << ", ";
2132    }
2133    if (i == words.size() - 1) {
2134      word_list << "and ";
2135    }
2136    word_list << "'" << words[i] << "'";
2137  }
2138  return word_list.GetString();
2139}
2140
2141bool ValidateTestPropertyName(const std::string& property_name,
2142                              const std::vector<std::string>& reserved_names) {
2143  if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2144          reserved_names.end()) {
2145    ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
2146                  << " (" << FormatWordList(reserved_names)
2147                  << " are reserved by " << GTEST_NAME_ << ")";
2148    return false;
2149  }
2150  return true;
2151}
2152
2153// Adds a failure if the key is a reserved attribute of the element named
2154// xml_element.  Returns true if the property is valid.
2155bool TestResult::ValidateTestProperty(const std::string& xml_element,
2156                                      const TestProperty& test_property) {
2157  return ValidateTestPropertyName(test_property.key(),
2158                                  GetReservedAttributesForElement(xml_element));
2159}
2160
2161// Clears the object.
2162void TestResult::Clear() {
2163  test_part_results_.clear();
2164  test_properties_.clear();
2165  death_test_count_ = 0;
2166  elapsed_time_ = 0;
2167}
2168
2169// Returns true iff the test failed.
2170bool TestResult::Failed() const {
2171  for (int i = 0; i < total_part_count(); ++i) {
2172    if (GetTestPartResult(i).failed())
2173      return true;
2174  }
2175  return false;
2176}
2177
2178// Returns true iff the test part fatally failed.
2179static bool TestPartFatallyFailed(const TestPartResult& result) {
2180  return result.fatally_failed();
2181}
2182
2183// Returns true iff the test fatally failed.
2184bool TestResult::HasFatalFailure() const {
2185  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
2186}
2187
2188// Returns true iff the test part non-fatally failed.
2189static bool TestPartNonfatallyFailed(const TestPartResult& result) {
2190  return result.nonfatally_failed();
2191}
2192
2193// Returns true iff the test has a non-fatal failure.
2194bool TestResult::HasNonfatalFailure() const {
2195  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
2196}
2197
2198// Gets the number of all test parts.  This is the sum of the number
2199// of successful test parts and the number of failed test parts.
2200int TestResult::total_part_count() const {
2201  return static_cast<int>(test_part_results_.size());
2202}
2203
2204// Returns the number of the test properties.
2205int TestResult::test_property_count() const {
2206  return static_cast<int>(test_properties_.size());
2207}
2208
2209// class Test
2210
2211// Creates a Test object.
2212
2213// The c'tor saves the states of all flags.
2214Test::Test()
2215    : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
2216}
2217
2218// The d'tor restores the states of all flags.  The actual work is
2219// done by the d'tor of the gtest_flag_saver_ field, and thus not
2220// visible here.
2221Test::~Test() {
2222}
2223
2224// Sets up the test fixture.
2225//
2226// A sub-class may override this.
2227void Test::SetUp() {
2228}
2229
2230// Tears down the test fixture.
2231//
2232// A sub-class may override this.
2233void Test::TearDown() {
2234}
2235
2236// Allows user supplied key value pairs to be recorded for later output.
2237void Test::RecordProperty(const std::string& key, const std::string& value) {
2238  UnitTest::GetInstance()->RecordProperty(key, value);
2239}
2240
2241// Allows user supplied key value pairs to be recorded for later output.
2242void Test::RecordProperty(const std::string& key, int value) {
2243  Message value_message;
2244  value_message << value;
2245  RecordProperty(key, value_message.GetString().c_str());
2246}
2247
2248namespace internal {
2249
2250void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
2251                                    const std::string& message) {
2252  // This function is a friend of UnitTest and as such has access to
2253  // AddTestPartResult.
2254  UnitTest::GetInstance()->AddTestPartResult(
2255      result_type,
2256      NULL,  // No info about the source file where the exception occurred.
2257      -1,    // We have no info on which line caused the exception.
2258      message,
2259      "");   // No stack trace, either.
2260}
2261
2262}  // namespace internal
2263
2264// Google Test requires all tests in the same test case to use the same test
2265// fixture class.  This function checks if the current test has the
2266// same fixture class as the first test in the current test case.  If
2267// yes, it returns true; otherwise it generates a Google Test failure and
2268// returns false.
2269bool Test::HasSameFixtureClass() {
2270  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2271  const TestCase* const test_case = impl->current_test_case();
2272
2273  // Info about the first test in the current test case.
2274  const TestInfo* const first_test_info = test_case->test_info_list()[0];
2275  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2276  const char* const first_test_name = first_test_info->name();
2277
2278  // Info about the current test.
2279  const TestInfo* const this_test_info = impl->current_test_info();
2280  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2281  const char* const this_test_name = this_test_info->name();
2282
2283  if (this_fixture_id != first_fixture_id) {
2284    // Is the first test defined using TEST?
2285    const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2286    // Is this test defined using TEST?
2287    const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2288
2289    if (first_is_TEST || this_is_TEST) {
2290      // Both TEST and TEST_F appear in same test case, which is incorrect.
2291      // Tell the user how to fix this.
2292
2293      // Gets the name of the TEST and the name of the TEST_F.  Note
2294      // that first_is_TEST and this_is_TEST cannot both be true, as
2295      // the fixture IDs are different for the two tests.
2296      const char* const TEST_name =
2297          first_is_TEST ? first_test_name : this_test_name;
2298      const char* const TEST_F_name =
2299          first_is_TEST ? this_test_name : first_test_name;
2300
2301      ADD_FAILURE()
2302          << "All tests in the same test case must use the same test fixture\n"
2303          << "class, so mixing TEST_F and TEST in the same test case is\n"
2304          << "illegal.  In test case " << this_test_info->test_case_name()
2305          << ",\n"
2306          << "test " << TEST_F_name << " is defined using TEST_F but\n"
2307          << "test " << TEST_name << " is defined using TEST.  You probably\n"
2308          << "want to change the TEST to TEST_F or move it to another test\n"
2309          << "case.";
2310    } else {
2311      // Two fixture classes with the same name appear in two different
2312      // namespaces, which is not allowed. Tell the user how to fix this.
2313      ADD_FAILURE()
2314          << "All tests in the same test case must use the same test fixture\n"
2315          << "class.  However, in test case "
2316          << this_test_info->test_case_name() << ",\n"
2317          << "you defined test " << first_test_name
2318          << " and test " << this_test_name << "\n"
2319          << "using two different test fixture classes.  This can happen if\n"
2320          << "the two classes are from different namespaces or translation\n"
2321          << "units and have the same name.  You should probably rename one\n"
2322          << "of the classes to put the tests into different test cases.";
2323    }
2324    return false;
2325  }
2326
2327  return true;
2328}
2329
2330#if GTEST_HAS_SEH
2331
2332// Adds an "exception thrown" fatal failure to the current test.  This
2333// function returns its result via an output parameter pointer because VC++
2334// prohibits creation of objects with destructors on stack in functions
2335// using __try (see error C2712).
2336static std::string* FormatSehExceptionMessage(DWORD exception_code,
2337                                              const char* location) {
2338  Message message;
2339  message << "SEH exception with code 0x" << std::setbase(16) <<
2340    exception_code << std::setbase(10) << " thrown in " << location << ".";
2341
2342  return new std::string(message.GetString());
2343}
2344
2345#endif  // GTEST_HAS_SEH
2346
2347namespace internal {
2348
2349#if GTEST_HAS_EXCEPTIONS
2350
2351// Adds an "exception thrown" fatal failure to the current test.
2352static std::string FormatCxxExceptionMessage(const char* description,
2353                                             const char* location) {
2354  Message message;
2355  if (description != NULL) {
2356    message << "C++ exception with description \"" << description << "\"";
2357  } else {
2358    message << "Unknown C++ exception";
2359  }
2360  message << " thrown in " << location << ".";
2361
2362  return message.GetString();
2363}
2364
2365static std::string PrintTestPartResultToString(
2366    const TestPartResult& test_part_result);
2367
2368GoogleTestFailureException::GoogleTestFailureException(
2369    const TestPartResult& failure)
2370    : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2371
2372#endif  // GTEST_HAS_EXCEPTIONS
2373
2374// We put these helper functions in the internal namespace as IBM's xlC
2375// compiler rejects the code if they were declared static.
2376
2377// Runs the given method and handles SEH exceptions it throws, when
2378// SEH is supported; returns the 0-value for type Result in case of an
2379// SEH exception.  (Microsoft compilers cannot handle SEH and C++
2380// exceptions in the same function.  Therefore, we provide a separate
2381// wrapper function for handling SEH exceptions.)
2382template <class T, typename Result>
2383Result HandleSehExceptionsInMethodIfSupported(
2384    T* object, Result (T::*method)(), const char* location) {
2385#if GTEST_HAS_SEH
2386  __try {
2387    return (object->*method)();
2388  } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
2389      GetExceptionCode())) {
2390    // We create the exception message on the heap because VC++ prohibits
2391    // creation of objects with destructors on stack in functions using __try
2392    // (see error C2712).
2393    std::string* exception_message = FormatSehExceptionMessage(
2394        GetExceptionCode(), location);
2395    internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
2396                                             *exception_message);
2397    delete exception_message;
2398    return static_cast<Result>(0);
2399  }
2400#else
2401  (void)location;
2402  return (object->*method)();
2403#endif  // GTEST_HAS_SEH
2404}
2405
2406// Runs the given method and catches and reports C++ and/or SEH-style
2407// exceptions, if they are supported; returns the 0-value for type
2408// Result in case of an SEH exception.
2409template <class T, typename Result>
2410Result HandleExceptionsInMethodIfSupported(
2411    T* object, Result (T::*method)(), const char* location) {
2412  // NOTE: The user code can affect the way in which Google Test handles
2413  // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2414  // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2415  // after the exception is caught and either report or re-throw the
2416  // exception based on the flag's value:
2417  //
2418  // try {
2419  //   // Perform the test method.
2420  // } catch (...) {
2421  //   if (GTEST_FLAG(catch_exceptions))
2422  //     // Report the exception as failure.
2423  //   else
2424  //     throw;  // Re-throws the original exception.
2425  // }
2426  //
2427  // However, the purpose of this flag is to allow the program to drop into
2428  // the debugger when the exception is thrown. On most platforms, once the
2429  // control enters the catch block, the exception origin information is
2430  // lost and the debugger will stop the program at the point of the
2431  // re-throw in this function -- instead of at the point of the original
2432  // throw statement in the code under test.  For this reason, we perform
2433  // the check early, sacrificing the ability to affect Google Test's
2434  // exception handling in the method where the exception is thrown.
2435  if (internal::GetUnitTestImpl()->catch_exceptions()) {
2436#if GTEST_HAS_EXCEPTIONS
2437    try {
2438      return HandleSehExceptionsInMethodIfSupported(object, method, location);
2439    } catch (const internal::GoogleTestFailureException&) {  // NOLINT
2440      // This exception type can only be thrown by a failed Google
2441      // Test assertion with the intention of letting another testing
2442      // framework catch it.  Therefore we just re-throw it.
2443      throw;
2444    } catch (const std::exception& e) {  // NOLINT
2445      internal::ReportFailureInUnknownLocation(
2446          TestPartResult::kFatalFailure,
2447          FormatCxxExceptionMessage(e.what(), location));
2448    } catch (...) {  // NOLINT
2449      internal::ReportFailureInUnknownLocation(
2450          TestPartResult::kFatalFailure,
2451          FormatCxxExceptionMessage(NULL, location));
2452    }
2453    return static_cast<Result>(0);
2454#else
2455    return HandleSehExceptionsInMethodIfSupported(object, method, location);
2456#endif  // GTEST_HAS_EXCEPTIONS
2457  } else {
2458    return (object->*method)();
2459  }
2460}
2461
2462}  // namespace internal
2463
2464// Runs the test and updates the test result.
2465void Test::Run() {
2466  if (!HasSameFixtureClass()) return;
2467
2468  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2469  impl->os_stack_trace_getter()->UponLeavingGTest();
2470  internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2471  // We will run the test only if SetUp() was successful.
2472  if (!HasFatalFailure()) {
2473    impl->os_stack_trace_getter()->UponLeavingGTest();
2474    internal::HandleExceptionsInMethodIfSupported(
2475        this, &Test::TestBody, "the test body");
2476  }
2477
2478  // However, we want to clean up as much as possible.  Hence we will
2479  // always call TearDown(), even if SetUp() or the test body has
2480  // failed.
2481  impl->os_stack_trace_getter()->UponLeavingGTest();
2482  internal::HandleExceptionsInMethodIfSupported(
2483      this, &Test::TearDown, "TearDown()");
2484}
2485
2486// Returns true iff the current test has a fatal failure.
2487bool Test::HasFatalFailure() {
2488  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2489}
2490
2491// Returns true iff the current test has a non-fatal failure.
2492bool Test::HasNonfatalFailure() {
2493  return internal::GetUnitTestImpl()->current_test_result()->
2494      HasNonfatalFailure();
2495}
2496
2497// class TestInfo
2498
2499// Constructs a TestInfo object. It assumes ownership of the test factory
2500// object.
2501TestInfo::TestInfo(const std::string& a_test_case_name,
2502                   const std::string& a_name,
2503                   const char* a_type_param,
2504                   const char* a_value_param,
2505                   internal::CodeLocation a_code_location,
2506                   internal::TypeId fixture_class_id,
2507                   internal::TestFactoryBase* factory)
2508    : test_case_name_(a_test_case_name),
2509      name_(a_name),
2510      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2511      value_param_(a_value_param ? new std::string(a_value_param) : NULL),
2512      location_(a_code_location),
2513      fixture_class_id_(fixture_class_id),
2514      should_run_(false),
2515      is_disabled_(false),
2516      matches_filter_(false),
2517      factory_(factory),
2518      result_() {}
2519
2520// Destructs a TestInfo object.
2521TestInfo::~TestInfo() { delete factory_; }
2522
2523namespace internal {
2524
2525// Creates a new TestInfo object and registers it with Google Test;
2526// returns the created object.
2527//
2528// Arguments:
2529//
2530//   test_case_name:   name of the test case
2531//   name:             name of the test
2532//   type_param:       the name of the test's type parameter, or NULL if
2533//                     this is not a typed or a type-parameterized test.
2534//   value_param:      text representation of the test's value parameter,
2535//                     or NULL if this is not a value-parameterized test.
2536//   code_location:    code location where the test is defined
2537//   fixture_class_id: ID of the test fixture class
2538//   set_up_tc:        pointer to the function that sets up the test case
2539//   tear_down_tc:     pointer to the function that tears down the test case
2540//   factory:          pointer to the factory that creates a test object.
2541//                     The newly created TestInfo instance will assume
2542//                     ownership of the factory object.
2543TestInfo* MakeAndRegisterTestInfo(
2544    const char* test_case_name,
2545    const char* name,
2546    const char* type_param,
2547    const char* value_param,
2548    CodeLocation code_location,
2549    TypeId fixture_class_id,
2550    SetUpTestCaseFunc set_up_tc,
2551    TearDownTestCaseFunc tear_down_tc,
2552    TestFactoryBase* factory) {
2553  TestInfo* const test_info =
2554      new TestInfo(test_case_name, name, type_param, value_param,
2555                   code_location, fixture_class_id, factory);
2556  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2557  return test_info;
2558}
2559
2560#if GTEST_HAS_PARAM_TEST
2561void ReportInvalidTestCaseType(const char* test_case_name,
2562                               CodeLocation code_location) {
2563  Message errors;
2564  errors
2565      << "Attempted redefinition of test case " << test_case_name << ".\n"
2566      << "All tests in the same test case must use the same test fixture\n"
2567      << "class.  However, in test case " << test_case_name << ", you tried\n"
2568      << "to define a test using a fixture class different from the one\n"
2569      << "used earlier. This can happen if the two fixture classes are\n"
2570      << "from different namespaces and have the same name. You should\n"
2571      << "probably rename one of the classes to put the tests into different\n"
2572      << "test cases.";
2573
2574  fprintf(stderr, "%s %s",
2575          FormatFileLocation(code_location.file.c_str(),
2576                             code_location.line).c_str(),
2577          errors.GetString().c_str());
2578}
2579#endif  // GTEST_HAS_PARAM_TEST
2580
2581}  // namespace internal
2582
2583namespace {
2584
2585// A predicate that checks the test name of a TestInfo against a known
2586// value.
2587//
2588// This is used for implementation of the TestCase class only.  We put
2589// it in the anonymous namespace to prevent polluting the outer
2590// namespace.
2591//
2592// TestNameIs is copyable.
2593class TestNameIs {
2594 public:
2595  // Constructor.
2596  //
2597  // TestNameIs has NO default constructor.
2598  explicit TestNameIs(const char* name)
2599      : name_(name) {}
2600
2601  // Returns true iff the test name of test_info matches name_.
2602  bool operator()(const TestInfo * test_info) const {
2603    return test_info && test_info->name() == name_;
2604  }
2605
2606 private:
2607  std::string name_;
2608};
2609
2610}  // namespace
2611
2612namespace internal {
2613
2614// This method expands all parameterized tests registered with macros TEST_P
2615// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2616// This will be done just once during the program runtime.
2617void UnitTestImpl::RegisterParameterizedTests() {
2618#if GTEST_HAS_PARAM_TEST
2619  if (!parameterized_tests_registered_) {
2620    parameterized_test_registry_.RegisterTests();
2621    parameterized_tests_registered_ = true;
2622  }
2623#endif
2624}
2625
2626}  // namespace internal
2627
2628// Creates the test object, runs it, records its result, and then
2629// deletes it.
2630void TestInfo::Run() {
2631  if (!should_run_) return;
2632
2633  // Tells UnitTest where to store test result.
2634  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2635  impl->set_current_test_info(this);
2636
2637  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2638
2639  // Notifies the unit test event listeners that a test is about to start.
2640  repeater->OnTestStart(*this);
2641
2642  const TimeInMillis start = internal::GetTimeInMillis();
2643
2644  impl->os_stack_trace_getter()->UponLeavingGTest();
2645
2646  // Creates the test object.
2647  Test* const test = internal::HandleExceptionsInMethodIfSupported(
2648      factory_, &internal::TestFactoryBase::CreateTest,
2649      "the test fixture's constructor");
2650
2651  // Runs the test only if the test object was created and its
2652  // constructor didn't generate a fatal failure.
2653  if ((test != NULL) && !Test::HasFatalFailure()) {
2654    // This doesn't throw as all user code that can throw are wrapped into
2655    // exception handling code.
2656    test->Run();
2657  }
2658
2659  // Deletes the test object.
2660  impl->os_stack_trace_getter()->UponLeavingGTest();
2661  internal::HandleExceptionsInMethodIfSupported(
2662      test, &Test::DeleteSelf_, "the test fixture's destructor");
2663
2664  result_.set_elapsed_time(internal::GetTimeInMillis() - start);
2665
2666  // Notifies the unit test event listener that a test has just finished.
2667  repeater->OnTestEnd(*this);
2668
2669  // Tells UnitTest to stop associating assertion results to this
2670  // test.
2671  impl->set_current_test_info(NULL);
2672}
2673
2674// class TestCase
2675
2676// Gets the number of successful tests in this test case.
2677int TestCase::successful_test_count() const {
2678  return CountIf(test_info_list_, TestPassed);
2679}
2680
2681// Gets the number of failed tests in this test case.
2682int TestCase::failed_test_count() const {
2683  return CountIf(test_info_list_, TestFailed);
2684}
2685
2686// Gets the number of disabled tests that will be reported in the XML report.
2687int TestCase::reportable_disabled_test_count() const {
2688  return CountIf(test_info_list_, TestReportableDisabled);
2689}
2690
2691// Gets the number of disabled tests in this test case.
2692int TestCase::disabled_test_count() const {
2693  return CountIf(test_info_list_, TestDisabled);
2694}
2695
2696// Gets the number of tests to be printed in the XML report.
2697int TestCase::reportable_test_count() const {
2698  return CountIf(test_info_list_, TestReportable);
2699}
2700
2701// Get the number of tests in this test case that should run.
2702int TestCase::test_to_run_count() const {
2703  return CountIf(test_info_list_, ShouldRunTest);
2704}
2705
2706// Gets the number of all tests.
2707int TestCase::total_test_count() const {
2708  return static_cast<int>(test_info_list_.size());
2709}
2710
2711// Creates a TestCase with the given name.
2712//
2713// Arguments:
2714//
2715//   name:         name of the test case
2716//   a_type_param: the name of the test case's type parameter, or NULL if
2717//                 this is not a typed or a type-parameterized test case.
2718//   set_up_tc:    pointer to the function that sets up the test case
2719//   tear_down_tc: pointer to the function that tears down the test case
2720TestCase::TestCase(const char* a_name, const char* a_type_param,
2721                   Test::SetUpTestCaseFunc set_up_tc,
2722                   Test::TearDownTestCaseFunc tear_down_tc)
2723    : name_(a_name),
2724      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2725      set_up_tc_(set_up_tc),
2726      tear_down_tc_(tear_down_tc),
2727      should_run_(false),
2728      elapsed_time_(0) {
2729}
2730
2731// Destructor of TestCase.
2732TestCase::~TestCase() {
2733  // Deletes every Test in the collection.
2734  ForEach(test_info_list_, internal::Delete<TestInfo>);
2735}
2736
2737// Returns the i-th test among all the tests. i can range from 0 to
2738// total_test_count() - 1. If i is not in that range, returns NULL.
2739const TestInfo* TestCase::GetTestInfo(int i) const {
2740  const int index = GetElementOr(test_indices_, i, -1);
2741  return index < 0 ? NULL : test_info_list_[index];
2742}
2743
2744// Returns the i-th test among all the tests. i can range from 0 to
2745// total_test_count() - 1. If i is not in that range, returns NULL.
2746TestInfo* TestCase::GetMutableTestInfo(int i) {
2747  const int index = GetElementOr(test_indices_, i, -1);
2748  return index < 0 ? NULL : test_info_list_[index];
2749}
2750
2751// Adds a test to this test case.  Will delete the test upon
2752// destruction of the TestCase object.
2753void TestCase::AddTestInfo(TestInfo * test_info) {
2754  test_info_list_.push_back(test_info);
2755  test_indices_.push_back(static_cast<int>(test_indices_.size()));
2756}
2757
2758// Runs every test in this TestCase.
2759void TestCase::Run() {
2760  if (!should_run_) return;
2761
2762  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2763  impl->set_current_test_case(this);
2764
2765  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2766
2767  repeater->OnTestCaseStart(*this);
2768  impl->os_stack_trace_getter()->UponLeavingGTest();
2769  internal::HandleExceptionsInMethodIfSupported(
2770      this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
2771
2772  const internal::TimeInMillis start = internal::GetTimeInMillis();
2773  for (int i = 0; i < total_test_count(); i++) {
2774    GetMutableTestInfo(i)->Run();
2775  }
2776  elapsed_time_ = internal::GetTimeInMillis() - start;
2777
2778  impl->os_stack_trace_getter()->UponLeavingGTest();
2779  internal::HandleExceptionsInMethodIfSupported(
2780      this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
2781
2782  repeater->OnTestCaseEnd(*this);
2783  impl->set_current_test_case(NULL);
2784}
2785
2786// Clears the results of all tests in this test case.
2787void TestCase::ClearResult() {
2788  ad_hoc_test_result_.Clear();
2789  ForEach(test_info_list_, TestInfo::ClearTestResult);
2790}
2791
2792// Shuffles the tests in this test case.
2793void TestCase::ShuffleTests(internal::Random* random) {
2794  Shuffle(random, &test_indices_);
2795}
2796
2797// Restores the test order to before the first shuffle.
2798void TestCase::UnshuffleTests() {
2799  for (size_t i = 0; i < test_indices_.size(); i++) {
2800    test_indices_[i] = static_cast<int>(i);
2801  }
2802}
2803
2804// Formats a countable noun.  Depending on its quantity, either the
2805// singular form or the plural form is used. e.g.
2806//
2807// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2808// FormatCountableNoun(5, "book", "books") returns "5 books".
2809static std::string FormatCountableNoun(int count,
2810                                       const char * singular_form,
2811                                       const char * plural_form) {
2812  return internal::StreamableToString(count) + " " +
2813      (count == 1 ? singular_form : plural_form);
2814}
2815
2816// Formats the count of tests.
2817static std::string FormatTestCount(int test_count) {
2818  return FormatCountableNoun(test_count, "test", "tests");
2819}
2820
2821// Formats the count of test cases.
2822static std::string FormatTestCaseCount(int test_case_count) {
2823  return FormatCountableNoun(test_case_count, "test case", "test cases");
2824}
2825
2826// Converts a TestPartResult::Type enum to human-friendly string
2827// representation.  Both kNonFatalFailure and kFatalFailure are translated
2828// to "Failure", as the user usually doesn't care about the difference
2829// between the two when viewing the test result.
2830static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2831  switch (type) {
2832    case TestPartResult::kSuccess:
2833      return "Success";
2834
2835    case TestPartResult::kNonFatalFailure:
2836    case TestPartResult::kFatalFailure:
2837#ifdef _MSC_VER
2838      return "error: ";
2839#else
2840      return "Failure\n";
2841#endif
2842    default:
2843      return "Unknown result type";
2844  }
2845}
2846
2847namespace internal {
2848
2849// Prints a TestPartResult to an std::string.
2850static std::string PrintTestPartResultToString(
2851    const TestPartResult& test_part_result) {
2852  return (Message()
2853          << internal::FormatFileLocation(test_part_result.file_name(),
2854                                          test_part_result.line_number())
2855          << " " << TestPartResultTypeToString(test_part_result.type())
2856          << test_part_result.message()).GetString();
2857}
2858
2859// Prints a TestPartResult.
2860static void PrintTestPartResult(const TestPartResult& test_part_result) {
2861  const std::string& result =
2862      PrintTestPartResultToString(test_part_result);
2863  printf("%s\n", result.c_str());
2864  fflush(stdout);
2865  // If the test program runs in Visual Studio or a debugger, the
2866  // following statements add the test part result message to the Output
2867  // window such that the user can double-click on it to jump to the
2868  // corresponding source code location; otherwise they do nothing.
2869#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2870  // We don't call OutputDebugString*() on Windows Mobile, as printing
2871  // to stdout is done by OutputDebugString() there already - we don't
2872  // want the same message printed twice.
2873  ::OutputDebugStringA(result.c_str());
2874  ::OutputDebugStringA("\n");
2875#endif
2876}
2877
2878// class PrettyUnitTestResultPrinter
2879
2880enum GTestColor {
2881  COLOR_DEFAULT,
2882  COLOR_RED,
2883  COLOR_GREEN,
2884  COLOR_YELLOW
2885};
2886
2887#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2888    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
2889
2890// Returns the character attribute for the given color.
2891WORD GetColorAttribute(GTestColor color) {
2892  switch (color) {
2893    case COLOR_RED:    return FOREGROUND_RED;
2894    case COLOR_GREEN:  return FOREGROUND_GREEN;
2895    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2896    default:           return 0;
2897  }
2898}
2899
2900#else
2901
2902// Returns the ANSI color code for the given color.  COLOR_DEFAULT is
2903// an invalid input.
2904const char* GetAnsiColorCode(GTestColor color) {
2905  switch (color) {
2906    case COLOR_RED:     return "1";
2907    case COLOR_GREEN:   return "2";
2908    case COLOR_YELLOW:  return "3";
2909    default:            return NULL;
2910  };
2911}
2912
2913#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2914
2915// Returns true iff Google Test should use colors in the output.
2916bool ShouldUseColor(bool stdout_is_tty) {
2917  const char* const gtest_color = GTEST_FLAG(color).c_str();
2918
2919  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2920#if GTEST_OS_WINDOWS
2921    // On Windows the TERM variable is usually not set, but the
2922    // console there does support colors.
2923    return stdout_is_tty;
2924#else
2925    // On non-Windows platforms, we rely on the TERM variable.
2926    const char* const term = posix::GetEnv("TERM");
2927    const bool term_supports_color =
2928        String::CStringEquals(term, "xterm") ||
2929        String::CStringEquals(term, "xterm-color") ||
2930        String::CStringEquals(term, "xterm-256color") ||
2931        String::CStringEquals(term, "screen") ||
2932        String::CStringEquals(term, "screen-256color") ||
2933        String::CStringEquals(term, "rxvt-unicode") ||
2934        String::CStringEquals(term, "rxvt-unicode-256color") ||
2935        String::CStringEquals(term, "linux") ||
2936        String::CStringEquals(term, "cygwin");
2937    return stdout_is_tty && term_supports_color;
2938#endif  // GTEST_OS_WINDOWS
2939  }
2940
2941  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2942      String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2943      String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2944      String::CStringEquals(gtest_color, "1");
2945  // We take "yes", "true", "t", and "1" as meaning "yes".  If the
2946  // value is neither one of these nor "auto", we treat it as "no" to
2947  // be conservative.
2948}
2949
2950// Helpers for printing colored strings to stdout. Note that on Windows, we
2951// cannot simply emit special characters and have the terminal change colors.
2952// This routine must actually emit the characters rather than return a string
2953// that would be colored when printed, as can be done on Linux.
2954void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2955  va_list args;
2956  va_start(args, fmt);
2957
2958#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
2959    GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
2960  const bool use_color = AlwaysFalse();
2961#else
2962  static const bool in_color_mode =
2963      ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
2964  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
2965#endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2966  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2967
2968  if (!use_color) {
2969    vprintf(fmt, args);
2970    va_end(args);
2971    return;
2972  }
2973
2974#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2975    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
2976  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2977
2978  // Gets the current text color.
2979  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2980  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2981  const WORD old_color_attrs = buffer_info.wAttributes;
2982
2983  // We need to flush the stream buffers into the console before each
2984  // SetConsoleTextAttribute call lest it affect the text that is already
2985  // printed but has not yet reached the console.
2986  fflush(stdout);
2987  SetConsoleTextAttribute(stdout_handle,
2988                          GetColorAttribute(color) | FOREGROUND_INTENSITY);
2989  vprintf(fmt, args);
2990
2991  fflush(stdout);
2992  // Restores the text color.
2993  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2994#else
2995  printf("\033[0;3%sm", GetAnsiColorCode(color));
2996  vprintf(fmt, args);
2997  printf("\033[m");  // Resets the terminal to default.
2998#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2999  va_end(args);
3000}
3001
3002// Text printed in Google Test's text output and --gunit_list_tests
3003// output to label the type parameter and value parameter for a test.
3004static const char kTypeParamLabel[] = "TypeParam";
3005static const char kValueParamLabel[] = "GetParam()";
3006
3007void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3008  const char* const type_param = test_info.type_param();
3009  const char* const value_param = test_info.value_param();
3010
3011  if (type_param != NULL || value_param != NULL) {
3012    printf(", where ");
3013    if (type_param != NULL) {
3014      printf("%s = %s", kTypeParamLabel, type_param);
3015      if (value_param != NULL)
3016        printf(" and ");
3017    }
3018    if (value_param != NULL) {
3019      printf("%s = %s", kValueParamLabel, value_param);
3020    }
3021  }
3022}
3023
3024// This class implements the TestEventListener interface.
3025//
3026// Class PrettyUnitTestResultPrinter is copyable.
3027class PrettyUnitTestResultPrinter : public TestEventListener {
3028 public:
3029  PrettyUnitTestResultPrinter() {}
3030  static void PrintTestName(const char * test_case, const char * test) {
3031    printf("%s.%s", test_case, test);
3032  }
3033
3034  // The following methods override what's in the TestEventListener class.
3035  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
3036  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3037  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3038  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
3039  virtual void OnTestCaseStart(const TestCase& test_case);
3040  virtual void OnTestStart(const TestInfo& test_info);
3041  virtual void OnTestPartResult(const TestPartResult& result);
3042  virtual void OnTestEnd(const TestInfo& test_info);
3043  virtual void OnTestCaseEnd(const TestCase& test_case);
3044  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3045  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
3046  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3047  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
3048
3049 private:
3050  static void PrintFailedTests(const UnitTest& unit_test);
3051};
3052
3053  // Fired before each iteration of tests starts.
3054void PrettyUnitTestResultPrinter::OnTestIterationStart(
3055    const UnitTest& unit_test, int iteration) {
3056  if (GTEST_FLAG(repeat) != 1)
3057    printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3058
3059  const char* const filter = GTEST_FLAG(filter).c_str();
3060
3061  // Prints the filter if it's not *.  This reminds the user that some
3062  // tests may be skipped.
3063  if (!String::CStringEquals(filter, kUniversalFilter)) {
3064    ColoredPrintf(COLOR_YELLOW,
3065                  "Note: %s filter = %s\n", GTEST_NAME_, filter);
3066  }
3067
3068  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
3069    const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
3070    ColoredPrintf(COLOR_YELLOW,
3071                  "Note: This is test shard %d of %s.\n",
3072                  static_cast<int>(shard_index) + 1,
3073                  internal::posix::GetEnv(kTestTotalShards));
3074  }
3075
3076  if (GTEST_FLAG(shuffle)) {
3077    ColoredPrintf(COLOR_YELLOW,
3078                  "Note: Randomizing tests' orders with a seed of %d .\n",
3079                  unit_test.random_seed());
3080  }
3081
3082  ColoredPrintf(COLOR_GREEN,  "[==========] ");
3083  printf("Running %s from %s.\n",
3084         FormatTestCount(unit_test.test_to_run_count()).c_str(),
3085         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3086  fflush(stdout);
3087}
3088
3089void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3090    const UnitTest& /*unit_test*/) {
3091  ColoredPrintf(COLOR_GREEN,  "[----------] ");
3092  printf("Global test environment set-up.\n");
3093  fflush(stdout);
3094}
3095
3096void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
3097  const std::string counts =
3098      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3099  ColoredPrintf(COLOR_GREEN, "[----------] ");
3100  printf("%s from %s", counts.c_str(), test_case.name());
3101  if (test_case.type_param() == NULL) {
3102    printf("\n");
3103  } else {
3104    printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
3105  }
3106  fflush(stdout);
3107}
3108
3109void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
3110  ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
3111  PrintTestName(test_info.test_case_name(), test_info.name());
3112  printf("\n");
3113  fflush(stdout);
3114}
3115
3116// Called after an assertion failure.
3117void PrettyUnitTestResultPrinter::OnTestPartResult(
3118    const TestPartResult& result) {
3119  // If the test part succeeded, we don't need to do anything.
3120  if (result.type() == TestPartResult::kSuccess)
3121    return;
3122
3123  // Print failure message from the assertion (e.g. expected this and got that).
3124  PrintTestPartResult(result);
3125  fflush(stdout);
3126}
3127
3128void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
3129  if (test_info.result()->Passed()) {
3130    ColoredPrintf(COLOR_GREEN, "[       OK ] ");
3131  } else {
3132    ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
3133  }
3134  PrintTestName(test_info.test_case_name(), test_info.name());
3135  if (test_info.result()->Failed())
3136    PrintFullTestCommentIfPresent(test_info);
3137
3138  if (GTEST_FLAG(print_time)) {
3139    printf(" (%s ms)\n", internal::StreamableToString(
3140           test_info.result()->elapsed_time()).c_str());
3141  } else {
3142    printf("\n");
3143  }
3144  fflush(stdout);
3145}
3146
3147void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
3148  if (!GTEST_FLAG(print_time)) return;
3149
3150  const std::string counts =
3151      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3152  ColoredPrintf(COLOR_GREEN, "[----------] ");
3153  printf("%s from %s (%s ms total)\n\n",
3154         counts.c_str(), test_case.name(),
3155         internal::StreamableToString(test_case.elapsed_time()).c_str());
3156  fflush(stdout);
3157}
3158
3159void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3160    const UnitTest& /*unit_test*/) {
3161  ColoredPrintf(COLOR_GREEN,  "[----------] ");
3162  printf("Global test environment tear-down\n");
3163  fflush(stdout);
3164}
3165
3166// Internal helper for printing the list of failed tests.
3167void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
3168  const int failed_test_count = unit_test.failed_test_count();
3169  if (failed_test_count == 0) {
3170    return;
3171  }
3172
3173  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3174    const TestCase& test_case = *unit_test.GetTestCase(i);
3175    if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
3176      continue;
3177    }
3178    for (int j = 0; j < test_case.total_test_count(); ++j) {
3179      const TestInfo& test_info = *test_case.GetTestInfo(j);
3180      if (!test_info.should_run() || test_info.result()->Passed()) {
3181        continue;
3182      }
3183      ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
3184      printf("%s.%s", test_case.name(), test_info.name());
3185      PrintFullTestCommentIfPresent(test_info);
3186      printf("\n");
3187    }
3188  }
3189}
3190
3191void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3192                                                     int /*iteration*/) {
3193  ColoredPrintf(COLOR_GREEN,  "[==========] ");
3194  printf("%s from %s ran.",
3195         FormatTestCount(unit_test.test_to_run_count()).c_str(),
3196         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3197  if (GTEST_FLAG(print_time)) {
3198    printf(" (%s ms total)",
3199           internal::StreamableToString(unit_test.elapsed_time()).c_str());
3200  }
3201  printf("\n");
3202  ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
3203  printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3204
3205  int num_failures = unit_test.failed_test_count();
3206  if (!unit_test.Passed()) {
3207    const int failed_test_count = unit_test.failed_test_count();
3208    ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
3209    printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
3210    PrintFailedTests(unit_test);
3211    printf("\n%2d FAILED %s\n", num_failures,
3212                        num_failures == 1 ? "TEST" : "TESTS");
3213  }
3214
3215  int num_disabled = unit_test.reportable_disabled_test_count();
3216  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
3217    if (!num_failures) {
3218      printf("\n");  // Add a spacer if no FAILURE banner is displayed.
3219    }
3220    ColoredPrintf(COLOR_YELLOW,
3221                  "  YOU HAVE %d DISABLED %s\n\n",
3222                  num_disabled,
3223                  num_disabled == 1 ? "TEST" : "TESTS");
3224  }
3225  // Ensure that Google Test output is printed before, e.g., heapchecker output.
3226  fflush(stdout);
3227}
3228
3229// End PrettyUnitTestResultPrinter
3230
3231// class TestEventRepeater
3232//
3233// This class forwards events to other event listeners.
3234class TestEventRepeater : public TestEventListener {
3235 public:
3236  TestEventRepeater() : forwarding_enabled_(true) {}
3237  virtual ~TestEventRepeater();
3238  void Append(TestEventListener *listener);
3239  TestEventListener* Release(TestEventListener* listener);
3240
3241  // Controls whether events will be forwarded to listeners_. Set to false
3242  // in death test child processes.
3243  bool forwarding_enabled() const { return forwarding_enabled_; }
3244  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
3245
3246  virtual void OnTestProgramStart(const UnitTest& unit_test);
3247  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3248  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3249  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
3250  virtual void OnTestCaseStart(const TestCase& test_case);
3251  virtual void OnTestStart(const TestInfo& test_info);
3252  virtual void OnTestPartResult(const TestPartResult& result);
3253  virtual void OnTestEnd(const TestInfo& test_info);
3254  virtual void OnTestCaseEnd(const TestCase& test_case);
3255  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3256  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
3257  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3258  virtual void OnTestProgramEnd(const UnitTest& unit_test);
3259
3260 private:
3261  // Controls whether events will be forwarded to listeners_. Set to false
3262  // in death test child processes.
3263  bool forwarding_enabled_;
3264  // The list of listeners that receive events.
3265  std::vector<TestEventListener*> listeners_;
3266
3267  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
3268};
3269
3270TestEventRepeater::~TestEventRepeater() {
3271  ForEach(listeners_, Delete<TestEventListener>);
3272}
3273
3274void TestEventRepeater::Append(TestEventListener *listener) {
3275  listeners_.push_back(listener);
3276}
3277
3278// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
3279TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
3280  for (size_t i = 0; i < listeners_.size(); ++i) {
3281    if (listeners_[i] == listener) {
3282      listeners_.erase(listeners_.begin() + i);
3283      return listener;
3284    }
3285  }
3286
3287  return NULL;
3288}
3289
3290// Since most methods are very similar, use macros to reduce boilerplate.
3291// This defines a member that forwards the call to all listeners.
3292#define GTEST_REPEATER_METHOD_(Name, Type) \
3293void TestEventRepeater::Name(const Type& parameter) { \
3294  if (forwarding_enabled_) { \
3295    for (size_t i = 0; i < listeners_.size(); i++) { \
3296      listeners_[i]->Name(parameter); \
3297    } \
3298  } \
3299}
3300// This defines a member that forwards the call to all listeners in reverse
3301// order.
3302#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3303void TestEventRepeater::Name(const Type& parameter) { \
3304  if (forwarding_enabled_) { \
3305    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
3306      listeners_[i]->Name(parameter); \
3307    } \
3308  } \
3309}
3310
3311GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
3312GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3313GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
3314GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
3315GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
3316GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
3317GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
3318GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
3319GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3320GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
3321GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
3322
3323#undef GTEST_REPEATER_METHOD_
3324#undef GTEST_REVERSE_REPEATER_METHOD_
3325
3326void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
3327                                             int iteration) {
3328  if (forwarding_enabled_) {
3329    for (size_t i = 0; i < listeners_.size(); i++) {
3330      listeners_[i]->OnTestIterationStart(unit_test, iteration);
3331    }
3332  }
3333}
3334
3335void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
3336                                           int iteration) {
3337  if (forwarding_enabled_) {
3338    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
3339      listeners_[i]->OnTestIterationEnd(unit_test, iteration);
3340    }
3341  }
3342}
3343
3344// End TestEventRepeater
3345
3346// This class generates an XML output file.
3347class XmlUnitTestResultPrinter : public EmptyTestEventListener {
3348 public:
3349  explicit XmlUnitTestResultPrinter(const char* output_file);
3350
3351  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3352
3353 private:
3354  // Is c a whitespace character that is normalized to a space character
3355  // when it appears in an XML attribute value?
3356  static bool IsNormalizableWhitespace(char c) {
3357    return c == 0x9 || c == 0xA || c == 0xD;
3358  }
3359
3360  // May c appear in a well-formed XML document?
3361  static bool IsValidXmlCharacter(char c) {
3362    return IsNormalizableWhitespace(c) || c >= 0x20;
3363  }
3364
3365  // Returns an XML-escaped copy of the input string str.  If
3366  // is_attribute is true, the text is meant to appear as an attribute
3367  // value, and normalizable whitespace is preserved by replacing it
3368  // with character references.
3369  static std::string EscapeXml(const std::string& str, bool is_attribute);
3370
3371  // Returns the given string with all characters invalid in XML removed.
3372  static std::string RemoveInvalidXmlCharacters(const std::string& str);
3373
3374  // Convenience wrapper around EscapeXml when str is an attribute value.
3375  static std::string EscapeXmlAttribute(const std::string& str) {
3376    return EscapeXml(str, true);
3377  }
3378
3379  // Convenience wrapper around EscapeXml when str is not an attribute value.
3380  static std::string EscapeXmlText(const char* str) {
3381    return EscapeXml(str, false);
3382  }
3383
3384  // Verifies that the given attribute belongs to the given element and
3385  // streams the attribute as XML.
3386  static void OutputXmlAttribute(std::ostream* stream,
3387                                 const std::string& element_name,
3388                                 const std::string& name,
3389                                 const std::string& value);
3390
3391  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3392  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3393
3394  // Streams an XML representation of a TestInfo object.
3395  static void OutputXmlTestInfo(::std::ostream* stream,
3396                                const char* test_case_name,
3397                                const TestInfo& test_info);
3398
3399  // Prints an XML representation of a TestCase object
3400  static void PrintXmlTestCase(::std::ostream* stream,
3401                               const TestCase& test_case);
3402
3403  // Prints an XML summary of unit_test to output stream out.
3404  static void PrintXmlUnitTest(::std::ostream* stream,
3405                               const UnitTest& unit_test);
3406
3407  // Produces a string representing the test properties in a result as space
3408  // delimited XML attributes based on the property key="value" pairs.
3409  // When the std::string is not empty, it includes a space at the beginning,
3410  // to delimit this attribute from prior attributes.
3411  static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
3412
3413  // The output file.
3414  const std::string output_file_;
3415
3416  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3417};
3418
3419// Creates a new XmlUnitTestResultPrinter.
3420XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3421    : output_file_(output_file) {
3422  if (output_file_.c_str() == NULL || output_file_.empty()) {
3423    fprintf(stderr, "XML output file may not be null\n");
3424    fflush(stderr);
3425    exit(EXIT_FAILURE);
3426  }
3427}
3428
3429// Called after the unit test ends.
3430void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3431                                                  int /*iteration*/) {
3432  FILE* xmlout = NULL;
3433  FilePath output_file(output_file_);
3434  FilePath output_dir(output_file.RemoveFileName());
3435
3436  if (output_dir.CreateDirectoriesRecursively()) {
3437    xmlout = posix::FOpen(output_file_.c_str(), "w");
3438  }
3439  if (xmlout == NULL) {
3440    // TODO(wan): report the reason of the failure.
3441    //
3442    // We don't do it for now as:
3443    //
3444    //   1. There is no urgent need for it.
3445    //   2. It's a bit involved to make the errno variable thread-safe on
3446    //      all three operating systems (Linux, Windows, and Mac OS).
3447    //   3. To interpret the meaning of errno in a thread-safe way,
3448    //      we need the strerror_r() function, which is not available on
3449    //      Windows.
3450    fprintf(stderr,
3451            "Unable to open file \"%s\"\n",
3452            output_file_.c_str());
3453    fflush(stderr);
3454    exit(EXIT_FAILURE);
3455  }
3456  std::stringstream stream;
3457  PrintXmlUnitTest(&stream, unit_test);
3458  fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
3459  fclose(xmlout);
3460}
3461
3462// Returns an XML-escaped copy of the input string str.  If is_attribute
3463// is true, the text is meant to appear as an attribute value, and
3464// normalizable whitespace is preserved by replacing it with character
3465// references.
3466//
3467// Invalid XML characters in str, if any, are stripped from the output.
3468// It is expected that most, if not all, of the text processed by this
3469// module will consist of ordinary English text.
3470// If this module is ever modified to produce version 1.1 XML output,
3471// most invalid characters can be retained using character references.
3472// TODO(wan): It might be nice to have a minimally invasive, human-readable
3473// escaping scheme for invalid characters, rather than dropping them.
3474std::string XmlUnitTestResultPrinter::EscapeXml(
3475    const std::string& str, bool is_attribute) {
3476  Message m;
3477
3478  for (size_t i = 0; i < str.size(); ++i) {
3479    const char ch = str[i];
3480    switch (ch) {
3481      case '<':
3482        m << "&lt;";
3483        break;
3484      case '>':
3485        m << "&gt;";
3486        break;
3487      case '&':
3488        m << "&amp;";
3489        break;
3490      case '\'':
3491        if (is_attribute)
3492          m << "&apos;";
3493        else
3494          m << '\'';
3495        break;
3496      case '"':
3497        if (is_attribute)
3498          m << "&quot;";
3499        else
3500          m << '"';
3501        break;
3502      default:
3503        if (IsValidXmlCharacter(ch)) {
3504          if (is_attribute && IsNormalizableWhitespace(ch))
3505            m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
3506              << ";";
3507          else
3508            m << ch;
3509        }
3510        break;
3511    }
3512  }
3513
3514  return m.GetString();
3515}
3516
3517// Returns the given string with all characters invalid in XML removed.
3518// Currently invalid characters are dropped from the string. An
3519// alternative is to replace them with certain characters such as . or ?.
3520std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
3521    const std::string& str) {
3522  std::string output;
3523  output.reserve(str.size());
3524  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
3525    if (IsValidXmlCharacter(*it))
3526      output.push_back(*it);
3527
3528  return output;
3529}
3530
3531// The following routines generate an XML representation of a UnitTest
3532// object.
3533//
3534// This is how Google Test concepts map to the DTD:
3535//
3536// <testsuites name="AllTests">        <-- corresponds to a UnitTest object
3537//   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
3538//     <testcase name="test-name">     <-- corresponds to a TestInfo object
3539//       <failure message="...">...</failure>
3540//       <failure message="...">...</failure>
3541//       <failure message="...">...</failure>
3542//                                     <-- individual assertion failures
3543//     </testcase>
3544//   </testsuite>
3545// </testsuites>
3546
3547// Formats the given time in milliseconds as seconds.
3548std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3549  ::std::stringstream ss;
3550  ss << (static_cast<double>(ms) * 1e-3);
3551  return ss.str();
3552}
3553
3554static bool PortableLocaltime(time_t seconds, struct tm* out) {
3555#if defined(_MSC_VER)
3556  return localtime_s(out, &seconds) == 0;
3557#elif defined(__MINGW32__) || defined(__MINGW64__)
3558  // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
3559  // Windows' localtime(), which has a thread-local tm buffer.
3560  struct tm* tm_ptr = localtime(&seconds);  // NOLINT
3561  if (tm_ptr == NULL)
3562    return false;
3563  *out = *tm_ptr;
3564  return true;
3565#else
3566  return localtime_r(&seconds, out) != NULL;
3567#endif
3568}
3569
3570// Converts the given epoch time in milliseconds to a date string in the ISO
3571// 8601 format, without the timezone information.
3572std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
3573  struct tm time_struct;
3574  if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
3575    return "";
3576  // YYYY-MM-DDThh:mm:ss
3577  return StreamableToString(time_struct.tm_year + 1900) + "-" +
3578      String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
3579      String::FormatIntWidth2(time_struct.tm_mday) + "T" +
3580      String::FormatIntWidth2(time_struct.tm_hour) + ":" +
3581      String::FormatIntWidth2(time_struct.tm_min) + ":" +
3582      String::FormatIntWidth2(time_struct.tm_sec);
3583}
3584
3585// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3586void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3587                                                     const char* data) {
3588  const char* segment = data;
3589  *stream << "<![CDATA[";
3590  for (;;) {
3591    const char* const next_segment = strstr(segment, "]]>");
3592    if (next_segment != NULL) {
3593      stream->write(
3594          segment, static_cast<std::streamsize>(next_segment - segment));
3595      *stream << "]]>]]&gt;<![CDATA[";
3596      segment = next_segment + strlen("]]>");
3597    } else {
3598      *stream << segment;
3599      break;
3600    }
3601  }
3602  *stream << "]]>";
3603}
3604
3605void XmlUnitTestResultPrinter::OutputXmlAttribute(
3606    std::ostream* stream,
3607    const std::string& element_name,
3608    const std::string& name,
3609    const std::string& value) {
3610  const std::vector<std::string>& allowed_names =
3611      GetReservedAttributesForElement(element_name);
3612
3613  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
3614                   allowed_names.end())
3615      << "Attribute " << name << " is not allowed for element <" << element_name
3616      << ">.";
3617
3618  *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
3619}
3620
3621// Prints an XML representation of a TestInfo object.
3622// TODO(wan): There is also value in printing properties with the plain printer.
3623void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3624                                                 const char* test_case_name,
3625                                                 const TestInfo& test_info) {
3626  const TestResult& result = *test_info.result();
3627  const std::string kTestcase = "testcase";
3628
3629  *stream << "    <testcase";
3630  OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
3631
3632  if (test_info.value_param() != NULL) {
3633    OutputXmlAttribute(stream, kTestcase, "value_param",
3634                       test_info.value_param());
3635  }
3636  if (test_info.type_param() != NULL) {
3637    OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
3638  }
3639
3640  OutputXmlAttribute(stream, kTestcase, "status",
3641                     test_info.should_run() ? "run" : "notrun");
3642  OutputXmlAttribute(stream, kTestcase, "time",
3643                     FormatTimeInMillisAsSeconds(result.elapsed_time()));
3644  OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
3645  *stream << TestPropertiesAsXmlAttributes(result);
3646
3647  int failures = 0;
3648  for (int i = 0; i < result.total_part_count(); ++i) {
3649    const TestPartResult& part = result.GetTestPartResult(i);
3650    if (part.failed()) {
3651      if (++failures == 1) {
3652        *stream << ">\n";
3653      }
3654      const string location = internal::FormatCompilerIndependentFileLocation(
3655          part.file_name(), part.line_number());
3656      const string summary = location + "\n" + part.summary();
3657      *stream << "      <failure message=\""
3658              << EscapeXmlAttribute(summary.c_str())
3659              << "\" type=\"\">";
3660      const string detail = location + "\n" + part.message();
3661      OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
3662      *stream << "</failure>\n";
3663    }
3664  }
3665
3666  if (failures == 0)
3667    *stream << " />\n";
3668  else
3669    *stream << "    </testcase>\n";
3670}
3671
3672// Prints an XML representation of a TestCase object
3673void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
3674                                                const TestCase& test_case) {
3675  const std::string kTestsuite = "testsuite";
3676  *stream << "  <" << kTestsuite;
3677  OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
3678  OutputXmlAttribute(stream, kTestsuite, "tests",
3679                     StreamableToString(test_case.reportable_test_count()));
3680  OutputXmlAttribute(stream, kTestsuite, "failures",
3681                     StreamableToString(test_case.failed_test_count()));
3682  OutputXmlAttribute(
3683      stream, kTestsuite, "disabled",
3684      StreamableToString(test_case.reportable_disabled_test_count()));
3685  OutputXmlAttribute(stream, kTestsuite, "errors", "0");
3686  OutputXmlAttribute(stream, kTestsuite, "time",
3687                     FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
3688  *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
3689          << ">\n";
3690
3691  for (int i = 0; i < test_case.total_test_count(); ++i) {
3692    if (test_case.GetTestInfo(i)->is_reportable())
3693      OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
3694  }
3695  *stream << "  </" << kTestsuite << ">\n";
3696}
3697
3698// Prints an XML summary of unit_test to output stream out.
3699void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
3700                                                const UnitTest& unit_test) {
3701  const std::string kTestsuites = "testsuites";
3702
3703  *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3704  *stream << "<" << kTestsuites;
3705
3706  OutputXmlAttribute(stream, kTestsuites, "tests",
3707                     StreamableToString(unit_test.reportable_test_count()));
3708  OutputXmlAttribute(stream, kTestsuites, "failures",
3709                     StreamableToString(unit_test.failed_test_count()));
3710  OutputXmlAttribute(
3711      stream, kTestsuites, "disabled",
3712      StreamableToString(unit_test.reportable_disabled_test_count()));
3713  OutputXmlAttribute(stream, kTestsuites, "errors", "0");
3714  OutputXmlAttribute(
3715      stream, kTestsuites, "timestamp",
3716      FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
3717  OutputXmlAttribute(stream, kTestsuites, "time",
3718                     FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
3719
3720  if (GTEST_FLAG(shuffle)) {
3721    OutputXmlAttribute(stream, kTestsuites, "random_seed",
3722                       StreamableToString(unit_test.random_seed()));
3723  }
3724
3725  *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
3726
3727  OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
3728  *stream << ">\n";
3729
3730  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3731    if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
3732      PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
3733  }
3734  *stream << "</" << kTestsuites << ">\n";
3735}
3736
3737// Produces a string representing the test properties in a result as space
3738// delimited XML attributes based on the property key="value" pairs.
3739std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3740    const TestResult& result) {
3741  Message attributes;
3742  for (int i = 0; i < result.test_property_count(); ++i) {
3743    const TestProperty& property = result.GetTestProperty(i);
3744    attributes << " " << property.key() << "="
3745        << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3746  }
3747  return attributes.GetString();
3748}
3749
3750// End XmlUnitTestResultPrinter
3751
3752#if GTEST_CAN_STREAM_RESULTS_
3753
3754// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
3755// replaces them by "%xx" where xx is their hexadecimal value. For
3756// example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
3757// in both time and space -- important as the input str may contain an
3758// arbitrarily long test failure message and stack trace.
3759string StreamingListener::UrlEncode(const char* str) {
3760  string result;
3761  result.reserve(strlen(str) + 1);
3762  for (char ch = *str; ch != '\0'; ch = *++str) {
3763    switch (ch) {
3764      case '%':
3765      case '=':
3766      case '&':
3767      case '\n':
3768        result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
3769        break;
3770      default:
3771        result.push_back(ch);
3772        break;
3773    }
3774  }
3775  return result;
3776}
3777
3778void StreamingListener::SocketWriter::MakeConnection() {
3779  GTEST_CHECK_(sockfd_ == -1)
3780      << "MakeConnection() can't be called when there is already a connection.";
3781
3782  addrinfo hints;
3783  memset(&hints, 0, sizeof(hints));
3784  hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
3785  hints.ai_socktype = SOCK_STREAM;
3786  addrinfo* servinfo = NULL;
3787
3788  // Use the getaddrinfo() to get a linked list of IP addresses for
3789  // the given host name.
3790  const int error_num = getaddrinfo(
3791      host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
3792  if (error_num != 0) {
3793    GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
3794                        << gai_strerror(error_num);
3795  }
3796
3797  // Loop through all the results and connect to the first we can.
3798  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
3799       cur_addr = cur_addr->ai_next) {
3800    sockfd_ = socket(
3801        cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
3802    if (sockfd_ != -1) {
3803      // Connect the client socket to the server socket.
3804      if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
3805        close(sockfd_);
3806        sockfd_ = -1;
3807      }
3808    }
3809  }
3810
3811  freeaddrinfo(servinfo);  // all done with this structure
3812
3813  if (sockfd_ == -1) {
3814    GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
3815                        << host_name_ << ":" << port_num_;
3816  }
3817}
3818
3819// End of class Streaming Listener
3820#endif  // GTEST_CAN_STREAM_RESULTS__
3821
3822// Class ScopedTrace
3823
3824// Pushes the given source file location and message onto a per-thread
3825// trace stack maintained by Google Test.
3826ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
3827    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
3828  TraceInfo trace;
3829  trace.file = file;
3830  trace.line = line;
3831  trace.message = message.GetString();
3832
3833  UnitTest::GetInstance()->PushGTestTrace(trace);
3834}
3835
3836// Pops the info pushed by the c'tor.
3837ScopedTrace::~ScopedTrace()
3838    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
3839  UnitTest::GetInstance()->PopGTestTrace();
3840}
3841
3842
3843// class OsStackTraceGetter
3844
3845const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
3846    "... " GTEST_NAME_ " internal frames ...";
3847
3848string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,
3849                                             int /*skip_count*/) {
3850  return "";
3851}
3852
3853void OsStackTraceGetter::UponLeavingGTest() {}
3854
3855// A helper class that creates the premature-exit file in its
3856// constructor and deletes the file in its destructor.
3857class ScopedPrematureExitFile {
3858 public:
3859  explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
3860      : premature_exit_filepath_(premature_exit_filepath) {
3861    // If a path to the premature-exit file is specified...
3862    if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
3863      // create the file with a single "0" character in it.  I/O
3864      // errors are ignored as there's nothing better we can do and we
3865      // don't want to fail the test because of this.
3866      FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
3867      fwrite("0", 1, 1, pfile);
3868      fclose(pfile);
3869    }
3870  }
3871
3872  ~ScopedPrematureExitFile() {
3873    if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
3874      remove(premature_exit_filepath_);
3875    }
3876  }
3877
3878 private:
3879  const char* const premature_exit_filepath_;
3880
3881  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
3882};
3883
3884}  // namespace internal
3885
3886// class TestEventListeners
3887
3888TestEventListeners::TestEventListeners()
3889    : repeater_(new internal::TestEventRepeater()),
3890      default_result_printer_(NULL),
3891      default_xml_generator_(NULL) {
3892}
3893
3894TestEventListeners::~TestEventListeners() { delete repeater_; }
3895
3896// Returns the standard listener responsible for the default console
3897// output.  Can be removed from the listeners list to shut down default
3898// console output.  Note that removing this object from the listener list
3899// with Release transfers its ownership to the user.
3900void TestEventListeners::Append(TestEventListener* listener) {
3901  repeater_->Append(listener);
3902}
3903
3904// Removes the given event listener from the list and returns it.  It then
3905// becomes the caller's responsibility to delete the listener. Returns
3906// NULL if the listener is not found in the list.
3907TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3908  if (listener == default_result_printer_)
3909    default_result_printer_ = NULL;
3910  else if (listener == default_xml_generator_)
3911    default_xml_generator_ = NULL;
3912  return repeater_->Release(listener);
3913}
3914
3915// Returns repeater that broadcasts the TestEventListener events to all
3916// subscribers.
3917TestEventListener* TestEventListeners::repeater() { return repeater_; }
3918
3919// Sets the default_result_printer attribute to the provided listener.
3920// The listener is also added to the listener list and previous
3921// default_result_printer is removed from it and deleted. The listener can
3922// also be NULL in which case it will not be added to the list. Does
3923// nothing if the previous and the current listener objects are the same.
3924void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3925  if (default_result_printer_ != listener) {
3926    // It is an error to pass this method a listener that is already in the
3927    // list.
3928    delete Release(default_result_printer_);
3929    default_result_printer_ = listener;
3930    if (listener != NULL)
3931      Append(listener);
3932  }
3933}
3934
3935// Sets the default_xml_generator attribute to the provided listener.  The
3936// listener is also added to the listener list and previous
3937// default_xml_generator is removed from it and deleted. The listener can
3938// also be NULL in which case it will not be added to the list. Does
3939// nothing if the previous and the current listener objects are the same.
3940void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3941  if (default_xml_generator_ != listener) {
3942    // It is an error to pass this method a listener that is already in the
3943    // list.
3944    delete Release(default_xml_generator_);
3945    default_xml_generator_ = listener;
3946    if (listener != NULL)
3947      Append(listener);
3948  }
3949}
3950
3951// Controls whether events will be forwarded by the repeater to the
3952// listeners in the list.
3953bool TestEventListeners::EventForwardingEnabled() const {
3954  return repeater_->forwarding_enabled();
3955}
3956
3957void TestEventListeners::SuppressEventForwarding() {
3958  repeater_->set_forwarding_enabled(false);
3959}
3960
3961// class UnitTest
3962
3963// Gets the singleton UnitTest object.  The first time this method is
3964// called, a UnitTest object is constructed and returned.  Consecutive
3965// calls will return the same object.
3966//
3967// We don't protect this under mutex_ as a user is not supposed to
3968// call this before main() starts, from which point on the return
3969// value will never change.
3970UnitTest* UnitTest::GetInstance() {
3971  // When compiled with MSVC 7.1 in optimized mode, destroying the
3972  // UnitTest object upon exiting the program messes up the exit code,
3973  // causing successful tests to appear failed.  We have to use a
3974  // different implementation in this case to bypass the compiler bug.
3975  // This implementation makes the compiler happy, at the cost of
3976  // leaking the UnitTest object.
3977
3978  // CodeGear C++Builder insists on a public destructor for the
3979  // default implementation.  Use this implementation to keep good OO
3980  // design with private destructor.
3981
3982#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3983  static UnitTest* const instance = new UnitTest;
3984  return instance;
3985#else
3986  static UnitTest instance;
3987  return &instance;
3988#endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3989}
3990
3991// Gets the number of successful test cases.
3992int UnitTest::successful_test_case_count() const {
3993  return impl()->successful_test_case_count();
3994}
3995
3996// Gets the number of failed test cases.
3997int UnitTest::failed_test_case_count() const {
3998  return impl()->failed_test_case_count();
3999}
4000
4001// Gets the number of all test cases.
4002int UnitTest::total_test_case_count() const {
4003  return impl()->total_test_case_count();
4004}
4005
4006// Gets the number of all test cases that contain at least one test
4007// that should run.
4008int UnitTest::test_case_to_run_count() const {
4009  return impl()->test_case_to_run_count();
4010}
4011
4012// Gets the number of successful tests.
4013int UnitTest::successful_test_count() const {
4014  return impl()->successful_test_count();
4015}
4016
4017// Gets the number of failed tests.
4018int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4019
4020// Gets the number of disabled tests that will be reported in the XML report.
4021int UnitTest::reportable_disabled_test_count() const {
4022  return impl()->reportable_disabled_test_count();
4023}
4024
4025// Gets the number of disabled tests.
4026int UnitTest::disabled_test_count() const {
4027  return impl()->disabled_test_count();
4028}
4029
4030// Gets the number of tests to be printed in the XML report.
4031int UnitTest::reportable_test_count() const {
4032  return impl()->reportable_test_count();
4033}
4034
4035// Gets the number of all tests.
4036int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4037
4038// Gets the number of tests that should run.
4039int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4040
4041// Gets the time of the test program start, in ms from the start of the
4042// UNIX epoch.
4043internal::TimeInMillis UnitTest::start_timestamp() const {
4044    return impl()->start_timestamp();
4045}
4046
4047// Gets the elapsed time, in milliseconds.
4048internal::TimeInMillis UnitTest::elapsed_time() const {
4049  return impl()->elapsed_time();
4050}
4051
4052// Returns true iff the unit test passed (i.e. all test cases passed).
4053bool UnitTest::Passed() const { return impl()->Passed(); }
4054
4055// Returns true iff the unit test failed (i.e. some test case failed
4056// or something outside of all tests failed).
4057bool UnitTest::Failed() const { return impl()->Failed(); }
4058
4059// Gets the i-th test case among all the test cases. i can range from 0 to
4060// total_test_case_count() - 1. If i is not in that range, returns NULL.
4061const TestCase* UnitTest::GetTestCase(int i) const {
4062  return impl()->GetTestCase(i);
4063}
4064
4065// Returns the TestResult containing information on test failures and
4066// properties logged outside of individual test cases.
4067const TestResult& UnitTest::ad_hoc_test_result() const {
4068  return *impl()->ad_hoc_test_result();
4069}
4070
4071// Gets the i-th test case among all the test cases. i can range from 0 to
4072// total_test_case_count() - 1. If i is not in that range, returns NULL.
4073TestCase* UnitTest::GetMutableTestCase(int i) {
4074  return impl()->GetMutableTestCase(i);
4075}
4076
4077// Returns the list of event listeners that can be used to track events
4078// inside Google Test.
4079TestEventListeners& UnitTest::listeners() {
4080  return *impl()->listeners();
4081}
4082
4083// Registers and returns a global test environment.  When a test
4084// program is run, all global test environments will be set-up in the
4085// order they were registered.  After all tests in the program have
4086// finished, all global test environments will be torn-down in the
4087// *reverse* order they were registered.
4088//
4089// The UnitTest object takes ownership of the given environment.
4090//
4091// We don't protect this under mutex_, as we only support calling it
4092// from the main thread.
4093Environment* UnitTest::AddEnvironment(Environment* env) {
4094  if (env == NULL) {
4095    return NULL;
4096  }
4097
4098  impl_->environments().push_back(env);
4099  return env;
4100}
4101
4102// Adds a TestPartResult to the current TestResult object.  All Google Test
4103// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
4104// this to report their results.  The user code should use the
4105// assertion macros instead of calling this directly.
4106void UnitTest::AddTestPartResult(
4107    TestPartResult::Type result_type,
4108    const char* file_name,
4109    int line_number,
4110    const std::string& message,
4111    const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
4112  Message msg;
4113  msg << message;
4114
4115  internal::MutexLock lock(&mutex_);
4116  if (impl_->gtest_trace_stack().size() > 0) {
4117    msg << "\n" << GTEST_NAME_ << " trace:";
4118
4119    for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
4120         i > 0; --i) {
4121      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
4122      msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
4123          << " " << trace.message;
4124    }
4125  }
4126
4127  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
4128    msg << internal::kStackTraceMarker << os_stack_trace;
4129  }
4130
4131  const TestPartResult result =
4132    TestPartResult(result_type, file_name, line_number,
4133                   msg.GetString().c_str());
4134  impl_->GetTestPartResultReporterForCurrentThread()->
4135      ReportTestPartResult(result);
4136
4137  if (result_type != TestPartResult::kSuccess) {
4138    // gtest_break_on_failure takes precedence over
4139    // gtest_throw_on_failure.  This allows a user to set the latter
4140    // in the code (perhaps in order to use Google Test assertions
4141    // with another testing framework) and specify the former on the
4142    // command line for debugging.
4143    if (GTEST_FLAG(break_on_failure)) {
4144#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4145      // Using DebugBreak on Windows allows gtest to still break into a debugger
4146      // when a failure happens and both the --gtest_break_on_failure and
4147      // the --gtest_catch_exceptions flags are specified.
4148      DebugBreak();
4149#else
4150      // Dereference NULL through a volatile pointer to prevent the compiler
4151      // from removing. We use this rather than abort() or __builtin_trap() for
4152      // portability: Symbian doesn't implement abort() well, and some debuggers
4153      // don't correctly trap abort().
4154      *static_cast<volatile int*>(NULL) = 1;
4155#endif  // GTEST_OS_WINDOWS
4156    } else if (GTEST_FLAG(throw_on_failure)) {
4157#if GTEST_HAS_EXCEPTIONS
4158      throw internal::GoogleTestFailureException(result);
4159#else
4160      // We cannot call abort() as it generates a pop-up in debug mode
4161      // that cannot be suppressed in VC 7.1 or below.
4162      exit(1);
4163#endif
4164    }
4165  }
4166}
4167
4168// Adds a TestProperty to the current TestResult object when invoked from
4169// inside a test, to current TestCase's ad_hoc_test_result_ when invoked
4170// from SetUpTestCase or TearDownTestCase, or to the global property set
4171// when invoked elsewhere.  If the result already contains a property with
4172// the same key, the value will be updated.
4173void UnitTest::RecordProperty(const std::string& key,
4174                              const std::string& value) {
4175  impl_->RecordProperty(TestProperty(key, value));
4176}
4177
4178// Runs all tests in this UnitTest object and prints the result.
4179// Returns 0 if successful, or 1 otherwise.
4180//
4181// We don't protect this under mutex_, as we only support calling it
4182// from the main thread.
4183int UnitTest::Run() {
4184  const bool in_death_test_child_process =
4185      internal::GTEST_FLAG(internal_run_death_test).length() > 0;
4186
4187  // Google Test implements this protocol for catching that a test
4188  // program exits before returning control to Google Test:
4189  //
4190  //   1. Upon start, Google Test creates a file whose absolute path
4191  //      is specified by the environment variable
4192  //      TEST_PREMATURE_EXIT_FILE.
4193  //   2. When Google Test has finished its work, it deletes the file.
4194  //
4195  // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
4196  // running a Google-Test-based test program and check the existence
4197  // of the file at the end of the test execution to see if it has
4198  // exited prematurely.
4199
4200  // If we are in the child process of a death test, don't
4201  // create/delete the premature exit file, as doing so is unnecessary
4202  // and will confuse the parent process.  Otherwise, create/delete
4203  // the file upon entering/leaving this function.  If the program
4204  // somehow exits before this function has a chance to return, the
4205  // premature-exit file will be left undeleted, causing a test runner
4206  // that understands the premature-exit-file protocol to report the
4207  // test as having failed.
4208  const internal::ScopedPrematureExitFile premature_exit_file(
4209      in_death_test_child_process ?
4210      NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
4211
4212  // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
4213  // used for the duration of the program.
4214  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
4215
4216#if GTEST_HAS_SEH
4217  // Either the user wants Google Test to catch exceptions thrown by the
4218  // tests or this is executing in the context of death test child
4219  // process. In either case the user does not want to see pop-up dialogs
4220  // about crashes - they are expected.
4221  if (impl()->catch_exceptions() || in_death_test_child_process) {
4222# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4223    // SetErrorMode doesn't exist on CE.
4224    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
4225                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
4226# endif  // !GTEST_OS_WINDOWS_MOBILE
4227
4228# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
4229    // Death test children can be terminated with _abort().  On Windows,
4230    // _abort() can show a dialog with a warning message.  This forces the
4231    // abort message to go to stderr instead.
4232    _set_error_mode(_OUT_TO_STDERR);
4233# endif
4234
4235# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
4236    // In the debug version, Visual Studio pops up a separate dialog
4237    // offering a choice to debug the aborted program. We need to suppress
4238    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
4239    // executed. Google Test will notify the user of any unexpected
4240    // failure via stderr.
4241    //
4242    // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
4243    // Users of prior VC versions shall suffer the agony and pain of
4244    // clicking through the countless debug dialogs.
4245    // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
4246    // debug mode when compiled with VC 7.1 or lower.
4247    if (!GTEST_FLAG(break_on_failure))
4248      _set_abort_behavior(
4249          0x0,                                    // Clear the following flags:
4250          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
4251# endif
4252  }
4253#endif  // GTEST_HAS_SEH
4254
4255  return internal::HandleExceptionsInMethodIfSupported(
4256      impl(),
4257      &internal::UnitTestImpl::RunAllTests,
4258      "auxiliary test code (environments or event listeners)") ? 0 : 1;
4259}
4260
4261// Returns the working directory when the first TEST() or TEST_F() was
4262// executed.
4263const char* UnitTest::original_working_dir() const {
4264  return impl_->original_working_dir_.c_str();
4265}
4266
4267// Returns the TestCase object for the test that's currently running,
4268// or NULL if no test is running.
4269const TestCase* UnitTest::current_test_case() const
4270    GTEST_LOCK_EXCLUDED_(mutex_) {
4271  internal::MutexLock lock(&mutex_);
4272  return impl_->current_test_case();
4273}
4274
4275// Returns the TestInfo object for the test that's currently running,
4276// or NULL if no test is running.
4277const TestInfo* UnitTest::current_test_info() const
4278    GTEST_LOCK_EXCLUDED_(mutex_) {
4279  internal::MutexLock lock(&mutex_);
4280  return impl_->current_test_info();
4281}
4282
4283// Returns the random seed used at the start of the current test run.
4284int UnitTest::random_seed() const { return impl_->random_seed(); }
4285
4286#if GTEST_HAS_PARAM_TEST
4287// Returns ParameterizedTestCaseRegistry object used to keep track of
4288// value-parameterized tests and instantiate and register them.
4289internal::ParameterizedTestCaseRegistry&
4290    UnitTest::parameterized_test_registry()
4291        GTEST_LOCK_EXCLUDED_(mutex_) {
4292  return impl_->parameterized_test_registry();
4293}
4294#endif  // GTEST_HAS_PARAM_TEST
4295
4296// Creates an empty UnitTest.
4297UnitTest::UnitTest() {
4298  impl_ = new internal::UnitTestImpl(this);
4299}
4300
4301// Destructor of UnitTest.
4302UnitTest::~UnitTest() {
4303  delete impl_;
4304}
4305
4306// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
4307// Google Test trace stack.
4308void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
4309    GTEST_LOCK_EXCLUDED_(mutex_) {
4310  internal::MutexLock lock(&mutex_);
4311  impl_->gtest_trace_stack().push_back(trace);
4312}
4313
4314// Pops a trace from the per-thread Google Test trace stack.
4315void UnitTest::PopGTestTrace()
4316    GTEST_LOCK_EXCLUDED_(mutex_) {
4317  internal::MutexLock lock(&mutex_);
4318  impl_->gtest_trace_stack().pop_back();
4319}
4320
4321namespace internal {
4322
4323UnitTestImpl::UnitTestImpl(UnitTest* parent)
4324    : parent_(parent),
4325      GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
4326      default_global_test_part_result_reporter_(this),
4327      default_per_thread_test_part_result_reporter_(this),
4328      GTEST_DISABLE_MSC_WARNINGS_POP_()
4329      global_test_part_result_repoter_(
4330          &default_global_test_part_result_reporter_),
4331      per_thread_test_part_result_reporter_(
4332          &default_per_thread_test_part_result_reporter_),
4333#if GTEST_HAS_PARAM_TEST
4334      parameterized_test_registry_(),
4335      parameterized_tests_registered_(false),
4336#endif  // GTEST_HAS_PARAM_TEST
4337      last_death_test_case_(-1),
4338      current_test_case_(NULL),
4339      current_test_info_(NULL),
4340      ad_hoc_test_result_(),
4341      os_stack_trace_getter_(NULL),
4342      post_flag_parse_init_performed_(false),
4343      random_seed_(0),  // Will be overridden by the flag before first use.
4344      random_(0),  // Will be reseeded before first use.
4345      start_timestamp_(0),
4346      elapsed_time_(0),
4347#if GTEST_HAS_DEATH_TEST
4348      death_test_factory_(new DefaultDeathTestFactory),
4349#endif
4350      // Will be overridden by the flag before first use.
4351      catch_exceptions_(false) {
4352  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
4353}
4354
4355UnitTestImpl::~UnitTestImpl() {
4356  // Deletes every TestCase.
4357  ForEach(test_cases_, internal::Delete<TestCase>);
4358
4359  // Deletes every Environment.
4360  ForEach(environments_, internal::Delete<Environment>);
4361
4362  delete os_stack_trace_getter_;
4363}
4364
4365// Adds a TestProperty to the current TestResult object when invoked in a
4366// context of a test, to current test case's ad_hoc_test_result when invoke
4367// from SetUpTestCase/TearDownTestCase, or to the global property set
4368// otherwise.  If the result already contains a property with the same key,
4369// the value will be updated.
4370void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
4371  std::string xml_element;
4372  TestResult* test_result;  // TestResult appropriate for property recording.
4373
4374  if (current_test_info_ != NULL) {
4375    xml_element = "testcase";
4376    test_result = &(current_test_info_->result_);
4377  } else if (current_test_case_ != NULL) {
4378    xml_element = "testsuite";
4379    test_result = &(current_test_case_->ad_hoc_test_result_);
4380  } else {
4381    xml_element = "testsuites";
4382    test_result = &ad_hoc_test_result_;
4383  }
4384  test_result->RecordProperty(xml_element, test_property);
4385}
4386
4387#if GTEST_HAS_DEATH_TEST
4388// Disables event forwarding if the control is currently in a death test
4389// subprocess. Must not be called before InitGoogleTest.
4390void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
4391  if (internal_run_death_test_flag_.get() != NULL)
4392    listeners()->SuppressEventForwarding();
4393}
4394#endif  // GTEST_HAS_DEATH_TEST
4395
4396// Initializes event listeners performing XML output as specified by
4397// UnitTestOptions. Must not be called before InitGoogleTest.
4398void UnitTestImpl::ConfigureXmlOutput() {
4399  const std::string& output_format = UnitTestOptions::GetOutputFormat();
4400  if (output_format == "xml") {
4401    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
4402        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
4403  } else if (output_format != "") {
4404    printf("WARNING: unrecognized output format \"%s\" ignored.\n",
4405           output_format.c_str());
4406    fflush(stdout);
4407  }
4408}
4409
4410#if GTEST_CAN_STREAM_RESULTS_
4411// Initializes event listeners for streaming test results in string form.
4412// Must not be called before InitGoogleTest.
4413void UnitTestImpl::ConfigureStreamingOutput() {
4414  const std::string& target = GTEST_FLAG(stream_result_to);
4415  if (!target.empty()) {
4416    const size_t pos = target.find(':');
4417    if (pos != std::string::npos) {
4418      listeners()->Append(new StreamingListener(target.substr(0, pos),
4419                                                target.substr(pos+1)));
4420    } else {
4421      printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
4422             target.c_str());
4423      fflush(stdout);
4424    }
4425  }
4426}
4427#endif  // GTEST_CAN_STREAM_RESULTS_
4428
4429// Performs initialization dependent upon flag values obtained in
4430// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
4431// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
4432// this function is also called from RunAllTests.  Since this function can be
4433// called more than once, it has to be idempotent.
4434void UnitTestImpl::PostFlagParsingInit() {
4435  // Ensures that this function does not execute more than once.
4436  if (!post_flag_parse_init_performed_) {
4437    post_flag_parse_init_performed_ = true;
4438
4439#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4440    // Register to send notifications about key process state changes.
4441    listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
4442#endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4443
4444#if GTEST_HAS_DEATH_TEST
4445    InitDeathTestSubprocessControlInfo();
4446    SuppressTestEventsIfInSubprocess();
4447#endif  // GTEST_HAS_DEATH_TEST
4448
4449    // Registers parameterized tests. This makes parameterized tests
4450    // available to the UnitTest reflection API without running
4451    // RUN_ALL_TESTS.
4452    RegisterParameterizedTests();
4453
4454    // Configures listeners for XML output. This makes it possible for users
4455    // to shut down the default XML output before invoking RUN_ALL_TESTS.
4456    ConfigureXmlOutput();
4457
4458#if GTEST_CAN_STREAM_RESULTS_
4459    // Configures listeners for streaming test results to the specified server.
4460    ConfigureStreamingOutput();
4461#endif  // GTEST_CAN_STREAM_RESULTS_
4462  }
4463}
4464
4465// A predicate that checks the name of a TestCase against a known
4466// value.
4467//
4468// This is used for implementation of the UnitTest class only.  We put
4469// it in the anonymous namespace to prevent polluting the outer
4470// namespace.
4471//
4472// TestCaseNameIs is copyable.
4473class TestCaseNameIs {
4474 public:
4475  // Constructor.
4476  explicit TestCaseNameIs(const std::string& name)
4477      : name_(name) {}
4478
4479  // Returns true iff the name of test_case matches name_.
4480  bool operator()(const TestCase* test_case) const {
4481    return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
4482  }
4483
4484 private:
4485  std::string name_;
4486};
4487
4488// Finds and returns a TestCase with the given name.  If one doesn't
4489// exist, creates one and returns it.  It's the CALLER'S
4490// RESPONSIBILITY to ensure that this function is only called WHEN THE
4491// TESTS ARE NOT SHUFFLED.
4492//
4493// Arguments:
4494//
4495//   test_case_name: name of the test case
4496//   type_param:     the name of the test case's type parameter, or NULL if
4497//                   this is not a typed or a type-parameterized test case.
4498//   set_up_tc:      pointer to the function that sets up the test case
4499//   tear_down_tc:   pointer to the function that tears down the test case
4500TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
4501                                    const char* type_param,
4502                                    Test::SetUpTestCaseFunc set_up_tc,
4503                                    Test::TearDownTestCaseFunc tear_down_tc) {
4504  // Can we find a TestCase with the given name?
4505  const std::vector<TestCase*>::const_iterator test_case =
4506      std::find_if(test_cases_.begin(), test_cases_.end(),
4507                   TestCaseNameIs(test_case_name));
4508
4509  if (test_case != test_cases_.end())
4510    return *test_case;
4511
4512  // No.  Let's create one.
4513  TestCase* const new_test_case =
4514      new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
4515
4516  // Is this a death test case?
4517  if (internal::UnitTestOptions::MatchesFilter(test_case_name,
4518                                               kDeathTestCaseFilter)) {
4519    // Yes.  Inserts the test case after the last death test case
4520    // defined so far.  This only works when the test cases haven't
4521    // been shuffled.  Otherwise we may end up running a death test
4522    // after a non-death test.
4523    ++last_death_test_case_;
4524    test_cases_.insert(test_cases_.begin() + last_death_test_case_,
4525                       new_test_case);
4526  } else {
4527    // No.  Appends to the end of the list.
4528    test_cases_.push_back(new_test_case);
4529  }
4530
4531  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
4532  return new_test_case;
4533}
4534
4535// Helpers for setting up / tearing down the given environment.  They
4536// are for use in the ForEach() function.
4537static void SetUpEnvironment(Environment* env) { env->SetUp(); }
4538static void TearDownEnvironment(Environment* env) { env->TearDown(); }
4539
4540// Runs all tests in this UnitTest object, prints the result, and
4541// returns true if all tests are successful.  If any exception is
4542// thrown during a test, the test is considered to be failed, but the
4543// rest of the tests will still be run.
4544//
4545// When parameterized tests are enabled, it expands and registers
4546// parameterized tests first in RegisterParameterizedTests().
4547// All other functions called from RunAllTests() may safely assume that
4548// parameterized tests are ready to be counted and run.
4549bool UnitTestImpl::RunAllTests() {
4550  // Makes sure InitGoogleTest() was called.
4551  if (!GTestIsInitialized()) {
4552    printf("%s",
4553           "\nThis test program did NOT call ::testing::InitGoogleTest "
4554           "before calling RUN_ALL_TESTS().  Please fix it.\n");
4555    return false;
4556  }
4557
4558  // Do not run any test if the --help flag was specified.
4559  if (g_help_flag)
4560    return true;
4561
4562  // Repeats the call to the post-flag parsing initialization in case the
4563  // user didn't call InitGoogleTest.
4564  PostFlagParsingInit();
4565
4566  // Even if sharding is not on, test runners may want to use the
4567  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
4568  // protocol.
4569  internal::WriteToShardStatusFileIfNeeded();
4570
4571  // True iff we are in a subprocess for running a thread-safe-style
4572  // death test.
4573  bool in_subprocess_for_death_test = false;
4574
4575#if GTEST_HAS_DEATH_TEST
4576  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
4577# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
4578  if (in_subprocess_for_death_test) {
4579    GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
4580  }
4581# endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
4582#endif  // GTEST_HAS_DEATH_TEST
4583
4584  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
4585                                        in_subprocess_for_death_test);
4586
4587  // Compares the full test names with the filter to decide which
4588  // tests to run.
4589  const bool has_tests_to_run = FilterTests(should_shard
4590                                              ? HONOR_SHARDING_PROTOCOL
4591                                              : IGNORE_SHARDING_PROTOCOL) > 0;
4592
4593  // Lists the tests and exits if the --gtest_list_tests flag was specified.
4594  if (GTEST_FLAG(list_tests)) {
4595    // This must be called *after* FilterTests() has been called.
4596    ListTestsMatchingFilter();
4597    return true;
4598  }
4599
4600  random_seed_ = GTEST_FLAG(shuffle) ?
4601      GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
4602
4603  // True iff at least one test has failed.
4604  bool failed = false;
4605
4606  TestEventListener* repeater = listeners()->repeater();
4607
4608  start_timestamp_ = GetTimeInMillis();
4609  repeater->OnTestProgramStart(*parent_);
4610
4611  // How many times to repeat the tests?  We don't want to repeat them
4612  // when we are inside the subprocess of a death test.
4613  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
4614  // Repeats forever if the repeat count is negative.
4615  const bool forever = repeat < 0;
4616  for (int i = 0; forever || i != repeat; i++) {
4617    // We want to preserve failures generated by ad-hoc test
4618    // assertions executed before RUN_ALL_TESTS().
4619    ClearNonAdHocTestResult();
4620
4621    const TimeInMillis start = GetTimeInMillis();
4622
4623    // Shuffles test cases and tests if requested.
4624    if (has_tests_to_run && GTEST_FLAG(shuffle)) {
4625      random()->Reseed(random_seed_);
4626      // This should be done before calling OnTestIterationStart(),
4627      // such that a test event listener can see the actual test order
4628      // in the event.
4629      ShuffleTests();
4630    }
4631
4632    // Tells the unit test event listeners that the tests are about to start.
4633    repeater->OnTestIterationStart(*parent_, i);
4634
4635    // Runs each test case if there is at least one test to run.
4636    if (has_tests_to_run) {
4637      // Sets up all environments beforehand.
4638      repeater->OnEnvironmentsSetUpStart(*parent_);
4639      ForEach(environments_, SetUpEnvironment);
4640      repeater->OnEnvironmentsSetUpEnd(*parent_);
4641
4642      // Runs the tests only if there was no fatal failure during global
4643      // set-up.
4644      if (!Test::HasFatalFailure()) {
4645        for (int test_index = 0; test_index < total_test_case_count();
4646             test_index++) {
4647          GetMutableTestCase(test_index)->Run();
4648        }
4649      }
4650
4651      // Tears down all environments in reverse order afterwards.
4652      repeater->OnEnvironmentsTearDownStart(*parent_);
4653      std::for_each(environments_.rbegin(), environments_.rend(),
4654                    TearDownEnvironment);
4655      repeater->OnEnvironmentsTearDownEnd(*parent_);
4656    }
4657
4658    elapsed_time_ = GetTimeInMillis() - start;
4659
4660    // Tells the unit test event listener that the tests have just finished.
4661    repeater->OnTestIterationEnd(*parent_, i);
4662
4663    // Gets the result and clears it.
4664    if (!Passed()) {
4665      failed = true;
4666    }
4667
4668    // Restores the original test order after the iteration.  This
4669    // allows the user to quickly repro a failure that happens in the
4670    // N-th iteration without repeating the first (N - 1) iterations.
4671    // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4672    // case the user somehow changes the value of the flag somewhere
4673    // (it's always safe to unshuffle the tests).
4674    UnshuffleTests();
4675
4676    if (GTEST_FLAG(shuffle)) {
4677      // Picks a new random seed for each iteration.
4678      random_seed_ = GetNextRandomSeed(random_seed_);
4679    }
4680  }
4681
4682  repeater->OnTestProgramEnd(*parent_);
4683
4684  return !failed;
4685}
4686
4687// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4688// if the variable is present. If a file already exists at this location, this
4689// function will write over it. If the variable is present, but the file cannot
4690// be created, prints an error and exits.
4691void WriteToShardStatusFileIfNeeded() {
4692  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
4693  if (test_shard_file != NULL) {
4694    FILE* const file = posix::FOpen(test_shard_file, "w");
4695    if (file == NULL) {
4696      ColoredPrintf(COLOR_RED,
4697                    "Could not write to the test shard status file \"%s\" "
4698                    "specified by the %s environment variable.\n",
4699                    test_shard_file, kTestShardStatusFile);
4700      fflush(stdout);
4701      exit(EXIT_FAILURE);
4702    }
4703    fclose(file);
4704  }
4705}
4706
4707// Checks whether sharding is enabled by examining the relevant
4708// environment variable values. If the variables are present,
4709// but inconsistent (i.e., shard_index >= total_shards), prints
4710// an error and exits. If in_subprocess_for_death_test, sharding is
4711// disabled because it must only be applied to the original test
4712// process. Otherwise, we could filter out death tests we intended to execute.
4713bool ShouldShard(const char* total_shards_env,
4714                 const char* shard_index_env,
4715                 bool in_subprocess_for_death_test) {
4716  if (in_subprocess_for_death_test) {
4717    return false;
4718  }
4719
4720  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4721  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4722
4723  if (total_shards == -1 && shard_index == -1) {
4724    return false;
4725  } else if (total_shards == -1 && shard_index != -1) {
4726    const Message msg = Message()
4727      << "Invalid environment variables: you have "
4728      << kTestShardIndex << " = " << shard_index
4729      << ", but have left " << kTestTotalShards << " unset.\n";
4730    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4731    fflush(stdout);
4732    exit(EXIT_FAILURE);
4733  } else if (total_shards != -1 && shard_index == -1) {
4734    const Message msg = Message()
4735      << "Invalid environment variables: you have "
4736      << kTestTotalShards << " = " << total_shards
4737      << ", but have left " << kTestShardIndex << " unset.\n";
4738    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4739    fflush(stdout);
4740    exit(EXIT_FAILURE);
4741  } else if (shard_index < 0 || shard_index >= total_shards) {
4742    const Message msg = Message()
4743      << "Invalid environment variables: we require 0 <= "
4744      << kTestShardIndex << " < " << kTestTotalShards
4745      << ", but you have " << kTestShardIndex << "=" << shard_index
4746      << ", " << kTestTotalShards << "=" << total_shards << ".\n";
4747    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4748    fflush(stdout);
4749    exit(EXIT_FAILURE);
4750  }
4751
4752  return total_shards > 1;
4753}
4754
4755// Parses the environment variable var as an Int32. If it is unset,
4756// returns default_val. If it is not an Int32, prints an error
4757// and aborts.
4758Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
4759  const char* str_val = posix::GetEnv(var);
4760  if (str_val == NULL) {
4761    return default_val;
4762  }
4763
4764  Int32 result;
4765  if (!ParseInt32(Message() << "The value of environment variable " << var,
4766                  str_val, &result)) {
4767    exit(EXIT_FAILURE);
4768  }
4769  return result;
4770}
4771
4772// Given the total number of shards, the shard index, and the test id,
4773// returns true iff the test should be run on this shard. The test id is
4774// some arbitrary but unique non-negative integer assigned to each test
4775// method. Assumes that 0 <= shard_index < total_shards.
4776bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4777  return (test_id % total_shards) == shard_index;
4778}
4779
4780// Compares the name of each test with the user-specified filter to
4781// decide whether the test should be run, then records the result in
4782// each TestCase and TestInfo object.
4783// If shard_tests == true, further filters tests based on sharding
4784// variables in the environment - see
4785// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
4786// Returns the number of tests that should run.
4787int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4788  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4789      Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4790  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4791      Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4792
4793  // num_runnable_tests are the number of tests that will
4794  // run across all shards (i.e., match filter and are not disabled).
4795  // num_selected_tests are the number of tests to be run on
4796  // this shard.
4797  int num_runnable_tests = 0;
4798  int num_selected_tests = 0;
4799  for (size_t i = 0; i < test_cases_.size(); i++) {
4800    TestCase* const test_case = test_cases_[i];
4801    const std::string &test_case_name = test_case->name();
4802    test_case->set_should_run(false);
4803
4804    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4805      TestInfo* const test_info = test_case->test_info_list()[j];
4806      const std::string test_name(test_info->name());
4807      // A test is disabled if test case name or test name matches
4808      // kDisableTestFilter.
4809      const bool is_disabled =
4810          internal::UnitTestOptions::MatchesFilter(test_case_name,
4811                                                   kDisableTestFilter) ||
4812          internal::UnitTestOptions::MatchesFilter(test_name,
4813                                                   kDisableTestFilter);
4814      test_info->is_disabled_ = is_disabled;
4815
4816      const bool matches_filter =
4817          internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4818                                                       test_name);
4819      test_info->matches_filter_ = matches_filter;
4820
4821      const bool is_runnable =
4822          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4823          matches_filter;
4824
4825      const bool is_selected = is_runnable &&
4826          (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4827           ShouldRunTestOnShard(total_shards, shard_index,
4828                                num_runnable_tests));
4829
4830      num_runnable_tests += is_runnable;
4831      num_selected_tests += is_selected;
4832
4833      test_info->should_run_ = is_selected;
4834      test_case->set_should_run(test_case->should_run() || is_selected);
4835    }
4836  }
4837  return num_selected_tests;
4838}
4839
4840// Prints the given C-string on a single line by replacing all '\n'
4841// characters with string "\\n".  If the output takes more than
4842// max_length characters, only prints the first max_length characters
4843// and "...".
4844static void PrintOnOneLine(const char* str, int max_length) {
4845  if (str != NULL) {
4846    for (int i = 0; *str != '\0'; ++str) {
4847      if (i >= max_length) {
4848        printf("...");
4849        break;
4850      }
4851      if (*str == '\n') {
4852        printf("\\n");
4853        i += 2;
4854      } else {
4855        printf("%c", *str);
4856        ++i;
4857      }
4858    }
4859  }
4860}
4861
4862// Prints the names of the tests matching the user-specified filter flag.
4863void UnitTestImpl::ListTestsMatchingFilter() {
4864  // Print at most this many characters for each type/value parameter.
4865  const int kMaxParamLength = 250;
4866
4867  for (size_t i = 0; i < test_cases_.size(); i++) {
4868    const TestCase* const test_case = test_cases_[i];
4869    bool printed_test_case_name = false;
4870
4871    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4872      const TestInfo* const test_info =
4873          test_case->test_info_list()[j];
4874      if (test_info->matches_filter_) {
4875        if (!printed_test_case_name) {
4876          printed_test_case_name = true;
4877          printf("%s.", test_case->name());
4878          if (test_case->type_param() != NULL) {
4879            printf("  # %s = ", kTypeParamLabel);
4880            // We print the type parameter on a single line to make
4881            // the output easy to parse by a program.
4882            PrintOnOneLine(test_case->type_param(), kMaxParamLength);
4883          }
4884          printf("\n");
4885        }
4886        printf("  %s", test_info->name());
4887        if (test_info->value_param() != NULL) {
4888          printf("  # %s = ", kValueParamLabel);
4889          // We print the value parameter on a single line to make the
4890          // output easy to parse by a program.
4891          PrintOnOneLine(test_info->value_param(), kMaxParamLength);
4892        }
4893        printf("\n");
4894      }
4895    }
4896  }
4897  fflush(stdout);
4898}
4899
4900// Sets the OS stack trace getter.
4901//
4902// Does nothing if the input and the current OS stack trace getter are
4903// the same; otherwise, deletes the old getter and makes the input the
4904// current getter.
4905void UnitTestImpl::set_os_stack_trace_getter(
4906    OsStackTraceGetterInterface* getter) {
4907  if (os_stack_trace_getter_ != getter) {
4908    delete os_stack_trace_getter_;
4909    os_stack_trace_getter_ = getter;
4910  }
4911}
4912
4913// Returns the current OS stack trace getter if it is not NULL;
4914// otherwise, creates an OsStackTraceGetter, makes it the current
4915// getter, and returns it.
4916OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4917  if (os_stack_trace_getter_ == NULL) {
4918#ifdef GTEST_OS_STACK_TRACE_GETTER_
4919    os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
4920#else
4921    os_stack_trace_getter_ = new OsStackTraceGetter;
4922#endif  // GTEST_OS_STACK_TRACE_GETTER_
4923  }
4924
4925  return os_stack_trace_getter_;
4926}
4927
4928// Returns the TestResult for the test that's currently running, or
4929// the TestResult for the ad hoc test if no test is running.
4930TestResult* UnitTestImpl::current_test_result() {
4931  return current_test_info_ ?
4932      &(current_test_info_->result_) : &ad_hoc_test_result_;
4933}
4934
4935// Shuffles all test cases, and the tests within each test case,
4936// making sure that death tests are still run first.
4937void UnitTestImpl::ShuffleTests() {
4938  // Shuffles the death test cases.
4939  ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
4940
4941  // Shuffles the non-death test cases.
4942  ShuffleRange(random(), last_death_test_case_ + 1,
4943               static_cast<int>(test_cases_.size()), &test_case_indices_);
4944
4945  // Shuffles the tests inside each test case.
4946  for (size_t i = 0; i < test_cases_.size(); i++) {
4947    test_cases_[i]->ShuffleTests(random());
4948  }
4949}
4950
4951// Restores the test cases and tests to their order before the first shuffle.
4952void UnitTestImpl::UnshuffleTests() {
4953  for (size_t i = 0; i < test_cases_.size(); i++) {
4954    // Unshuffles the tests in each test case.
4955    test_cases_[i]->UnshuffleTests();
4956    // Resets the index of each test case.
4957    test_case_indices_[i] = static_cast<int>(i);
4958  }
4959}
4960
4961// Returns the current OS stack trace as an std::string.
4962//
4963// The maximum number of stack frames to be included is specified by
4964// the gtest_stack_trace_depth flag.  The skip_count parameter
4965// specifies the number of top frames to be skipped, which doesn't
4966// count against the number of frames to be included.
4967//
4968// For example, if Foo() calls Bar(), which in turn calls
4969// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4970// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4971std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4972                                            int skip_count) {
4973  // We pass skip_count + 1 to skip this wrapper function in addition
4974  // to what the user really wants to skip.
4975  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4976}
4977
4978// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
4979// suppress unreachable code warnings.
4980namespace {
4981class ClassUniqueToAlwaysTrue {};
4982}
4983
4984bool IsTrue(bool condition) { return condition; }
4985
4986bool AlwaysTrue() {
4987#if GTEST_HAS_EXCEPTIONS
4988  // This condition is always false so AlwaysTrue() never actually throws,
4989  // but it makes the compiler think that it may throw.
4990  if (IsTrue(false))
4991    throw ClassUniqueToAlwaysTrue();
4992#endif  // GTEST_HAS_EXCEPTIONS
4993  return true;
4994}
4995
4996// If *pstr starts with the given prefix, modifies *pstr to be right
4997// past the prefix and returns true; otherwise leaves *pstr unchanged
4998// and returns false.  None of pstr, *pstr, and prefix can be NULL.
4999bool SkipPrefix(const char* prefix, const char** pstr) {
5000  const size_t prefix_len = strlen(prefix);
5001  if (strncmp(*pstr, prefix, prefix_len) == 0) {
5002    *pstr += prefix_len;
5003    return true;
5004  }
5005  return false;
5006}
5007
5008// Parses a string as a command line flag.  The string should have
5009// the format "--flag=value".  When def_optional is true, the "=value"
5010// part can be omitted.
5011//
5012// Returns the value of the flag, or NULL if the parsing failed.
5013const char* ParseFlagValue(const char* str,
5014                           const char* flag,
5015                           bool def_optional) {
5016  // str and flag must not be NULL.
5017  if (str == NULL || flag == NULL) return NULL;
5018
5019  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5020  const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
5021  const size_t flag_len = flag_str.length();
5022  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5023
5024  // Skips the flag name.
5025  const char* flag_end = str + flag_len;
5026
5027  // When def_optional is true, it's OK to not have a "=value" part.
5028  if (def_optional && (flag_end[0] == '\0')) {
5029    return flag_end;
5030  }
5031
5032  // If def_optional is true and there are more characters after the
5033  // flag name, or if def_optional is false, there must be a '=' after
5034  // the flag name.
5035  if (flag_end[0] != '=') return NULL;
5036
5037  // Returns the string after "=".
5038  return flag_end + 1;
5039}
5040
5041// Parses a string for a bool flag, in the form of either
5042// "--flag=value" or "--flag".
5043//
5044// In the former case, the value is taken as true as long as it does
5045// not start with '0', 'f', or 'F'.
5046//
5047// In the latter case, the value is taken as true.
5048//
5049// On success, stores the value of the flag in *value, and returns
5050// true.  On failure, returns false without changing *value.
5051bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5052  // Gets the value of the flag as a string.
5053  const char* const value_str = ParseFlagValue(str, flag, true);
5054
5055  // Aborts if the parsing failed.
5056  if (value_str == NULL) return false;
5057
5058  // Converts the string value to a bool.
5059  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5060  return true;
5061}
5062
5063// Parses a string for an Int32 flag, in the form of
5064// "--flag=value".
5065//
5066// On success, stores the value of the flag in *value, and returns
5067// true.  On failure, returns false without changing *value.
5068bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5069  // Gets the value of the flag as a string.
5070  const char* const value_str = ParseFlagValue(str, flag, false);
5071
5072  // Aborts if the parsing failed.
5073  if (value_str == NULL) return false;
5074
5075  // Sets *value to the value of the flag.
5076  return ParseInt32(Message() << "The value of flag --" << flag,
5077                    value_str, value);
5078}
5079
5080// Parses a string for a string flag, in the form of
5081// "--flag=value".
5082//
5083// On success, stores the value of the flag in *value, and returns
5084// true.  On failure, returns false without changing *value.
5085bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
5086  // Gets the value of the flag as a string.
5087  const char* const value_str = ParseFlagValue(str, flag, false);
5088
5089  // Aborts if the parsing failed.
5090  if (value_str == NULL) return false;
5091
5092  // Sets *value to the value of the flag.
5093  *value = value_str;
5094  return true;
5095}
5096
5097// Determines whether a string has a prefix that Google Test uses for its
5098// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5099// If Google Test detects that a command line flag has its prefix but is not
5100// recognized, it will print its help message. Flags starting with
5101// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5102// internal flags and do not trigger the help message.
5103static bool HasGoogleTestFlagPrefix(const char* str) {
5104  return (SkipPrefix("--", &str) ||
5105          SkipPrefix("-", &str) ||
5106          SkipPrefix("/", &str)) &&
5107         !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5108         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5109          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5110}
5111
5112// Prints a string containing code-encoded text.  The following escape
5113// sequences can be used in the string to control the text color:
5114//
5115//   @@    prints a single '@' character.
5116//   @R    changes the color to red.
5117//   @G    changes the color to green.
5118//   @Y    changes the color to yellow.
5119//   @D    changes to the default terminal text color.
5120//
5121// TODO(wan@google.com): Write tests for this once we add stdout
5122// capturing to Google Test.
5123static void PrintColorEncoded(const char* str) {
5124  GTestColor color = COLOR_DEFAULT;  // The current color.
5125
5126  // Conceptually, we split the string into segments divided by escape
5127  // sequences.  Then we print one segment at a time.  At the end of
5128  // each iteration, the str pointer advances to the beginning of the
5129  // next segment.
5130  for (;;) {
5131    const char* p = strchr(str, '@');
5132    if (p == NULL) {
5133      ColoredPrintf(color, "%s", str);
5134      return;
5135    }
5136
5137    ColoredPrintf(color, "%s", std::string(str, p).c_str());
5138
5139    const char ch = p[1];
5140    str = p + 2;
5141    if (ch == '@') {
5142      ColoredPrintf(color, "@");
5143    } else if (ch == 'D') {
5144      color = COLOR_DEFAULT;
5145    } else if (ch == 'R') {
5146      color = COLOR_RED;
5147    } else if (ch == 'G') {
5148      color = COLOR_GREEN;
5149    } else if (ch == 'Y') {
5150      color = COLOR_YELLOW;
5151    } else {
5152      --str;
5153    }
5154  }
5155}
5156
5157static const char kColorEncodedHelpMessage[] =
5158"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
5159"following command line flags to control its behavior:\n"
5160"\n"
5161"Test Selection:\n"
5162"  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
5163"      List the names of all tests instead of running them. The name of\n"
5164"      TEST(Foo, Bar) is \"Foo.Bar\".\n"
5165"  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
5166    "[@G-@YNEGATIVE_PATTERNS]@D\n"
5167"      Run only the tests whose name matches one of the positive patterns but\n"
5168"      none of the negative patterns. '?' matches any single character; '*'\n"
5169"      matches any substring; ':' separates two patterns.\n"
5170"  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
5171"      Run all disabled tests too.\n"
5172"\n"
5173"Test Execution:\n"
5174"  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
5175"      Run the tests repeatedly; use a negative count to repeat forever.\n"
5176"  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
5177"      Randomize tests' orders on every iteration.\n"
5178"  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
5179"      Random number seed to use for shuffling test orders (between 1 and\n"
5180"      99999, or 0 to use a seed based on the current time).\n"
5181"\n"
5182"Test Output:\n"
5183"  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
5184"      Enable/disable colored output. The default is @Gauto@D.\n"
5185"  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
5186"      Don't print the elapsed time of each test.\n"
5187"  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
5188    GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
5189"      Generate an XML report in the given directory or with the given file\n"
5190"      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
5191#if GTEST_CAN_STREAM_RESULTS_
5192"  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
5193"      Stream test results to the given server.\n"
5194#endif  // GTEST_CAN_STREAM_RESULTS_
5195"\n"
5196"Assertion Behavior:\n"
5197#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5198"  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
5199"      Set the default death test style.\n"
5200#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5201"  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
5202"      Turn assertion failures into debugger break-points.\n"
5203"  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
5204"      Turn assertion failures into C++ exceptions.\n"
5205"  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
5206"      Do not report exceptions as test failures. Instead, allow them\n"
5207"      to crash the program or throw a pop-up (on Windows).\n"
5208"\n"
5209"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
5210    "the corresponding\n"
5211"environment variable of a flag (all letters in upper-case). For example, to\n"
5212"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
5213    "color=no@D or set\n"
5214"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
5215"\n"
5216"For more information, please read the " GTEST_NAME_ " documentation at\n"
5217"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
5218"(not one in your own code or tests), please report it to\n"
5219"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
5220
5221bool ParseGoogleTestFlag(const char* const arg) {
5222  return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
5223                       &GTEST_FLAG(also_run_disabled_tests)) ||
5224      ParseBoolFlag(arg, kBreakOnFailureFlag,
5225                    &GTEST_FLAG(break_on_failure)) ||
5226      ParseBoolFlag(arg, kCatchExceptionsFlag,
5227                    &GTEST_FLAG(catch_exceptions)) ||
5228      ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
5229      ParseStringFlag(arg, kDeathTestStyleFlag,
5230                      &GTEST_FLAG(death_test_style)) ||
5231      ParseBoolFlag(arg, kDeathTestUseFork,
5232                    &GTEST_FLAG(death_test_use_fork)) ||
5233      ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
5234      ParseStringFlag(arg, kInternalRunDeathTestFlag,
5235                      &GTEST_FLAG(internal_run_death_test)) ||
5236      ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
5237      ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
5238      ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
5239      ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
5240      ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
5241      ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
5242      ParseInt32Flag(arg, kStackTraceDepthFlag,
5243                     &GTEST_FLAG(stack_trace_depth)) ||
5244      ParseStringFlag(arg, kStreamResultToFlag,
5245                      &GTEST_FLAG(stream_result_to)) ||
5246      ParseBoolFlag(arg, kThrowOnFailureFlag,
5247                    &GTEST_FLAG(throw_on_failure));
5248}
5249
5250#if GTEST_USE_OWN_FLAGFILE_FLAG_
5251void LoadFlagsFromFile(const std::string& path) {
5252  FILE* flagfile = posix::FOpen(path.c_str(), "r");
5253  if (!flagfile) {
5254    fprintf(stderr,
5255            "Unable to open file \"%s\"\n",
5256            GTEST_FLAG(flagfile).c_str());
5257    fflush(stderr);
5258    exit(EXIT_FAILURE);
5259  }
5260  std::string contents(ReadEntireFile(flagfile));
5261  posix::FClose(flagfile);
5262  std::vector<std::string> lines;
5263  SplitString(contents, '\n', &lines);
5264  for (size_t i = 0; i < lines.size(); ++i) {
5265    if (lines[i].empty())
5266      continue;
5267    if (!ParseGoogleTestFlag(lines[i].c_str()))
5268      g_help_flag = true;
5269  }
5270}
5271#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
5272
5273// Parses the command line for Google Test flags, without initializing
5274// other parts of Google Test.  The type parameter CharType can be
5275// instantiated to either char or wchar_t.
5276template <typename CharType>
5277void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
5278  for (int i = 1; i < *argc; i++) {
5279    const std::string arg_string = StreamableToString(argv[i]);
5280    const char* const arg = arg_string.c_str();
5281
5282    using internal::ParseBoolFlag;
5283    using internal::ParseInt32Flag;
5284    using internal::ParseStringFlag;
5285
5286    bool remove_flag = false;
5287    if (ParseGoogleTestFlag(arg)) {
5288      remove_flag = true;
5289#if GTEST_USE_OWN_FLAGFILE_FLAG_
5290    } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
5291      LoadFlagsFromFile(GTEST_FLAG(flagfile));
5292      remove_flag = true;
5293#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
5294    } else if (arg_string == "--help" || arg_string == "-h" ||
5295               arg_string == "-?" || arg_string == "/?" ||
5296               HasGoogleTestFlagPrefix(arg)) {
5297      // Both help flag and unrecognized Google Test flags (excluding
5298      // internal ones) trigger help display.
5299      g_help_flag = true;
5300    }
5301
5302    if (remove_flag) {
5303      // Shift the remainder of the argv list left by one.  Note
5304      // that argv has (*argc + 1) elements, the last one always being
5305      // NULL.  The following loop moves the trailing NULL element as
5306      // well.
5307      for (int j = i; j != *argc; j++) {
5308        argv[j] = argv[j + 1];
5309      }
5310
5311      // Decrements the argument count.
5312      (*argc)--;
5313
5314      // We also need to decrement the iterator as we just removed
5315      // an element.
5316      i--;
5317    }
5318  }
5319
5320  if (g_help_flag) {
5321    // We print the help here instead of in RUN_ALL_TESTS(), as the
5322    // latter may not be called at all if the user is using Google
5323    // Test with another testing framework.
5324    PrintColorEncoded(kColorEncodedHelpMessage);
5325  }
5326}
5327
5328// Parses the command line for Google Test flags, without initializing
5329// other parts of Google Test.
5330void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
5331  ParseGoogleTestFlagsOnlyImpl(argc, argv);
5332}
5333void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
5334  ParseGoogleTestFlagsOnlyImpl(argc, argv);
5335}
5336
5337// The internal implementation of InitGoogleTest().
5338//
5339// The type parameter CharType can be instantiated to either char or
5340// wchar_t.
5341template <typename CharType>
5342void InitGoogleTestImpl(int* argc, CharType** argv) {
5343  // We don't want to run the initialization code twice.
5344  if (GTestIsInitialized()) return;
5345
5346  if (*argc <= 0) return;
5347
5348  g_argvs.clear();
5349  for (int i = 0; i != *argc; i++) {
5350    g_argvs.push_back(StreamableToString(argv[i]));
5351  }
5352
5353  ParseGoogleTestFlagsOnly(argc, argv);
5354  GetUnitTestImpl()->PostFlagParsingInit();
5355}
5356
5357}  // namespace internal
5358
5359// Initializes Google Test.  This must be called before calling
5360// RUN_ALL_TESTS().  In particular, it parses a command line for the
5361// flags that Google Test recognizes.  Whenever a Google Test flag is
5362// seen, it is removed from argv, and *argc is decremented.
5363//
5364// No value is returned.  Instead, the Google Test flag variables are
5365// updated.
5366//
5367// Calling the function for the second time has no user-visible effect.
5368void InitGoogleTest(int* argc, char** argv) {
5369#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5370  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5371#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5372  internal::InitGoogleTestImpl(argc, argv);
5373#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5374}
5375
5376// This overloaded version can be used in Windows programs compiled in
5377// UNICODE mode.
5378void InitGoogleTest(int* argc, wchar_t** argv) {
5379#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5380  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5381#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5382  internal::InitGoogleTestImpl(argc, argv);
5383#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5384}
5385
5386}  // namespace testing
trunk/3rdparty/googletest/googletest/src/gtest_main.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30#include <stdio.h>
31
32#include "gtest/gtest.h"
33
34GTEST_API_ int main(int argc, char **argv) {
35  printf("Running main() from gtest_main.cc\n");
36  testing::InitGoogleTest(&argc, argv);
37  return RUN_ALL_TESTS();
38}
trunk/3rdparty/googletest/googletest/test/gtest-death-test_ex_test.cc
r0r249096
1// Copyright 2010, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31//
32// Tests that verify interaction of exceptions and death tests.
33
34#include "gtest/gtest-death-test.h"
35#include "gtest/gtest.h"
36
37#if GTEST_HAS_DEATH_TEST
38
39# if GTEST_HAS_SEH
40#  include <windows.h>          // For RaiseException().
41# endif
42
43# include "gtest/gtest-spi.h"
44
45# if GTEST_HAS_EXCEPTIONS
46
47#  include <exception>  // For std::exception.
48
49// Tests that death tests report thrown exceptions as failures and that the
50// exceptions do not escape death test macros.
51TEST(CxxExceptionDeathTest, ExceptionIsFailure) {
52  try {
53    EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, ""), "threw an exception");
54  } catch (...) {  // NOLINT
55    FAIL() << "An exception escaped a death test macro invocation "
56           << "with catch_exceptions "
57           << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
58  }
59}
60
61class TestException : public std::exception {
62 public:
63  virtual const char* what() const throw() { return "exceptional message"; }
64};
65
66TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
67  // Verifies that the exception message is quoted in the failure text.
68  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
69                          "exceptional message");
70  // Verifies that the location is mentioned in the failure text.
71  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
72                          "gtest-death-test_ex_test.cc");
73}
74# endif  // GTEST_HAS_EXCEPTIONS
75
76# if GTEST_HAS_SEH
77// Tests that enabling interception of SEH exceptions with the
78// catch_exceptions flag does not interfere with SEH exceptions being
79// treated as death by death tests.
80TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {
81  EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "")
82      << "with catch_exceptions "
83      << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
84}
85# endif
86
87#endif  // GTEST_HAS_DEATH_TEST
88
89int main(int argc, char** argv) {
90  testing::InitGoogleTest(&argc, argv);
91  testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0;
92  return RUN_ALL_TESTS();
93}
trunk/3rdparty/googletest/googletest/test/gtest-death-test_test.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for death tests.
33
34#include "gtest/gtest-death-test.h"
35#include "gtest/gtest.h"
36#include "gtest/internal/gtest-filepath.h"
37
38using testing::internal::AlwaysFalse;
39using testing::internal::AlwaysTrue;
40
41#if GTEST_HAS_DEATH_TEST
42
43# if GTEST_OS_WINDOWS
44#  include <direct.h>          // For chdir().
45# else
46#  include <unistd.h>
47#  include <sys/wait.h>        // For waitpid.
48# endif  // GTEST_OS_WINDOWS
49
50# include <limits.h>
51# include <signal.h>
52# include <stdio.h>
53
54# if GTEST_OS_LINUX
55#  include <sys/time.h>
56# endif  // GTEST_OS_LINUX
57
58# include "gtest/gtest-spi.h"
59
60// Indicates that this translation unit is part of Google Test's
61// implementation.  It must come before gtest-internal-inl.h is
62// included, or there will be a compiler error.  This trick is to
63// prevent a user from accidentally including gtest-internal-inl.h in
64// his code.
65# define GTEST_IMPLEMENTATION_ 1
66# include "src/gtest-internal-inl.h"
67# undef GTEST_IMPLEMENTATION_
68
69namespace posix = ::testing::internal::posix;
70
71using testing::Message;
72using testing::internal::DeathTest;
73using testing::internal::DeathTestFactory;
74using testing::internal::FilePath;
75using testing::internal::GetLastErrnoDescription;
76using testing::internal::GetUnitTestImpl;
77using testing::internal::InDeathTestChild;
78using testing::internal::ParseNaturalNumber;
79
80namespace testing {
81namespace internal {
82
83// A helper class whose objects replace the death test factory for a
84// single UnitTest object during their lifetimes.
85class ReplaceDeathTestFactory {
86 public:
87  explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
88      : unit_test_impl_(GetUnitTestImpl()) {
89    old_factory_ = unit_test_impl_->death_test_factory_.release();
90    unit_test_impl_->death_test_factory_.reset(new_factory);
91  }
92
93  ~ReplaceDeathTestFactory() {
94    unit_test_impl_->death_test_factory_.release();
95    unit_test_impl_->death_test_factory_.reset(old_factory_);
96  }
97 private:
98  // Prevents copying ReplaceDeathTestFactory objects.
99  ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
100  void operator=(const ReplaceDeathTestFactory&);
101
102  UnitTestImpl* unit_test_impl_;
103  DeathTestFactory* old_factory_;
104};
105
106}  // namespace internal
107}  // namespace testing
108
109void DieWithMessage(const ::std::string& message) {
110  fprintf(stderr, "%s", message.c_str());
111  fflush(stderr);  // Make sure the text is printed before the process exits.
112
113  // We call _exit() instead of exit(), as the former is a direct
114  // system call and thus safer in the presence of threads.  exit()
115  // will invoke user-defined exit-hooks, which may do dangerous
116  // things that conflict with death tests.
117  //
118  // Some compilers can recognize that _exit() never returns and issue the
119  // 'unreachable code' warning for code following this function, unless
120  // fooled by a fake condition.
121  if (AlwaysTrue())
122    _exit(1);
123}
124
125void DieInside(const ::std::string& function) {
126  DieWithMessage("death inside " + function + "().");
127}
128
129// Tests that death tests work.
130
131class TestForDeathTest : public testing::Test {
132 protected:
133  TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
134
135  virtual ~TestForDeathTest() {
136    posix::ChDir(original_dir_.c_str());
137  }
138
139  // A static member function that's expected to die.
140  static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
141
142  // A method of the test fixture that may die.
143  void MemberFunction() {
144    if (should_die_)
145      DieInside("MemberFunction");
146  }
147
148  // True iff MemberFunction() should die.
149  bool should_die_;
150  const FilePath original_dir_;
151};
152
153// A class with a member function that may die.
154class MayDie {
155 public:
156  explicit MayDie(bool should_die) : should_die_(should_die) {}
157
158  // A member function that may die.
159  void MemberFunction() const {
160    if (should_die_)
161      DieInside("MayDie::MemberFunction");
162  }
163
164 private:
165  // True iff MemberFunction() should die.
166  bool should_die_;
167};
168
169// A global function that's expected to die.
170void GlobalFunction() { DieInside("GlobalFunction"); }
171
172// A non-void function that's expected to die.
173int NonVoidFunction() {
174  DieInside("NonVoidFunction");
175  return 1;
176}
177
178// A unary function that may die.
179void DieIf(bool should_die) {
180  if (should_die)
181    DieInside("DieIf");
182}
183
184// A binary function that may die.
185bool DieIfLessThan(int x, int y) {
186  if (x < y) {
187    DieInside("DieIfLessThan");
188  }
189  return true;
190}
191
192// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
193void DeathTestSubroutine() {
194  EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
195  ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
196}
197
198// Death in dbg, not opt.
199int DieInDebugElse12(int* sideeffect) {
200  if (sideeffect) *sideeffect = 12;
201
202# ifndef NDEBUG
203
204  DieInside("DieInDebugElse12");
205
206# endif  // NDEBUG
207
208  return 12;
209}
210
211# if GTEST_OS_WINDOWS
212
213// Tests the ExitedWithCode predicate.
214TEST(ExitStatusPredicateTest, ExitedWithCode) {
215  // On Windows, the process's exit code is the same as its exit status,
216  // so the predicate just compares the its input with its parameter.
217  EXPECT_TRUE(testing::ExitedWithCode(0)(0));
218  EXPECT_TRUE(testing::ExitedWithCode(1)(1));
219  EXPECT_TRUE(testing::ExitedWithCode(42)(42));
220  EXPECT_FALSE(testing::ExitedWithCode(0)(1));
221  EXPECT_FALSE(testing::ExitedWithCode(1)(0));
222}
223
224# else
225
226// Returns the exit status of a process that calls _exit(2) with a
227// given exit code.  This is a helper function for the
228// ExitStatusPredicateTest test suite.
229static int NormalExitStatus(int exit_code) {
230  pid_t child_pid = fork();
231  if (child_pid == 0) {
232    _exit(exit_code);
233  }
234  int status;
235  waitpid(child_pid, &status, 0);
236  return status;
237}
238
239// Returns the exit status of a process that raises a given signal.
240// If the signal does not cause the process to die, then it returns
241// instead the exit status of a process that exits normally with exit
242// code 1.  This is a helper function for the ExitStatusPredicateTest
243// test suite.
244static int KilledExitStatus(int signum) {
245  pid_t child_pid = fork();
246  if (child_pid == 0) {
247    raise(signum);
248    _exit(1);
249  }
250  int status;
251  waitpid(child_pid, &status, 0);
252  return status;
253}
254
255// Tests the ExitedWithCode predicate.
256TEST(ExitStatusPredicateTest, ExitedWithCode) {
257  const int status0  = NormalExitStatus(0);
258  const int status1  = NormalExitStatus(1);
259  const int status42 = NormalExitStatus(42);
260  const testing::ExitedWithCode pred0(0);
261  const testing::ExitedWithCode pred1(1);
262  const testing::ExitedWithCode pred42(42);
263  EXPECT_PRED1(pred0,  status0);
264  EXPECT_PRED1(pred1,  status1);
265  EXPECT_PRED1(pred42, status42);
266  EXPECT_FALSE(pred0(status1));
267  EXPECT_FALSE(pred42(status0));
268  EXPECT_FALSE(pred1(status42));
269}
270
271// Tests the KilledBySignal predicate.
272TEST(ExitStatusPredicateTest, KilledBySignal) {
273  const int status_segv = KilledExitStatus(SIGSEGV);
274  const int status_kill = KilledExitStatus(SIGKILL);
275  const testing::KilledBySignal pred_segv(SIGSEGV);
276  const testing::KilledBySignal pred_kill(SIGKILL);
277  EXPECT_PRED1(pred_segv, status_segv);
278  EXPECT_PRED1(pred_kill, status_kill);
279  EXPECT_FALSE(pred_segv(status_kill));
280  EXPECT_FALSE(pred_kill(status_segv));
281}
282
283# endif  // GTEST_OS_WINDOWS
284
285// Tests that the death test macros expand to code which may or may not
286// be followed by operator<<, and that in either case the complete text
287// comprises only a single C++ statement.
288TEST_F(TestForDeathTest, SingleStatement) {
289  if (AlwaysFalse())
290    // This would fail if executed; this is a compilation test only
291    ASSERT_DEATH(return, "");
292
293  if (AlwaysTrue())
294    EXPECT_DEATH(_exit(1), "");
295  else
296    // This empty "else" branch is meant to ensure that EXPECT_DEATH
297    // doesn't expand into an "if" statement without an "else"
298    ;
299
300  if (AlwaysFalse())
301    ASSERT_DEATH(return, "") << "did not die";
302
303  if (AlwaysFalse())
304    ;
305  else
306    EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
307}
308
309void DieWithEmbeddedNul() {
310  fprintf(stderr, "Hello%cmy null world.\n", '\0');
311  fflush(stderr);
312  _exit(1);
313}
314
315# if GTEST_USES_PCRE
316// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
317// message has a NUL character in it.
318TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
319  // TODO(wan@google.com): <regex.h> doesn't support matching strings
320  // with embedded NUL characters - find a way to workaround it.
321  EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
322  ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
323}
324# endif  // GTEST_USES_PCRE
325
326// Tests that death test macros expand to code which interacts well with switch
327// statements.
328TEST_F(TestForDeathTest, SwitchStatement) {
329  // Microsoft compiler usually complains about switch statements without
330  // case labels. We suppress that warning for this test.
331  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
332
333  switch (0)
334    default:
335      ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
336
337  switch (0)
338    case 0:
339      EXPECT_DEATH(_exit(1), "") << "exit in switch case";
340
341  GTEST_DISABLE_MSC_WARNINGS_POP_()
342}
343
344// Tests that a static member function can be used in a "fast" style
345// death test.
346TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
347  testing::GTEST_FLAG(death_test_style) = "fast";
348  ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
349}
350
351// Tests that a method of the test fixture can be used in a "fast"
352// style death test.
353TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
354  testing::GTEST_FLAG(death_test_style) = "fast";
355  should_die_ = true;
356  EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
357}
358
359void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
360
361// Tests that death tests work even if the current directory has been
362// changed.
363TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
364  testing::GTEST_FLAG(death_test_style) = "fast";
365
366  ChangeToRootDir();
367  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
368
369  ChangeToRootDir();
370  ASSERT_DEATH(_exit(1), "");
371}
372
373# if GTEST_OS_LINUX
374void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
375
376// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
377void SetSigprofActionAndTimer() {
378  struct itimerval timer;
379  timer.it_interval.tv_sec = 0;
380  timer.it_interval.tv_usec = 1;
381  timer.it_value = timer.it_interval;
382  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
383  struct sigaction signal_action;
384  memset(&signal_action, 0, sizeof(signal_action));
385  sigemptyset(&signal_action.sa_mask);
386  signal_action.sa_sigaction = SigprofAction;
387  signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
388  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL));
389}
390
391// Disables ITIMER_PROF timer and ignores SIGPROF signal.
392void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
393  struct itimerval timer;
394  timer.it_interval.tv_sec = 0;
395  timer.it_interval.tv_usec = 0;
396  timer.it_value = timer.it_interval;
397  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
398  struct sigaction signal_action;
399  memset(&signal_action, 0, sizeof(signal_action));
400  sigemptyset(&signal_action.sa_mask);
401  signal_action.sa_handler = SIG_IGN;
402  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
403}
404
405// Tests that death tests work when SIGPROF handler and timer are set.
406TEST_F(TestForDeathTest, FastSigprofActionSet) {
407  testing::GTEST_FLAG(death_test_style) = "fast";
408  SetSigprofActionAndTimer();
409  EXPECT_DEATH(_exit(1), "");
410  struct sigaction old_signal_action;
411  DisableSigprofActionAndTimer(&old_signal_action);
412  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
413}
414
415TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
416  testing::GTEST_FLAG(death_test_style) = "threadsafe";
417  SetSigprofActionAndTimer();
418  EXPECT_DEATH(_exit(1), "");
419  struct sigaction old_signal_action;
420  DisableSigprofActionAndTimer(&old_signal_action);
421  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
422}
423# endif  // GTEST_OS_LINUX
424
425// Repeats a representative sample of death tests in the "threadsafe" style:
426
427TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
428  testing::GTEST_FLAG(death_test_style) = "threadsafe";
429  ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
430}
431
432TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
433  testing::GTEST_FLAG(death_test_style) = "threadsafe";
434  should_die_ = true;
435  EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
436}
437
438TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
439  testing::GTEST_FLAG(death_test_style) = "threadsafe";
440
441  for (int i = 0; i < 3; ++i)
442    EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
443}
444
445TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
446  testing::GTEST_FLAG(death_test_style) = "threadsafe";
447
448  ChangeToRootDir();
449  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
450
451  ChangeToRootDir();
452  ASSERT_DEATH(_exit(1), "");
453}
454
455TEST_F(TestForDeathTest, MixedStyles) {
456  testing::GTEST_FLAG(death_test_style) = "threadsafe";
457  EXPECT_DEATH(_exit(1), "");
458  testing::GTEST_FLAG(death_test_style) = "fast";
459  EXPECT_DEATH(_exit(1), "");
460}
461
462# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
463
464namespace {
465
466bool pthread_flag;
467
468void SetPthreadFlag() {
469  pthread_flag = true;
470}
471
472}  // namespace
473
474TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
475  if (!testing::GTEST_FLAG(death_test_use_fork)) {
476    testing::GTEST_FLAG(death_test_style) = "threadsafe";
477    pthread_flag = false;
478    ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
479    ASSERT_DEATH(_exit(1), "");
480    ASSERT_FALSE(pthread_flag);
481  }
482}
483
484# endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
485
486// Tests that a method of another class can be used in a death test.
487TEST_F(TestForDeathTest, MethodOfAnotherClass) {
488  const MayDie x(true);
489  ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
490}
491
492// Tests that a global function can be used in a death test.
493TEST_F(TestForDeathTest, GlobalFunction) {
494  EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
495}
496
497// Tests that any value convertible to an RE works as a second
498// argument to EXPECT_DEATH.
499TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
500  static const char regex_c_str[] = "GlobalFunction";
501  EXPECT_DEATH(GlobalFunction(), regex_c_str);
502
503  const testing::internal::RE regex(regex_c_str);
504  EXPECT_DEATH(GlobalFunction(), regex);
505
506# if GTEST_HAS_GLOBAL_STRING
507
508  const string regex_str(regex_c_str);
509  EXPECT_DEATH(GlobalFunction(), regex_str);
510
511# endif  // GTEST_HAS_GLOBAL_STRING
512
513# if !GTEST_USES_PCRE
514
515  const ::std::string regex_std_str(regex_c_str);
516  EXPECT_DEATH(GlobalFunction(), regex_std_str);
517
518# endif  // !GTEST_USES_PCRE
519}
520
521// Tests that a non-void function can be used in a death test.
522TEST_F(TestForDeathTest, NonVoidFunction) {
523  ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
524}
525
526// Tests that functions that take parameter(s) can be used in a death test.
527TEST_F(TestForDeathTest, FunctionWithParameter) {
528  EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
529  EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
530}
531
532// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
533TEST_F(TestForDeathTest, OutsideFixture) {
534  DeathTestSubroutine();
535}
536
537// Tests that death tests can be done inside a loop.
538TEST_F(TestForDeathTest, InsideLoop) {
539  for (int i = 0; i < 5; i++) {
540    EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
541  }
542}
543
544// Tests that a compound statement can be used in a death test.
545TEST_F(TestForDeathTest, CompoundStatement) {
546  EXPECT_DEATH({  // NOLINT
547    const int x = 2;
548    const int y = x + 1;
549    DieIfLessThan(x, y);
550  },
551  "DieIfLessThan");
552}
553
554// Tests that code that doesn't die causes a death test to fail.
555TEST_F(TestForDeathTest, DoesNotDie) {
556  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
557                          "failed to die");
558}
559
560// Tests that a death test fails when the error message isn't expected.
561TEST_F(TestForDeathTest, ErrorMessageMismatch) {
562  EXPECT_NONFATAL_FAILURE({  // NOLINT
563    EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
564  }, "died but not with expected error");
565}
566
567// On exit, *aborted will be true iff the EXPECT_DEATH() statement
568// aborted the function.
569void ExpectDeathTestHelper(bool* aborted) {
570  *aborted = true;
571  EXPECT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
572  *aborted = false;
573}
574
575// Tests that EXPECT_DEATH doesn't abort the test on failure.
576TEST_F(TestForDeathTest, EXPECT_DEATH) {
577  bool aborted = true;
578  EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
579                          "failed to die");
580  EXPECT_FALSE(aborted);
581}
582
583// Tests that ASSERT_DEATH does abort the test on failure.
584TEST_F(TestForDeathTest, ASSERT_DEATH) {
585  static bool aborted;
586  EXPECT_FATAL_FAILURE({  // NOLINT
587    aborted = true;
588    ASSERT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
589    aborted = false;
590  }, "failed to die");
591  EXPECT_TRUE(aborted);
592}
593
594// Tests that EXPECT_DEATH evaluates the arguments exactly once.
595TEST_F(TestForDeathTest, SingleEvaluation) {
596  int x = 3;
597  EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
598
599  const char* regex = "DieIf";
600  const char* regex_save = regex;
601  EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
602  EXPECT_EQ(regex_save + 1, regex);
603}
604
605// Tests that run-away death tests are reported as failures.
606TEST_F(TestForDeathTest, RunawayIsFailure) {
607  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
608                          "failed to die.");
609}
610
611// Tests that death tests report executing 'return' in the statement as
612// failure.
613TEST_F(TestForDeathTest, ReturnIsFailure) {
614  EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
615                       "illegal return in test statement.");
616}
617
618// Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
619// message to it, and in debug mode it:
620// 1. Asserts on death.
621// 2. Has no side effect.
622//
623// And in opt mode, it:
624// 1.  Has side effects but does not assert.
625TEST_F(TestForDeathTest, TestExpectDebugDeath) {
626  int sideeffect = 0;
627
628  EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
629      << "Must accept a streamed message";
630
631# ifdef NDEBUG
632
633  // Checks that the assignment occurs in opt mode (sideeffect).
634  EXPECT_EQ(12, sideeffect);
635
636# else
637
638  // Checks that the assignment does not occur in dbg mode (no sideeffect).
639  EXPECT_EQ(0, sideeffect);
640
641# endif
642}
643
644// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
645// message to it, and in debug mode it:
646// 1. Asserts on death.
647// 2. Has no side effect.
648//
649// And in opt mode, it:
650// 1.  Has side effects but does not assert.
651TEST_F(TestForDeathTest, TestAssertDebugDeath) {
652  int sideeffect = 0;
653
654  ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
655      << "Must accept a streamed message";
656
657# ifdef NDEBUG
658
659  // Checks that the assignment occurs in opt mode (sideeffect).
660  EXPECT_EQ(12, sideeffect);
661
662# else
663
664  // Checks that the assignment does not occur in dbg mode (no sideeffect).
665  EXPECT_EQ(0, sideeffect);
666
667# endif
668}
669
670# ifndef NDEBUG
671
672void ExpectDebugDeathHelper(bool* aborted) {
673  *aborted = true;
674  EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
675  *aborted = false;
676}
677
678#  if GTEST_OS_WINDOWS
679TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
680  printf("This test should be considered failing if it shows "
681         "any pop-up dialogs.\n");
682  fflush(stdout);
683
684  EXPECT_DEATH({
685    testing::GTEST_FLAG(catch_exceptions) = false;
686    abort();
687  }, "");
688}
689#  endif  // GTEST_OS_WINDOWS
690
691// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
692// the function.
693TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
694  bool aborted = true;
695  EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
696  EXPECT_FALSE(aborted);
697}
698
699void AssertDebugDeathHelper(bool* aborted) {
700  *aborted = true;
701  GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH";
702  ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "")
703      << "This is expected to fail.";
704  GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH";
705  *aborted = false;
706}
707
708// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
709// failure.
710TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
711  static bool aborted;
712  aborted = false;
713  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
714  EXPECT_TRUE(aborted);
715}
716
717TEST_F(TestForDeathTest, AssertDebugDeathAborts2) {
718  static bool aborted;
719  aborted = false;
720  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
721  EXPECT_TRUE(aborted);
722}
723
724TEST_F(TestForDeathTest, AssertDebugDeathAborts3) {
725  static bool aborted;
726  aborted = false;
727  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
728  EXPECT_TRUE(aborted);
729}
730
731TEST_F(TestForDeathTest, AssertDebugDeathAborts4) {
732  static bool aborted;
733  aborted = false;
734  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
735  EXPECT_TRUE(aborted);
736}
737
738TEST_F(TestForDeathTest, AssertDebugDeathAborts5) {
739  static bool aborted;
740  aborted = false;
741  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
742  EXPECT_TRUE(aborted);
743}
744
745TEST_F(TestForDeathTest, AssertDebugDeathAborts6) {
746  static bool aborted;
747  aborted = false;
748  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
749  EXPECT_TRUE(aborted);
750}
751
752TEST_F(TestForDeathTest, AssertDebugDeathAborts7) {
753  static bool aborted;
754  aborted = false;
755  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
756  EXPECT_TRUE(aborted);
757}
758
759TEST_F(TestForDeathTest, AssertDebugDeathAborts8) {
760  static bool aborted;
761  aborted = false;
762  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
763  EXPECT_TRUE(aborted);
764}
765
766TEST_F(TestForDeathTest, AssertDebugDeathAborts9) {
767  static bool aborted;
768  aborted = false;
769  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
770  EXPECT_TRUE(aborted);
771}
772
773TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
774  static bool aborted;
775  aborted = false;
776  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
777  EXPECT_TRUE(aborted);
778}
779
780# endif  // _NDEBUG
781
782// Tests the *_EXIT family of macros, using a variety of predicates.
783static void TestExitMacros() {
784  EXPECT_EXIT(_exit(1),  testing::ExitedWithCode(1),  "");
785  ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
786
787# if GTEST_OS_WINDOWS
788
789  // Of all signals effects on the process exit code, only those of SIGABRT
790  // are documented on Windows.
791  // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
792  EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
793
794# else
795
796  EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
797  ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
798
799  EXPECT_FATAL_FAILURE({  // NOLINT
800    ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
801      << "This failure is expected, too.";
802  }, "This failure is expected, too.");
803
804# endif  // GTEST_OS_WINDOWS
805
806  EXPECT_NONFATAL_FAILURE({  // NOLINT
807    EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
808      << "This failure is expected.";
809  }, "This failure is expected.");
810}
811
812TEST_F(TestForDeathTest, ExitMacros) {
813  TestExitMacros();
814}
815
816TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
817  testing::GTEST_FLAG(death_test_use_fork) = true;
818  TestExitMacros();
819}
820
821TEST_F(TestForDeathTest, InvalidStyle) {
822  testing::GTEST_FLAG(death_test_style) = "rococo";
823  EXPECT_NONFATAL_FAILURE({  // NOLINT
824    EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
825  }, "This failure is expected.");
826}
827
828TEST_F(TestForDeathTest, DeathTestFailedOutput) {
829  testing::GTEST_FLAG(death_test_style) = "fast";
830  EXPECT_NONFATAL_FAILURE(
831      EXPECT_DEATH(DieWithMessage("death\n"),
832                   "expected message"),
833      "Actual msg:\n"
834      "[  DEATH   ] death\n");
835}
836
837TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
838  testing::GTEST_FLAG(death_test_style) = "fast";
839  EXPECT_NONFATAL_FAILURE(
840      EXPECT_DEATH({
841          fprintf(stderr, "returning\n");
842          fflush(stderr);
843          return;
844        }, ""),
845      "    Result: illegal return in test statement.\n"
846      " Error msg:\n"
847      "[  DEATH   ] returning\n");
848}
849
850TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
851  testing::GTEST_FLAG(death_test_style) = "fast";
852  EXPECT_NONFATAL_FAILURE(
853      EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
854                  testing::ExitedWithCode(3),
855                  "expected message"),
856      "    Result: died but not with expected exit code:\n"
857      "            Exited with exit status 1\n"
858      "Actual msg:\n"
859      "[  DEATH   ] exiting with rc 1\n");
860}
861
862TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
863  testing::GTEST_FLAG(death_test_style) = "fast";
864  EXPECT_NONFATAL_FAILURE(
865      EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
866                   "line 1\nxyz\nline 3\n"),
867      "Actual msg:\n"
868      "[  DEATH   ] line 1\n"
869      "[  DEATH   ] line 2\n"
870      "[  DEATH   ] line 3\n");
871}
872
873TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
874  testing::GTEST_FLAG(death_test_style) = "fast";
875  EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
876               "line 1\nline 2\nline 3\n");
877}
878
879// A DeathTestFactory that returns MockDeathTests.
880class MockDeathTestFactory : public DeathTestFactory {
881 public:
882  MockDeathTestFactory();
883  virtual bool Create(const char* statement,
884                      const ::testing::internal::RE* regex,
885                      const char* file, int line, DeathTest** test);
886
887  // Sets the parameters for subsequent calls to Create.
888  void SetParameters(bool create, DeathTest::TestRole role,
889                     int status, bool passed);
890
891  // Accessors.
892  int AssumeRoleCalls() const { return assume_role_calls_; }
893  int WaitCalls() const { return wait_calls_; }
894  size_t PassedCalls() const { return passed_args_.size(); }
895  bool PassedArgument(int n) const { return passed_args_[n]; }
896  size_t AbortCalls() const { return abort_args_.size(); }
897  DeathTest::AbortReason AbortArgument(int n) const {
898    return abort_args_[n];
899  }
900  bool TestDeleted() const { return test_deleted_; }
901
902 private:
903  friend class MockDeathTest;
904  // If true, Create will return a MockDeathTest; otherwise it returns
905  // NULL.
906  bool create_;
907  // The value a MockDeathTest will return from its AssumeRole method.
908  DeathTest::TestRole role_;
909  // The value a MockDeathTest will return from its Wait method.
910  int status_;
911  // The value a MockDeathTest will return from its Passed method.
912  bool passed_;
913
914  // Number of times AssumeRole was called.
915  int assume_role_calls_;
916  // Number of times Wait was called.
917  int wait_calls_;
918  // The arguments to the calls to Passed since the last call to
919  // SetParameters.
920  std::vector<bool> passed_args_;
921  // The arguments to the calls to Abort since the last call to
922  // SetParameters.
923  std::vector<DeathTest::AbortReason> abort_args_;
924  // True if the last MockDeathTest returned by Create has been
925  // deleted.
926  bool test_deleted_;
927};
928
929
930// A DeathTest implementation useful in testing.  It returns values set
931// at its creation from its various inherited DeathTest methods, and
932// reports calls to those methods to its parent MockDeathTestFactory
933// object.
934class MockDeathTest : public DeathTest {
935 public:
936  MockDeathTest(MockDeathTestFactory *parent,
937                TestRole role, int status, bool passed) :
938      parent_(parent), role_(role), status_(status), passed_(passed) {
939  }
940  virtual ~MockDeathTest() {
941    parent_->test_deleted_ = true;
942  }
943  virtual TestRole AssumeRole() {
944    ++parent_->assume_role_calls_;
945    return role_;
946  }
947  virtual int Wait() {
948    ++parent_->wait_calls_;
949    return status_;
950  }
951  virtual bool Passed(bool exit_status_ok) {
952    parent_->passed_args_.push_back(exit_status_ok);
953    return passed_;
954  }
955  virtual void Abort(AbortReason reason) {
956    parent_->abort_args_.push_back(reason);
957  }
958
959 private:
960  MockDeathTestFactory* const parent_;
961  const TestRole role_;
962  const int status_;
963  const bool passed_;
964};
965
966
967// MockDeathTestFactory constructor.
968MockDeathTestFactory::MockDeathTestFactory()
969    : create_(true),
970      role_(DeathTest::OVERSEE_TEST),
971      status_(0),
972      passed_(true),
973      assume_role_calls_(0),
974      wait_calls_(0),
975      passed_args_(),
976      abort_args_() {
977}
978
979
980// Sets the parameters for subsequent calls to Create.
981void MockDeathTestFactory::SetParameters(bool create,
982                                         DeathTest::TestRole role,
983                                         int status, bool passed) {
984  create_ = create;
985  role_ = role;
986  status_ = status;
987  passed_ = passed;
988
989  assume_role_calls_ = 0;
990  wait_calls_ = 0;
991  passed_args_.clear();
992  abort_args_.clear();
993}
994
995
996// Sets test to NULL (if create_ is false) or to the address of a new
997// MockDeathTest object with parameters taken from the last call
998// to SetParameters (if create_ is true).  Always returns true.
999bool MockDeathTestFactory::Create(const char* /*statement*/,
1000                                  const ::testing::internal::RE* /*regex*/,
1001                                  const char* /*file*/,
1002                                  int /*line*/,
1003                                  DeathTest** test) {
1004  test_deleted_ = false;
1005  if (create_) {
1006    *test = new MockDeathTest(this, role_, status_, passed_);
1007  } else {
1008    *test = NULL;
1009  }
1010  return true;
1011}
1012
1013// A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
1014// It installs a MockDeathTestFactory that is used for the duration
1015// of the test case.
1016class MacroLogicDeathTest : public testing::Test {
1017 protected:
1018  static testing::internal::ReplaceDeathTestFactory* replacer_;
1019  static MockDeathTestFactory* factory_;
1020
1021  static void SetUpTestCase() {
1022    factory_ = new MockDeathTestFactory;
1023    replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
1024  }
1025
1026  static void TearDownTestCase() {
1027    delete replacer_;
1028    replacer_ = NULL;
1029    delete factory_;
1030    factory_ = NULL;
1031  }
1032
1033  // Runs a death test that breaks the rules by returning.  Such a death
1034  // test cannot be run directly from a test routine that uses a
1035  // MockDeathTest, or the remainder of the routine will not be executed.
1036  static void RunReturningDeathTest(bool* flag) {
1037    ASSERT_DEATH({  // NOLINT
1038      *flag = true;
1039      return;
1040    }, "");
1041  }
1042};
1043
1044testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
1045    = NULL;
1046MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
1047
1048
1049// Test that nothing happens when the factory doesn't return a DeathTest:
1050TEST_F(MacroLogicDeathTest, NothingHappens) {
1051  bool flag = false;
1052  factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
1053  EXPECT_DEATH(flag = true, "");
1054  EXPECT_FALSE(flag);
1055  EXPECT_EQ(0, factory_->AssumeRoleCalls());
1056  EXPECT_EQ(0, factory_->WaitCalls());
1057  EXPECT_EQ(0U, factory_->PassedCalls());
1058  EXPECT_EQ(0U, factory_->AbortCalls());
1059  EXPECT_FALSE(factory_->TestDeleted());
1060}
1061
1062// Test that the parent process doesn't run the death test code,
1063// and that the Passed method returns false when the (simulated)
1064// child process exits with status 0:
1065TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
1066  bool flag = false;
1067  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
1068  EXPECT_DEATH(flag = true, "");
1069  EXPECT_FALSE(flag);
1070  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1071  EXPECT_EQ(1, factory_->WaitCalls());
1072  ASSERT_EQ(1U, factory_->PassedCalls());
1073  EXPECT_FALSE(factory_->PassedArgument(0));
1074  EXPECT_EQ(0U, factory_->AbortCalls());
1075  EXPECT_TRUE(factory_->TestDeleted());
1076}
1077
1078// Tests that the Passed method was given the argument "true" when
1079// the (simulated) child process exits with status 1:
1080TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
1081  bool flag = false;
1082  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
1083  EXPECT_DEATH(flag = true, "");
1084  EXPECT_FALSE(flag);
1085  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1086  EXPECT_EQ(1, factory_->WaitCalls());
1087  ASSERT_EQ(1U, factory_->PassedCalls());
1088  EXPECT_TRUE(factory_->PassedArgument(0));
1089  EXPECT_EQ(0U, factory_->AbortCalls());
1090  EXPECT_TRUE(factory_->TestDeleted());
1091}
1092
1093// Tests that the (simulated) child process executes the death test
1094// code, and is aborted with the correct AbortReason if it
1095// executes a return statement.
1096TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
1097  bool flag = false;
1098  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1099  RunReturningDeathTest(&flag);
1100  EXPECT_TRUE(flag);
1101  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1102  EXPECT_EQ(0, factory_->WaitCalls());
1103  EXPECT_EQ(0U, factory_->PassedCalls());
1104  EXPECT_EQ(1U, factory_->AbortCalls());
1105  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1106            factory_->AbortArgument(0));
1107  EXPECT_TRUE(factory_->TestDeleted());
1108}
1109
1110// Tests that the (simulated) child process is aborted with the
1111// correct AbortReason if it does not die.
1112TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
1113  bool flag = false;
1114  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1115  EXPECT_DEATH(flag = true, "");
1116  EXPECT_TRUE(flag);
1117  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1118  EXPECT_EQ(0, factory_->WaitCalls());
1119  EXPECT_EQ(0U, factory_->PassedCalls());
1120  // This time there are two calls to Abort: one since the test didn't
1121  // die, and another from the ReturnSentinel when it's destroyed.  The
1122  // sentinel normally isn't destroyed if a test doesn't die, since
1123  // _exit(2) is called in that case by ForkingDeathTest, but not by
1124  // our MockDeathTest.
1125  ASSERT_EQ(2U, factory_->AbortCalls());
1126  EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
1127            factory_->AbortArgument(0));
1128  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1129            factory_->AbortArgument(1));
1130  EXPECT_TRUE(factory_->TestDeleted());
1131}
1132
1133// Tests that a successful death test does not register a successful
1134// test part.
1135TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1136  EXPECT_DEATH(_exit(1), "");
1137  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
1138}
1139
1140TEST(StreamingAssertionsDeathTest, DeathTest) {
1141  EXPECT_DEATH(_exit(1), "") << "unexpected failure";
1142  ASSERT_DEATH(_exit(1), "") << "unexpected failure";
1143  EXPECT_NONFATAL_FAILURE({  // NOLINT
1144    EXPECT_DEATH(_exit(0), "") << "expected failure";
1145  }, "expected failure");
1146  EXPECT_FATAL_FAILURE({  // NOLINT
1147    ASSERT_DEATH(_exit(0), "") << "expected failure";
1148  }, "expected failure");
1149}
1150
1151// Tests that GetLastErrnoDescription returns an empty string when the
1152// last error is 0 and non-empty string when it is non-zero.
1153TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
1154  errno = ENOENT;
1155  EXPECT_STRNE("", GetLastErrnoDescription().c_str());
1156  errno = 0;
1157  EXPECT_STREQ("", GetLastErrnoDescription().c_str());
1158}
1159
1160# if GTEST_OS_WINDOWS
1161TEST(AutoHandleTest, AutoHandleWorks) {
1162  HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1163  ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1164
1165  // Tests that the AutoHandle is correctly initialized with a handle.
1166  testing::internal::AutoHandle auto_handle(handle);
1167  EXPECT_EQ(handle, auto_handle.Get());
1168
1169  // Tests that Reset assigns INVALID_HANDLE_VALUE.
1170  // Note that this cannot verify whether the original handle is closed.
1171  auto_handle.Reset();
1172  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
1173
1174  // Tests that Reset assigns the new handle.
1175  // Note that this cannot verify whether the original handle is closed.
1176  handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1177  ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1178  auto_handle.Reset(handle);
1179  EXPECT_EQ(handle, auto_handle.Get());
1180
1181  // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
1182  testing::internal::AutoHandle auto_handle2;
1183  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
1184}
1185# endif  // GTEST_OS_WINDOWS
1186
1187# if GTEST_OS_WINDOWS
1188typedef unsigned __int64 BiggestParsable;
1189typedef signed __int64 BiggestSignedParsable;
1190# else
1191typedef unsigned long long BiggestParsable;
1192typedef signed long long BiggestSignedParsable;
1193# endif  // GTEST_OS_WINDOWS
1194
1195// We cannot use std::numeric_limits<T>::max() as it clashes with the
1196// max() macro defined by <windows.h>.
1197const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1198const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
1199
1200TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
1201  BiggestParsable result = 0;
1202
1203  // Rejects non-numbers.
1204  EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
1205
1206  // Rejects numbers with whitespace prefix.
1207  EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
1208
1209  // Rejects negative numbers.
1210  EXPECT_FALSE(ParseNaturalNumber("-123", &result));
1211
1212  // Rejects numbers starting with a plus sign.
1213  EXPECT_FALSE(ParseNaturalNumber("+123", &result));
1214  errno = 0;
1215}
1216
1217TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
1218  BiggestParsable result = 0;
1219
1220  EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
1221
1222  signed char char_result = 0;
1223  EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
1224  errno = 0;
1225}
1226
1227TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
1228  BiggestParsable result = 0;
1229
1230  result = 0;
1231  ASSERT_TRUE(ParseNaturalNumber("123", &result));
1232  EXPECT_EQ(123U, result);
1233
1234  // Check 0 as an edge case.
1235  result = 1;
1236  ASSERT_TRUE(ParseNaturalNumber("0", &result));
1237  EXPECT_EQ(0U, result);
1238
1239  result = 1;
1240  ASSERT_TRUE(ParseNaturalNumber("00000", &result));
1241  EXPECT_EQ(0U, result);
1242}
1243
1244TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
1245  Message msg;
1246  msg << kBiggestParsableMax;
1247
1248  BiggestParsable result = 0;
1249  EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
1250  EXPECT_EQ(kBiggestParsableMax, result);
1251
1252  Message msg2;
1253  msg2 << kBiggestSignedParsableMax;
1254
1255  BiggestSignedParsable signed_result = 0;
1256  EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
1257  EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
1258
1259  Message msg3;
1260  msg3 << INT_MAX;
1261
1262  int int_result = 0;
1263  EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
1264  EXPECT_EQ(INT_MAX, int_result);
1265
1266  Message msg4;
1267  msg4 << UINT_MAX;
1268
1269  unsigned int uint_result = 0;
1270  EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
1271  EXPECT_EQ(UINT_MAX, uint_result);
1272}
1273
1274TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
1275  short short_result = 0;
1276  ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
1277  EXPECT_EQ(123, short_result);
1278
1279  signed char char_result = 0;
1280  ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
1281  EXPECT_EQ(123, char_result);
1282}
1283
1284# if GTEST_OS_WINDOWS
1285TEST(EnvironmentTest, HandleFitsIntoSizeT) {
1286  // TODO(vladl@google.com): Remove this test after this condition is verified
1287  // in a static assertion in gtest-death-test.cc in the function
1288  // GetStatusFileDescriptor.
1289  ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
1290}
1291# endif  // GTEST_OS_WINDOWS
1292
1293// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
1294// failures when death tests are available on the system.
1295TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
1296  EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
1297                            "death inside CondDeathTestExpectMacro");
1298  ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
1299                            "death inside CondDeathTestAssertMacro");
1300
1301  // Empty statement will not crash, which must trigger a failure.
1302  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
1303  EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
1304}
1305
1306TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
1307  testing::GTEST_FLAG(death_test_style) = "fast";
1308  EXPECT_FALSE(InDeathTestChild());
1309  EXPECT_DEATH({
1310    fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1311    fflush(stderr);
1312    _exit(1);
1313  }, "Inside");
1314}
1315
1316TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
1317  testing::GTEST_FLAG(death_test_style) = "threadsafe";
1318  EXPECT_FALSE(InDeathTestChild());
1319  EXPECT_DEATH({
1320    fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1321    fflush(stderr);
1322    _exit(1);
1323  }, "Inside");
1324}
1325
1326#else  // !GTEST_HAS_DEATH_TEST follows
1327
1328using testing::internal::CaptureStderr;
1329using testing::internal::GetCapturedStderr;
1330
1331// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
1332// defined but do not trigger failures when death tests are not available on
1333// the system.
1334TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
1335  // Empty statement will not crash, but that should not trigger a failure
1336  // when death tests are not supported.
1337  CaptureStderr();
1338  EXPECT_DEATH_IF_SUPPORTED(;, "");
1339  std::string output = GetCapturedStderr();
1340  ASSERT_TRUE(NULL != strstr(output.c_str(),
1341                             "Death tests are not supported on this platform"));
1342  ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1343
1344  // The streamed message should not be printed as there is no test failure.
1345  CaptureStderr();
1346  EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
1347  output = GetCapturedStderr();
1348  ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1349
1350  CaptureStderr();
1351  ASSERT_DEATH_IF_SUPPORTED(;, "");  // NOLINT
1352  output = GetCapturedStderr();
1353  ASSERT_TRUE(NULL != strstr(output.c_str(),
1354                             "Death tests are not supported on this platform"));
1355  ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1356
1357  CaptureStderr();
1358  ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message";  // NOLINT
1359  output = GetCapturedStderr();
1360  ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1361}
1362
1363void FuncWithAssert(int* n) {
1364  ASSERT_DEATH_IF_SUPPORTED(return;, "");
1365  (*n)++;
1366}
1367
1368// Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
1369// function (as ASSERT_DEATH does) if death tests are not supported.
1370TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
1371  int n = 0;
1372  FuncWithAssert(&n);
1373  EXPECT_EQ(1, n);
1374}
1375
1376#endif  // !GTEST_HAS_DEATH_TEST
1377
1378// Tests that the death test macros expand to code which may or may not
1379// be followed by operator<<, and that in either case the complete text
1380// comprises only a single C++ statement.
1381//
1382// The syntax should work whether death tests are available or not.
1383TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
1384  if (AlwaysFalse())
1385    // This would fail if executed; this is a compilation test only
1386    ASSERT_DEATH_IF_SUPPORTED(return, "");
1387
1388  if (AlwaysTrue())
1389    EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
1390  else
1391    // This empty "else" branch is meant to ensure that EXPECT_DEATH
1392    // doesn't expand into an "if" statement without an "else"
1393    ;  // NOLINT
1394
1395  if (AlwaysFalse())
1396    ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
1397
1398  if (AlwaysFalse())
1399    ;  // NOLINT
1400  else
1401    EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
1402}
1403
1404// Tests that conditional death test macros expand to code which interacts
1405// well with switch statements.
1406TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
1407  // Microsoft compiler usually complains about switch statements without
1408  // case labels. We suppress that warning for this test.
1409  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
1410
1411  switch (0)
1412    default:
1413      ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
1414          << "exit in default switch handler";
1415
1416  switch (0)
1417    case 0:
1418      EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
1419
1420  GTEST_DISABLE_MSC_WARNINGS_POP_()
1421}
1422
1423// Tests that a test case whose name ends with "DeathTest" works fine
1424// on Windows.
1425TEST(NotADeathTest, Test) {
1426  SUCCEED();
1427}
trunk/3rdparty/googletest/googletest/test/gtest-filepath_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: keith.ray@gmail.com (Keith Ray)
31//
32// Google Test filepath utilities
33//
34// This file tests classes and functions used internally by
35// Google Test.  They are subject to change without notice.
36//
37// This file is #included from gtest_unittest.cc, to avoid changing
38// build or make-files for some existing Google Test clients. Do not
39// #include this file anywhere else!
40
41#include "gtest/internal/gtest-filepath.h"
42#include "gtest/gtest.h"
43
44// Indicates that this translation unit is part of Google Test's
45// implementation.  It must come before gtest-internal-inl.h is
46// included, or there will be a compiler error.  This trick is to
47// prevent a user from accidentally including gtest-internal-inl.h in
48// his code.
49#define GTEST_IMPLEMENTATION_ 1
50#include "src/gtest-internal-inl.h"
51#undef GTEST_IMPLEMENTATION_
52
53#if GTEST_OS_WINDOWS_MOBILE
54# include <windows.h>  // NOLINT
55#elif GTEST_OS_WINDOWS
56# include <direct.h>  // NOLINT
57#endif  // GTEST_OS_WINDOWS_MOBILE
58
59namespace testing {
60namespace internal {
61namespace {
62
63#if GTEST_OS_WINDOWS_MOBILE
64// TODO(wan@google.com): Move these to the POSIX adapter section in
65// gtest-port.h.
66
67// Windows CE doesn't have the remove C function.
68int remove(const char* path) {
69  LPCWSTR wpath = String::AnsiToUtf16(path);
70  int ret = DeleteFile(wpath) ? 0 : -1;
71  delete [] wpath;
72  return ret;
73}
74// Windows CE doesn't have the _rmdir C function.
75int _rmdir(const char* path) {
76  FilePath filepath(path);
77  LPCWSTR wpath = String::AnsiToUtf16(
78      filepath.RemoveTrailingPathSeparator().c_str());
79  int ret = RemoveDirectory(wpath) ? 0 : -1;
80  delete [] wpath;
81  return ret;
82}
83
84#else
85
86TEST(GetCurrentDirTest, ReturnsCurrentDir) {
87  const FilePath original_dir = FilePath::GetCurrentDir();
88  EXPECT_FALSE(original_dir.IsEmpty());
89
90  posix::ChDir(GTEST_PATH_SEP_);
91  const FilePath cwd = FilePath::GetCurrentDir();
92  posix::ChDir(original_dir.c_str());
93
94# if GTEST_OS_WINDOWS
95
96  // Skips the ":".
97  const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
98  ASSERT_TRUE(cwd_without_drive != NULL);
99  EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);
100
101# else
102
103  EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
104
105# endif
106}
107
108#endif  // GTEST_OS_WINDOWS_MOBILE
109
110TEST(IsEmptyTest, ReturnsTrueForEmptyPath) {
111  EXPECT_TRUE(FilePath("").IsEmpty());
112}
113
114TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) {
115  EXPECT_FALSE(FilePath("a").IsEmpty());
116  EXPECT_FALSE(FilePath(".").IsEmpty());
117  EXPECT_FALSE(FilePath("a/b").IsEmpty());
118  EXPECT_FALSE(FilePath("a\\b\\").IsEmpty());
119}
120
121// RemoveDirectoryName "" -> ""
122TEST(RemoveDirectoryNameTest, WhenEmptyName) {
123  EXPECT_EQ("", FilePath("").RemoveDirectoryName().string());
124}
125
126// RemoveDirectoryName "afile" -> "afile"
127TEST(RemoveDirectoryNameTest, ButNoDirectory) {
128  EXPECT_EQ("afile",
129      FilePath("afile").RemoveDirectoryName().string());
130}
131
132// RemoveDirectoryName "/afile" -> "afile"
133TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
134  EXPECT_EQ("afile",
135      FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
136}
137
138// RemoveDirectoryName "adir/" -> ""
139TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
140  EXPECT_EQ("",
141      FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
142}
143
144// RemoveDirectoryName "adir/afile" -> "afile"
145TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
146  EXPECT_EQ("afile",
147      FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
148}
149
150// RemoveDirectoryName "adir/subdir/afile" -> "afile"
151TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
152  EXPECT_EQ("afile",
153      FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
154      .RemoveDirectoryName().string());
155}
156
157#if GTEST_HAS_ALT_PATH_SEP_
158
159// Tests that RemoveDirectoryName() works with the alternate separator
160// on Windows.
161
162// RemoveDirectoryName("/afile") -> "afile"
163TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) {
164  EXPECT_EQ("afile", FilePath("/afile").RemoveDirectoryName().string());
165}
166
167// RemoveDirectoryName("adir/") -> ""
168TEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) {
169  EXPECT_EQ("", FilePath("adir/").RemoveDirectoryName().string());
170}
171
172// RemoveDirectoryName("adir/afile") -> "afile"
173TEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) {
174  EXPECT_EQ("afile", FilePath("adir/afile").RemoveDirectoryName().string());
175}
176
177// RemoveDirectoryName("adir/subdir/afile") -> "afile"
178TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {
179  EXPECT_EQ("afile",
180            FilePath("adir/subdir/afile").RemoveDirectoryName().string());
181}
182
183#endif
184
185// RemoveFileName "" -> "./"
186TEST(RemoveFileNameTest, EmptyName) {
187#if GTEST_OS_WINDOWS_MOBILE
188  // On Windows CE, we use the root as the current directory.
189  EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
190#else
191  EXPECT_EQ("." GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
192#endif
193}
194
195// RemoveFileName "adir/" -> "adir/"
196TEST(RemoveFileNameTest, ButNoFile) {
197  EXPECT_EQ("adir" GTEST_PATH_SEP_,
198      FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
199}
200
201// RemoveFileName "adir/afile" -> "adir/"
202TEST(RemoveFileNameTest, GivesDirName) {
203  EXPECT_EQ("adir" GTEST_PATH_SEP_,
204            FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveFileName().string());
205}
206
207// RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
208TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
209  EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
210      FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
211      .RemoveFileName().string());
212}
213
214// RemoveFileName "/afile" -> "/"
215TEST(RemoveFileNameTest, GivesRootDir) {
216  EXPECT_EQ(GTEST_PATH_SEP_,
217      FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
218}
219
220#if GTEST_HAS_ALT_PATH_SEP_
221
222// Tests that RemoveFileName() works with the alternate separator on
223// Windows.
224
225// RemoveFileName("adir/") -> "adir/"
226TEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) {
227  EXPECT_EQ("adir" GTEST_PATH_SEP_,
228            FilePath("adir/").RemoveFileName().string());
229}
230
231// RemoveFileName("adir/afile") -> "adir/"
232TEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) {
233  EXPECT_EQ("adir" GTEST_PATH_SEP_,
234            FilePath("adir/afile").RemoveFileName().string());
235}
236
237// RemoveFileName("adir/subdir/afile") -> "adir/subdir/"
238TEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) {
239  EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
240            FilePath("adir/subdir/afile").RemoveFileName().string());
241}
242
243// RemoveFileName("/afile") -> "\"
244TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
245  EXPECT_EQ(GTEST_PATH_SEP_, FilePath("/afile").RemoveFileName().string());
246}
247
248#endif
249
250TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
251  FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
252      0, "xml");
253  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
254}
255
256TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
257  FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
258      12, "xml");
259  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
260}
261
262TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
263  FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
264      FilePath("bar"), 0, "xml");
265  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
266}
267
268TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
269  FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
270      FilePath("bar"), 12, "xml");
271  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
272}
273
274TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
275  FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
276      0, "xml");
277  EXPECT_EQ("bar.xml", actual.string());
278}
279
280TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
281  FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
282      14, "xml");
283  EXPECT_EQ("bar_14.xml", actual.string());
284}
285
286TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
287  FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
288                                          FilePath("bar.xml"));
289  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
290}
291
292TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
293  FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
294                                          FilePath("bar.xml"));
295  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
296}
297
298TEST(ConcatPathsTest, Path1BeingEmpty) {
299  FilePath actual = FilePath::ConcatPaths(FilePath(""),
300                                          FilePath("bar.xml"));
301  EXPECT_EQ("bar.xml", actual.string());
302}
303
304TEST(ConcatPathsTest, Path2BeingEmpty) {
305  FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath(""));
306  EXPECT_EQ("foo" GTEST_PATH_SEP_, actual.string());
307}
308
309TEST(ConcatPathsTest, BothPathBeingEmpty) {
310  FilePath actual = FilePath::ConcatPaths(FilePath(""),
311                                          FilePath(""));
312  EXPECT_EQ("", actual.string());
313}
314
315TEST(ConcatPathsTest, Path1ContainsPathSep) {
316  FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_ "bar"),
317                                          FilePath("foobar.xml"));
318  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "foobar.xml",
319            actual.string());
320}
321
322TEST(ConcatPathsTest, Path2ContainsPathSep) {
323  FilePath actual = FilePath::ConcatPaths(
324      FilePath("foo" GTEST_PATH_SEP_),
325      FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
326  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
327            actual.string());
328}
329
330TEST(ConcatPathsTest, Path2EndsWithPathSep) {
331  FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
332                                          FilePath("bar" GTEST_PATH_SEP_));
333  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
334}
335
336// RemoveTrailingPathSeparator "" -> ""
337TEST(RemoveTrailingPathSeparatorTest, EmptyString) {
338  EXPECT_EQ("", FilePath("").RemoveTrailingPathSeparator().string());
339}
340
341// RemoveTrailingPathSeparator "foo" -> "foo"
342TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
343  EXPECT_EQ("foo", FilePath("foo").RemoveTrailingPathSeparator().string());
344}
345
346// RemoveTrailingPathSeparator "foo/" -> "foo"
347TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
348  EXPECT_EQ("foo",
349      FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
350#if GTEST_HAS_ALT_PATH_SEP_
351  EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
352#endif
353}
354
355// RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/"
356TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
357  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
358            FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
359                .RemoveTrailingPathSeparator().string());
360}
361
362// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
363TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
364  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
365            FilePath("foo" GTEST_PATH_SEP_ "bar")
366                .RemoveTrailingPathSeparator().string());
367}
368
369TEST(DirectoryTest, RootDirectoryExists) {
370#if GTEST_OS_WINDOWS  // We are on Windows.
371  char current_drive[_MAX_PATH];  // NOLINT
372  current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
373  current_drive[1] = ':';
374  current_drive[2] = '\\';
375  current_drive[3] = '\0';
376  EXPECT_TRUE(FilePath(current_drive).DirectoryExists());
377#else
378  EXPECT_TRUE(FilePath("/").DirectoryExists());
379#endif  // GTEST_OS_WINDOWS
380}
381
382#if GTEST_OS_WINDOWS
383TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) {
384  const int saved_drive_ = _getdrive();
385  // Find a drive that doesn't exist. Start with 'Z' to avoid common ones.
386  for (char drive = 'Z'; drive >= 'A'; drive--)
387    if (_chdrive(drive - 'A' + 1) == -1) {
388      char non_drive[_MAX_PATH];  // NOLINT
389      non_drive[0] = drive;
390      non_drive[1] = ':';
391      non_drive[2] = '\\';
392      non_drive[3] = '\0';
393      EXPECT_FALSE(FilePath(non_drive).DirectoryExists());
394      break;
395    }
396  _chdrive(saved_drive_);
397}
398#endif  // GTEST_OS_WINDOWS
399
400#if !GTEST_OS_WINDOWS_MOBILE
401// Windows CE _does_ consider an empty directory to exist.
402TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
403  EXPECT_FALSE(FilePath("").DirectoryExists());
404}
405#endif  // !GTEST_OS_WINDOWS_MOBILE
406
407TEST(DirectoryTest, CurrentDirectoryExists) {
408#if GTEST_OS_WINDOWS  // We are on Windows.
409# ifndef _WIN32_CE  // Windows CE doesn't have a current directory.
410
411  EXPECT_TRUE(FilePath(".").DirectoryExists());
412  EXPECT_TRUE(FilePath(".\\").DirectoryExists());
413
414# endif  // _WIN32_CE
415#else
416  EXPECT_TRUE(FilePath(".").DirectoryExists());
417  EXPECT_TRUE(FilePath("./").DirectoryExists());
418#endif  // GTEST_OS_WINDOWS
419}
420
421// "foo/bar" == foo//bar" == "foo///bar"
422TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
423  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
424            FilePath("foo" GTEST_PATH_SEP_ "bar").string());
425  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
426            FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
427  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
428            FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_
429                     GTEST_PATH_SEP_ "bar").string());
430}
431
432// "/bar" == //bar" == "///bar"
433TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
434  EXPECT_EQ(GTEST_PATH_SEP_ "bar",
435    FilePath(GTEST_PATH_SEP_ "bar").string());
436  EXPECT_EQ(GTEST_PATH_SEP_ "bar",
437    FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
438  EXPECT_EQ(GTEST_PATH_SEP_ "bar",
439    FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
440}
441
442// "foo/" == foo//" == "foo///"
443TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
444  EXPECT_EQ("foo" GTEST_PATH_SEP_,
445    FilePath("foo" GTEST_PATH_SEP_).string());
446  EXPECT_EQ("foo" GTEST_PATH_SEP_,
447    FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
448  EXPECT_EQ("foo" GTEST_PATH_SEP_,
449    FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
450}
451
452#if GTEST_HAS_ALT_PATH_SEP_
453
454// Tests that separators at the end of the string are normalized
455// regardless of their combination (e.g. "foo\" =="foo/\" ==
456// "foo\\/").
457TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
458  EXPECT_EQ("foo" GTEST_PATH_SEP_,
459            FilePath("foo/").string());
460  EXPECT_EQ("foo" GTEST_PATH_SEP_,
461            FilePath("foo" GTEST_PATH_SEP_ "/").string());
462  EXPECT_EQ("foo" GTEST_PATH_SEP_,
463            FilePath("foo//" GTEST_PATH_SEP_).string());
464}
465
466#endif
467
468TEST(AssignmentOperatorTest, DefaultAssignedToNonDefault) {
469  FilePath default_path;
470  FilePath non_default_path("path");
471  non_default_path = default_path;
472  EXPECT_EQ("", non_default_path.string());
473  EXPECT_EQ("", default_path.string());  // RHS var is unchanged.
474}
475
476TEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) {
477  FilePath non_default_path("path");
478  FilePath default_path;
479  default_path = non_default_path;
480  EXPECT_EQ("path", default_path.string());
481  EXPECT_EQ("path", non_default_path.string());  // RHS var is unchanged.
482}
483
484TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
485  const FilePath const_default_path("const_path");
486  FilePath non_default_path("path");
487  non_default_path = const_default_path;
488  EXPECT_EQ("const_path", non_default_path.string());
489}
490
491class DirectoryCreationTest : public Test {
492 protected:
493  virtual void SetUp() {
494    testdata_path_.Set(FilePath(
495        TempDir() + GetCurrentExecutableName().string() +
496        "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
497    testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
498
499    unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
500        0, "txt"));
501    unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
502        1, "txt"));
503
504    remove(testdata_file_.c_str());
505    remove(unique_file0_.c_str());
506    remove(unique_file1_.c_str());
507    posix::RmDir(testdata_path_.c_str());
508  }
509
510  virtual void TearDown() {
511    remove(testdata_file_.c_str());
512    remove(unique_file0_.c_str());
513    remove(unique_file1_.c_str());
514    posix::RmDir(testdata_path_.c_str());
515  }
516
517  void CreateTextFile(const char* filename) {
518    FILE* f = posix::FOpen(filename, "w");
519    fprintf(f, "text\n");
520    fclose(f);
521  }
522
523  // Strings representing a directory and a file, with identical paths
524  // except for the trailing separator character that distinquishes
525  // a directory named 'test' from a file named 'test'. Example names:
526  FilePath testdata_path_;  // "/tmp/directory_creation/test/"
527  FilePath testdata_file_;  // "/tmp/directory_creation/test"
528  FilePath unique_file0_;  // "/tmp/directory_creation/test/unique.txt"
529  FilePath unique_file1_;  // "/tmp/directory_creation/test/unique_1.txt"
530};
531
532TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
533  EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
534  EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
535  EXPECT_TRUE(testdata_path_.DirectoryExists());
536}
537
538TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
539  EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
540  EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
541  // Call 'create' again... should still succeed.
542  EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
543}
544
545TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
546  FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_,
547      FilePath("unique"), "txt"));
548  EXPECT_EQ(unique_file0_.string(), file_path.string());
549  EXPECT_FALSE(file_path.FileOrDirectoryExists());  // file not there
550
551  testdata_path_.CreateDirectoriesRecursively();
552  EXPECT_FALSE(file_path.FileOrDirectoryExists());  // file still not there
553  CreateTextFile(file_path.c_str());
554  EXPECT_TRUE(file_path.FileOrDirectoryExists());
555
556  FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_,
557      FilePath("unique"), "txt"));
558  EXPECT_EQ(unique_file1_.string(), file_path2.string());
559  EXPECT_FALSE(file_path2.FileOrDirectoryExists());  // file not there
560  CreateTextFile(file_path2.c_str());
561  EXPECT_TRUE(file_path2.FileOrDirectoryExists());
562}
563
564TEST_F(DirectoryCreationTest, CreateDirectoriesFail) {
565  // force a failure by putting a file where we will try to create a directory.
566  CreateTextFile(testdata_file_.c_str());
567  EXPECT_TRUE(testdata_file_.FileOrDirectoryExists());
568  EXPECT_FALSE(testdata_file_.DirectoryExists());
569  EXPECT_FALSE(testdata_file_.CreateDirectoriesRecursively());
570}
571
572TEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) {
573  const FilePath test_detail_xml("test_detail.xml");
574  EXPECT_FALSE(test_detail_xml.CreateDirectoriesRecursively());
575}
576
577TEST(FilePathTest, DefaultConstructor) {
578  FilePath fp;
579  EXPECT_EQ("", fp.string());
580}
581
582TEST(FilePathTest, CharAndCopyConstructors) {
583  const FilePath fp("spicy");
584  EXPECT_EQ("spicy", fp.string());
585
586  const FilePath fp_copy(fp);
587  EXPECT_EQ("spicy", fp_copy.string());
588}
589
590TEST(FilePathTest, StringConstructor) {
591  const FilePath fp(std::string("cider"));
592  EXPECT_EQ("cider", fp.string());
593}
594
595TEST(FilePathTest, Set) {
596  const FilePath apple("apple");
597  FilePath mac("mac");
598  mac.Set(apple);  // Implement Set() since overloading operator= is forbidden.
599  EXPECT_EQ("apple", mac.string());
600  EXPECT_EQ("apple", apple.string());
601}
602
603TEST(FilePathTest, ToString) {
604  const FilePath file("drink");
605  EXPECT_EQ("drink", file.string());
606}
607
608TEST(FilePathTest, RemoveExtension) {
609  EXPECT_EQ("app", FilePath("app.cc").RemoveExtension("cc").string());
610  EXPECT_EQ("app", FilePath("app.exe").RemoveExtension("exe").string());
611  EXPECT_EQ("APP", FilePath("APP.EXE").RemoveExtension("exe").string());
612}
613
614TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) {
615  EXPECT_EQ("app", FilePath("app").RemoveExtension("exe").string());
616}
617
618TEST(FilePathTest, IsDirectory) {
619  EXPECT_FALSE(FilePath("cola").IsDirectory());
620  EXPECT_TRUE(FilePath("koala" GTEST_PATH_SEP_).IsDirectory());
621#if GTEST_HAS_ALT_PATH_SEP_
622  EXPECT_TRUE(FilePath("koala/").IsDirectory());
623#endif
624}
625
626TEST(FilePathTest, IsAbsolutePath) {
627  EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
628  EXPECT_FALSE(FilePath("").IsAbsolutePath());
629#if GTEST_OS_WINDOWS
630  EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not"
631                       GTEST_PATH_SEP_ "relative").IsAbsolutePath());
632  EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
633  EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not"
634                       GTEST_PATH_SEP_ "relative").IsAbsolutePath());
635#else
636  EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
637              .IsAbsolutePath());
638#endif  // GTEST_OS_WINDOWS
639}
640
641TEST(FilePathTest, IsRootDirectory) {
642#if GTEST_OS_WINDOWS
643  EXPECT_TRUE(FilePath("a:\\").IsRootDirectory());
644  EXPECT_TRUE(FilePath("Z:/").IsRootDirectory());
645  EXPECT_TRUE(FilePath("e://").IsRootDirectory());
646  EXPECT_FALSE(FilePath("").IsRootDirectory());
647  EXPECT_FALSE(FilePath("b:").IsRootDirectory());
648  EXPECT_FALSE(FilePath("b:a").IsRootDirectory());
649  EXPECT_FALSE(FilePath("8:/").IsRootDirectory());
650  EXPECT_FALSE(FilePath("c|/").IsRootDirectory());
651#else
652  EXPECT_TRUE(FilePath("/").IsRootDirectory());
653  EXPECT_TRUE(FilePath("//").IsRootDirectory());
654  EXPECT_FALSE(FilePath("").IsRootDirectory());
655  EXPECT_FALSE(FilePath("\\").IsRootDirectory());
656  EXPECT_FALSE(FilePath("/x").IsRootDirectory());
657#endif
658}
659
660}  // namespace
661}  // namespace internal
662}  // namespace testing
trunk/3rdparty/googletest/googletest/test/gtest-linked_ptr_test.cc
r0r249096
1// Copyright 2003, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: Dan Egnor (egnor@google.com)
31// Ported to Windows: Vadim Berman (vadimb@google.com)
32
33#include "gtest/internal/gtest-linked_ptr.h"
34
35#include <stdlib.h>
36#include "gtest/gtest.h"
37
38namespace {
39
40using testing::Message;
41using testing::internal::linked_ptr;
42
43int num;
44Message* history = NULL;
45
46// Class which tracks allocation/deallocation
47class A {
48 public:
49  A(): mynum(num++) { *history << "A" << mynum << " ctor\n"; }
50  virtual ~A() { *history << "A" << mynum << " dtor\n"; }
51  virtual void Use() { *history << "A" << mynum << " use\n"; }
52 protected:
53  int mynum;
54};
55
56// Subclass
57class B : public A {
58 public:
59  B() { *history << "B" << mynum << " ctor\n"; }
60  ~B() { *history << "B" << mynum << " dtor\n"; }
61  virtual void Use() { *history << "B" << mynum << " use\n"; }
62};
63
64class LinkedPtrTest : public testing::Test {
65 public:
66  LinkedPtrTest() {
67    num = 0;
68    history = new Message;
69  }
70
71  virtual ~LinkedPtrTest() {
72    delete history;
73    history = NULL;
74  }
75};
76
77TEST_F(LinkedPtrTest, GeneralTest) {
78  {
79    linked_ptr<A> a0, a1, a2;
80    // Use explicit function call notation here to suppress self-assign warning.
81    a0.operator=(a0);
82    a1 = a2;
83    ASSERT_EQ(a0.get(), static_cast<A*>(NULL));
84    ASSERT_EQ(a1.get(), static_cast<A*>(NULL));
85    ASSERT_EQ(a2.get(), static_cast<A*>(NULL));
86    ASSERT_TRUE(a0 == NULL);
87    ASSERT_TRUE(a1 == NULL);
88    ASSERT_TRUE(a2 == NULL);
89
90    {
91      linked_ptr<A> a3(new A);
92      a0 = a3;
93      ASSERT_TRUE(a0 == a3);
94      ASSERT_TRUE(a0 != NULL);
95      ASSERT_TRUE(a0.get() == a3);
96      ASSERT_TRUE(a0 == a3.get());
97      linked_ptr<A> a4(a0);
98      a1 = a4;
99      linked_ptr<A> a5(new A);
100      ASSERT_TRUE(a5.get() != a3);
101      ASSERT_TRUE(a5 != a3.get());
102      a2 = a5;
103      linked_ptr<B> b0(new B);
104      linked_ptr<A> a6(b0);
105      ASSERT_TRUE(b0 == a6);
106      ASSERT_TRUE(a6 == b0);
107      ASSERT_TRUE(b0 != NULL);
108      a5 = b0;
109      a5 = b0;
110      a3->Use();
111      a4->Use();
112      a5->Use();
113      a6->Use();
114      b0->Use();
115      (*b0).Use();
116      b0.get()->Use();
117    }
118
119    a0->Use();
120    a1->Use();
121    a2->Use();
122
123    a1 = a2;
124    a2.reset(new A);
125    a0.reset();
126
127    linked_ptr<A> a7;
128  }
129
130  ASSERT_STREQ(
131    "A0 ctor\n"
132    "A1 ctor\n"
133    "A2 ctor\n"
134    "B2 ctor\n"
135    "A0 use\n"
136    "A0 use\n"
137    "B2 use\n"
138    "B2 use\n"
139    "B2 use\n"
140    "B2 use\n"
141    "B2 use\n"
142    "B2 dtor\n"
143    "A2 dtor\n"
144    "A0 use\n"
145    "A0 use\n"
146    "A1 use\n"
147    "A3 ctor\n"
148    "A0 dtor\n"
149    "A3 dtor\n"
150    "A1 dtor\n",
151    history->GetString().c_str());
152}
153
154}  // Unnamed namespace
trunk/3rdparty/googletest/googletest/test/gtest-listener_test.cc
r0r249096
1// Copyright 2009 Google Inc. All rights reserved.
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are
5// met:
6//
7//     * Redistributions of source code must retain the above copyright
8// notice, this list of conditions and the following disclaimer.
9//     * Redistributions in binary form must reproduce the above
10// copyright notice, this list of conditions and the following disclaimer
11// in the documentation and/or other materials provided with the
12// distribution.
13//     * Neither the name of Google Inc. nor the names of its
14// contributors may be used to endorse or promote products derived from
15// this software without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: vladl@google.com (Vlad Losev)
30//
31// The Google C++ Testing Framework (Google Test)
32//
33// This file verifies Google Test event listeners receive events at the
34// right times.
35
36#include "gtest/gtest.h"
37#include <vector>
38
39using ::testing::AddGlobalTestEnvironment;
40using ::testing::Environment;
41using ::testing::InitGoogleTest;
42using ::testing::Test;
43using ::testing::TestCase;
44using ::testing::TestEventListener;
45using ::testing::TestInfo;
46using ::testing::TestPartResult;
47using ::testing::UnitTest;
48
49// Used by tests to register their events.
50std::vector<std::string>* g_events = NULL;
51
52namespace testing {
53namespace internal {
54
55class EventRecordingListener : public TestEventListener {
56 public:
57  explicit EventRecordingListener(const char* name) : name_(name) {}
58
59 protected:
60  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
61    g_events->push_back(GetFullMethodName("OnTestProgramStart"));
62  }
63
64  virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
65                                    int iteration) {
66    Message message;
67    message << GetFullMethodName("OnTestIterationStart")
68            << "(" << iteration << ")";
69    g_events->push_back(message.GetString());
70  }
71
72  virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {
73    g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart"));
74  }
75
76  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {
77    g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd"));
78  }
79
80  virtual void OnTestCaseStart(const TestCase& /*test_case*/) {
81    g_events->push_back(GetFullMethodName("OnTestCaseStart"));
82  }
83
84  virtual void OnTestStart(const TestInfo& /*test_info*/) {
85    g_events->push_back(GetFullMethodName("OnTestStart"));
86  }
87
88  virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {
89    g_events->push_back(GetFullMethodName("OnTestPartResult"));
90  }
91
92  virtual void OnTestEnd(const TestInfo& /*test_info*/) {
93    g_events->push_back(GetFullMethodName("OnTestEnd"));
94  }
95
96  virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {
97    g_events->push_back(GetFullMethodName("OnTestCaseEnd"));
98  }
99
100  virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {
101    g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart"));
102  }
103
104  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {
105    g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd"));
106  }
107
108  virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
109                                  int iteration) {
110    Message message;
111    message << GetFullMethodName("OnTestIterationEnd")
112            << "("  << iteration << ")";
113    g_events->push_back(message.GetString());
114  }
115
116  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
117    g_events->push_back(GetFullMethodName("OnTestProgramEnd"));
118  }
119
120 private:
121  std::string GetFullMethodName(const char* name) {
122    return name_ + "." + name;
123  }
124
125  std::string name_;
126};
127
128class EnvironmentInvocationCatcher : public Environment {
129 protected:
130  virtual void SetUp() {
131    g_events->push_back("Environment::SetUp");
132  }
133
134  virtual void TearDown() {
135    g_events->push_back("Environment::TearDown");
136  }
137};
138
139class ListenerTest : public Test {
140 protected:
141  static void SetUpTestCase() {
142    g_events->push_back("ListenerTest::SetUpTestCase");
143  }
144
145  static void TearDownTestCase() {
146    g_events->push_back("ListenerTest::TearDownTestCase");
147  }
148
149  virtual void SetUp() {
150    g_events->push_back("ListenerTest::SetUp");
151  }
152
153  virtual void TearDown() {
154    g_events->push_back("ListenerTest::TearDown");
155  }
156};
157
158TEST_F(ListenerTest, DoesFoo) {
159  // Test execution order within a test case is not guaranteed so we are not
160  // recording the test name.
161  g_events->push_back("ListenerTest::* Test Body");
162  SUCCEED();  // Triggers OnTestPartResult.
163}
164
165TEST_F(ListenerTest, DoesBar) {
166  g_events->push_back("ListenerTest::* Test Body");
167  SUCCEED();  // Triggers OnTestPartResult.
168}
169
170}  // namespace internal
171
172}  // namespace testing
173
174using ::testing::internal::EnvironmentInvocationCatcher;
175using ::testing::internal::EventRecordingListener;
176
177void VerifyResults(const std::vector<std::string>& data,
178                   const char* const* expected_data,
179                   size_t expected_data_size) {
180  const size_t actual_size = data.size();
181  // If the following assertion fails, a new entry will be appended to
182  // data.  Hence we save data.size() first.
183  EXPECT_EQ(expected_data_size, actual_size);
184
185  // Compares the common prefix.
186  const size_t shorter_size = expected_data_size <= actual_size ?
187      expected_data_size : actual_size;
188  size_t i = 0;
189  for (; i < shorter_size; ++i) {
190    ASSERT_STREQ(expected_data[i], data[i].c_str())
191        << "at position " << i;
192  }
193
194  // Prints extra elements in the actual data.
195  for (; i < actual_size; ++i) {
196    printf("  Actual event #%lu: %s\n",
197        static_cast<unsigned long>(i), data[i].c_str());
198  }
199}
200
201int main(int argc, char **argv) {
202  std::vector<std::string> events;
203  g_events = &events;
204  InitGoogleTest(&argc, argv);
205
206  UnitTest::GetInstance()->listeners().Append(
207      new EventRecordingListener("1st"));
208  UnitTest::GetInstance()->listeners().Append(
209      new EventRecordingListener("2nd"));
210
211  AddGlobalTestEnvironment(new EnvironmentInvocationCatcher);
212
213  GTEST_CHECK_(events.size() == 0)
214      << "AddGlobalTestEnvironment should not generate any events itself.";
215
216  ::testing::GTEST_FLAG(repeat) = 2;
217  int ret_val = RUN_ALL_TESTS();
218
219  const char* const expected_events[] = {
220    "1st.OnTestProgramStart",
221    "2nd.OnTestProgramStart",
222    "1st.OnTestIterationStart(0)",
223    "2nd.OnTestIterationStart(0)",
224    "1st.OnEnvironmentsSetUpStart",
225    "2nd.OnEnvironmentsSetUpStart",
226    "Environment::SetUp",
227    "2nd.OnEnvironmentsSetUpEnd",
228    "1st.OnEnvironmentsSetUpEnd",
229    "1st.OnTestCaseStart",
230    "2nd.OnTestCaseStart",
231    "ListenerTest::SetUpTestCase",
232    "1st.OnTestStart",
233    "2nd.OnTestStart",
234    "ListenerTest::SetUp",
235    "ListenerTest::* Test Body",
236    "1st.OnTestPartResult",
237    "2nd.OnTestPartResult",
238    "ListenerTest::TearDown",
239    "2nd.OnTestEnd",
240    "1st.OnTestEnd",
241    "1st.OnTestStart",
242    "2nd.OnTestStart",
243    "ListenerTest::SetUp",
244    "ListenerTest::* Test Body",
245    "1st.OnTestPartResult",
246    "2nd.OnTestPartResult",
247    "ListenerTest::TearDown",
248    "2nd.OnTestEnd",
249    "1st.OnTestEnd",
250    "ListenerTest::TearDownTestCase",
251    "2nd.OnTestCaseEnd",
252    "1st.OnTestCaseEnd",
253    "1st.OnEnvironmentsTearDownStart",
254    "2nd.OnEnvironmentsTearDownStart",
255    "Environment::TearDown",
256    "2nd.OnEnvironmentsTearDownEnd",
257    "1st.OnEnvironmentsTearDownEnd",
258    "2nd.OnTestIterationEnd(0)",
259    "1st.OnTestIterationEnd(0)",
260    "1st.OnTestIterationStart(1)",
261    "2nd.OnTestIterationStart(1)",
262    "1st.OnEnvironmentsSetUpStart",
263    "2nd.OnEnvironmentsSetUpStart",
264    "Environment::SetUp",
265    "2nd.OnEnvironmentsSetUpEnd",
266    "1st.OnEnvironmentsSetUpEnd",
267    "1st.OnTestCaseStart",
268    "2nd.OnTestCaseStart",
269    "ListenerTest::SetUpTestCase",
270    "1st.OnTestStart",
271    "2nd.OnTestStart",
272    "ListenerTest::SetUp",
273    "ListenerTest::* Test Body",
274    "1st.OnTestPartResult",
275    "2nd.OnTestPartResult",
276    "ListenerTest::TearDown",
277    "2nd.OnTestEnd",
278    "1st.OnTestEnd",
279    "1st.OnTestStart",
280    "2nd.OnTestStart",
281    "ListenerTest::SetUp",
282    "ListenerTest::* Test Body",
283    "1st.OnTestPartResult",
284    "2nd.OnTestPartResult",
285    "ListenerTest::TearDown",
286    "2nd.OnTestEnd",
287    "1st.OnTestEnd",
288    "ListenerTest::TearDownTestCase",
289    "2nd.OnTestCaseEnd",
290    "1st.OnTestCaseEnd",
291    "1st.OnEnvironmentsTearDownStart",
292    "2nd.OnEnvironmentsTearDownStart",
293    "Environment::TearDown",
294    "2nd.OnEnvironmentsTearDownEnd",
295    "1st.OnEnvironmentsTearDownEnd",
296    "2nd.OnTestIterationEnd(1)",
297    "1st.OnTestIterationEnd(1)",
298    "2nd.OnTestProgramEnd",
299    "1st.OnTestProgramEnd"
300  };
301  VerifyResults(events,
302                expected_events,
303                sizeof(expected_events)/sizeof(expected_events[0]));
304
305  // We need to check manually for ad hoc test failures that happen after
306  // RUN_ALL_TESTS finishes.
307  if (UnitTest::GetInstance()->Failed())
308    ret_val = 1;
309
310  return ret_val;
311}
trunk/3rdparty/googletest/googletest/test/gtest-message_test.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for the Message class.
33
34#include "gtest/gtest-message.h"
35
36#include "gtest/gtest.h"
37
38namespace {
39
40using ::testing::Message;
41
42// Tests the testing::Message class
43
44// Tests the default constructor.
45TEST(MessageTest, DefaultConstructor) {
46  const Message msg;
47  EXPECT_EQ("", msg.GetString());
48}
49
50// Tests the copy constructor.
51TEST(MessageTest, CopyConstructor) {
52  const Message msg1("Hello");
53  const Message msg2(msg1);
54  EXPECT_EQ("Hello", msg2.GetString());
55}
56
57// Tests constructing a Message from a C-string.
58TEST(MessageTest, ConstructsFromCString) {
59  Message msg("Hello");
60  EXPECT_EQ("Hello", msg.GetString());
61}
62
63// Tests streaming a float.
64TEST(MessageTest, StreamsFloat) {
65  const std::string s = (Message() << 1.23456F << " " << 2.34567F).GetString();
66  // Both numbers should be printed with enough precision.
67  EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s.c_str());
68  EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s.c_str());
69}
70
71// Tests streaming a double.
72TEST(MessageTest, StreamsDouble) {
73  const std::string s = (Message() << 1260570880.4555497 << " "
74                                  << 1260572265.1954534).GetString();
75  // Both numbers should be printed with enough precision.
76  EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str());
77  EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str());
78}
79
80// Tests streaming a non-char pointer.
81TEST(MessageTest, StreamsPointer) {
82  int n = 0;
83  int* p = &n;
84  EXPECT_NE("(null)", (Message() << p).GetString());
85}
86
87// Tests streaming a NULL non-char pointer.
88TEST(MessageTest, StreamsNullPointer) {
89  int* p = NULL;
90  EXPECT_EQ("(null)", (Message() << p).GetString());
91}
92
93// Tests streaming a C string.
94TEST(MessageTest, StreamsCString) {
95  EXPECT_EQ("Foo", (Message() << "Foo").GetString());
96}
97
98// Tests streaming a NULL C string.
99TEST(MessageTest, StreamsNullCString) {
100  char* p = NULL;
101  EXPECT_EQ("(null)", (Message() << p).GetString());
102}
103
104// Tests streaming std::string.
105TEST(MessageTest, StreamsString) {
106  const ::std::string str("Hello");
107  EXPECT_EQ("Hello", (Message() << str).GetString());
108}
109
110// Tests that we can output strings containing embedded NULs.
111TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
112  const char char_array_with_nul[] =
113      "Here's a NUL\0 and some more string";
114  const ::std::string string_with_nul(char_array_with_nul,
115                                      sizeof(char_array_with_nul) - 1);
116  EXPECT_EQ("Here's a NUL\\0 and some more string",
117            (Message() << string_with_nul).GetString());
118}
119
120// Tests streaming a NUL char.
121TEST(MessageTest, StreamsNULChar) {
122  EXPECT_EQ("\\0", (Message() << '\0').GetString());
123}
124
125// Tests streaming int.
126TEST(MessageTest, StreamsInt) {
127  EXPECT_EQ("123", (Message() << 123).GetString());
128}
129
130// Tests that basic IO manipulators (endl, ends, and flush) can be
131// streamed to Message.
132TEST(MessageTest, StreamsBasicIoManip) {
133  EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.",
134               (Message() << "Line 1." << std::endl
135                         << "A NUL char " << std::ends << std::flush
136                         << " in line 2.").GetString());
137}
138
139// Tests Message::GetString()
140TEST(MessageTest, GetString) {
141  Message msg;
142  msg << 1 << " lamb";
143  EXPECT_EQ("1 lamb", msg.GetString());
144}
145
146// Tests streaming a Message object to an ostream.
147TEST(MessageTest, StreamsToOStream) {
148  Message msg("Hello");
149  ::std::stringstream ss;
150  ss << msg;
151  EXPECT_EQ("Hello", testing::internal::StringStreamToString(&ss));
152}
153
154// Tests that a Message object doesn't take up too much stack space.
155TEST(MessageTest, DoesNotTakeUpMuchStackSpace) {
156  EXPECT_LE(sizeof(Message), 16U);
157}
158
159}  // namespace
trunk/3rdparty/googletest/googletest/test/gtest-options_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: keith.ray@gmail.com (Keith Ray)
31//
32// Google Test UnitTestOptions tests
33//
34// This file tests classes and functions used internally by
35// Google Test.  They are subject to change without notice.
36//
37// This file is #included from gtest.cc, to avoid changing build or
38// make-files on Windows and other platforms. Do not #include this file
39// anywhere else!
40
41#include "gtest/gtest.h"
42
43#if GTEST_OS_WINDOWS_MOBILE
44# include <windows.h>
45#elif GTEST_OS_WINDOWS
46# include <direct.h>
47#endif  // GTEST_OS_WINDOWS_MOBILE
48
49// Indicates that this translation unit is part of Google Test's
50// implementation.  It must come before gtest-internal-inl.h is
51// included, or there will be a compiler error.  This trick is to
52// prevent a user from accidentally including gtest-internal-inl.h in
53// his code.
54#define GTEST_IMPLEMENTATION_ 1
55#include "src/gtest-internal-inl.h"
56#undef GTEST_IMPLEMENTATION_
57
58namespace testing {
59namespace internal {
60namespace {
61
62// Turns the given relative path into an absolute path.
63FilePath GetAbsolutePathOf(const FilePath& relative_path) {
64  return FilePath::ConcatPaths(FilePath::GetCurrentDir(), relative_path);
65}
66
67// Testing UnitTestOptions::GetOutputFormat/GetOutputFile.
68
69TEST(XmlOutputTest, GetOutputFormatDefault) {
70  GTEST_FLAG(output) = "";
71  EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str());
72}
73
74TEST(XmlOutputTest, GetOutputFormat) {
75  GTEST_FLAG(output) = "xml:filename";
76  EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str());
77}
78
79TEST(XmlOutputTest, GetOutputFileDefault) {
80  GTEST_FLAG(output) = "";
81  EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(),
82            UnitTestOptions::GetAbsolutePathToOutputFile());
83}
84
85TEST(XmlOutputTest, GetOutputFileSingleFile) {
86  GTEST_FLAG(output) = "xml:filename.abc";
87  EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(),
88            UnitTestOptions::GetAbsolutePathToOutputFile());
89}
90
91TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
92  GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_;
93  const std::string expected_output_file =
94      GetAbsolutePathOf(
95          FilePath(std::string("path") + GTEST_PATH_SEP_ +
96                   GetCurrentExecutableName().string() + ".xml")).string();
97  const std::string& output_file =
98      UnitTestOptions::GetAbsolutePathToOutputFile();
99#if GTEST_OS_WINDOWS
100  EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
101#else
102  EXPECT_EQ(expected_output_file, output_file.c_str());
103#endif
104}
105
106TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
107  const std::string exe_str = GetCurrentExecutableName().string();
108#if GTEST_OS_WINDOWS
109  const bool success =
110      _strcmpi("gtest-options_test", exe_str.c_str()) == 0 ||
111      _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 ||
112      _strcmpi("gtest_all_test", exe_str.c_str()) == 0 ||
113      _strcmpi("gtest_dll_test", exe_str.c_str()) == 0;
114#else
115  // TODO(wan@google.com): remove the hard-coded "lt-" prefix when
116  //   Chandler Carruth's libtool replacement is ready.
117  const bool success =
118      exe_str == "gtest-options_test" ||
119      exe_str == "gtest_all_test" ||
120      exe_str == "lt-gtest_all_test" ||
121      exe_str == "gtest_dll_test";
122#endif  // GTEST_OS_WINDOWS
123  if (!success)
124    FAIL() << "GetCurrentExecutableName() returns " << exe_str;
125}
126
127class XmlOutputChangeDirTest : public Test {
128 protected:
129  virtual void SetUp() {
130    original_working_dir_ = FilePath::GetCurrentDir();
131    posix::ChDir("..");
132    // This will make the test fail if run from the root directory.
133    EXPECT_NE(original_working_dir_.string(),
134              FilePath::GetCurrentDir().string());
135  }
136
137  virtual void TearDown() {
138    posix::ChDir(original_working_dir_.string().c_str());
139  }
140
141  FilePath original_working_dir_;
142};
143
144TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {
145  GTEST_FLAG(output) = "";
146  EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
147                                  FilePath("test_detail.xml")).string(),
148            UnitTestOptions::GetAbsolutePathToOutputFile());
149}
150
151TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {
152  GTEST_FLAG(output) = "xml";
153  EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
154                                  FilePath("test_detail.xml")).string(),
155            UnitTestOptions::GetAbsolutePathToOutputFile());
156}
157
158TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {
159  GTEST_FLAG(output) = "xml:filename.abc";
160  EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
161                                  FilePath("filename.abc")).string(),
162            UnitTestOptions::GetAbsolutePathToOutputFile());
163}
164
165TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
166  GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_;
167  const std::string expected_output_file =
168      FilePath::ConcatPaths(
169          original_working_dir_,
170          FilePath(std::string("path") + GTEST_PATH_SEP_ +
171                   GetCurrentExecutableName().string() + ".xml")).string();
172  const std::string& output_file =
173      UnitTestOptions::GetAbsolutePathToOutputFile();
174#if GTEST_OS_WINDOWS
175  EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
176#else
177  EXPECT_EQ(expected_output_file, output_file.c_str());
178#endif
179}
180
181TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {
182#if GTEST_OS_WINDOWS
183  GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc";
184  EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(),
185            UnitTestOptions::GetAbsolutePathToOutputFile());
186#else
187  GTEST_FLAG(output) ="xml:/tmp/filename.abc";
188  EXPECT_EQ(FilePath("/tmp/filename.abc").string(),
189            UnitTestOptions::GetAbsolutePathToOutputFile());
190#endif
191}
192
193TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {
194#if GTEST_OS_WINDOWS
195  const std::string path = "c:\\tmp\\";
196#else
197  const std::string path = "/tmp/";
198#endif
199
200  GTEST_FLAG(output) = "xml:" + path;
201  const std::string expected_output_file =
202      path + GetCurrentExecutableName().string() + ".xml";
203  const std::string& output_file =
204      UnitTestOptions::GetAbsolutePathToOutputFile();
205
206#if GTEST_OS_WINDOWS
207  EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
208#else
209  EXPECT_EQ(expected_output_file, output_file.c_str());
210#endif
211}
212
213}  // namespace
214}  // namespace internal
215}  // namespace testing
trunk/3rdparty/googletest/googletest/test/gtest-param-test2_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31//
32// Tests for Google Test itself.  This verifies that the basic constructs of
33// Google Test work.
34
35#include "gtest/gtest.h"
36
37#include "test/gtest-param-test_test.h"
38
39#if GTEST_HAS_PARAM_TEST
40
41using ::testing::Values;
42using ::testing::internal::ParamGenerator;
43
44// Tests that generators defined in a different translation unit
45// are functional. The test using extern_gen is defined
46// in gtest-param-test_test.cc.
47ParamGenerator<int> extern_gen = Values(33);
48
49// Tests that a parameterized test case can be defined in one translation unit
50// and instantiated in another. The test is defined in gtest-param-test_test.cc
51// and ExternalInstantiationTest fixture class is defined in
52// gtest-param-test_test.h.
53INSTANTIATE_TEST_CASE_P(MultiplesOf33,
54                        ExternalInstantiationTest,
55                        Values(33, 66));
56
57// Tests that a parameterized test case can be instantiated
58// in multiple translation units. Another instantiation is defined
59// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest
60// fixture is defined in gtest-param-test_test.h
61INSTANTIATE_TEST_CASE_P(Sequence2,
62                        InstantiationInMultipleTranslaionUnitsTest,
63                        Values(42*3, 42*4, 42*5));
64
65#endif  // GTEST_HAS_PARAM_TEST
trunk/3rdparty/googletest/googletest/test/gtest-param-test_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31//
32// Tests for Google Test itself. This file verifies that the parameter
33// generators objects produce correct parameter sequences and that
34// Google Test runtime instantiates correct tests from those sequences.
35
36#include "gtest/gtest.h"
37
38#if GTEST_HAS_PARAM_TEST
39
40# include <algorithm>
41# include <iostream>
42# include <list>
43# include <sstream>
44# include <string>
45# include <vector>
46
47// To include gtest-internal-inl.h.
48# define GTEST_IMPLEMENTATION_ 1
49# include "src/gtest-internal-inl.h"  // for UnitTestOptions
50# undef GTEST_IMPLEMENTATION_
51
52# include "test/gtest-param-test_test.h"
53
54using ::std::vector;
55using ::std::sort;
56
57using ::testing::AddGlobalTestEnvironment;
58using ::testing::Bool;
59using ::testing::Message;
60using ::testing::Range;
61using ::testing::TestWithParam;
62using ::testing::Values;
63using ::testing::ValuesIn;
64
65# if GTEST_HAS_COMBINE
66using ::testing::Combine;
67using ::testing::get;
68using ::testing::make_tuple;
69using ::testing::tuple;
70# endif  // GTEST_HAS_COMBINE
71
72using ::testing::internal::ParamGenerator;
73using ::testing::internal::UnitTestOptions;
74
75// Prints a value to a string.
76//
77// TODO(wan@google.com): remove PrintValue() when we move matchers and
78// EXPECT_THAT() from Google Mock to Google Test.  At that time, we
79// can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as
80// EXPECT_THAT() and the matchers know how to print tuples.
81template <typename T>
82::std::string PrintValue(const T& value) {
83  ::std::stringstream stream;
84  stream << value;
85  return stream.str();
86}
87
88# if GTEST_HAS_COMBINE
89
90// These overloads allow printing tuples in our tests.  We cannot
91// define an operator<< for tuples, as that definition needs to be in
92// the std namespace in order to be picked up by Google Test via
93// Argument-Dependent Lookup, yet defining anything in the std
94// namespace in non-STL code is undefined behavior.
95
96template <typename T1, typename T2>
97::std::string PrintValue(const tuple<T1, T2>& value) {
98  ::std::stringstream stream;
99  stream << "(" << get<0>(value) << ", " << get<1>(value) << ")";
100  return stream.str();
101}
102
103template <typename T1, typename T2, typename T3>
104::std::string PrintValue(const tuple<T1, T2, T3>& value) {
105  ::std::stringstream stream;
106  stream << "(" << get<0>(value) << ", " << get<1>(value)
107         << ", "<< get<2>(value) << ")";
108  return stream.str();
109}
110
111template <typename T1, typename T2, typename T3, typename T4, typename T5,
112          typename T6, typename T7, typename T8, typename T9, typename T10>
113::std::string PrintValue(
114    const tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& value) {
115  ::std::stringstream stream;
116  stream << "(" << get<0>(value) << ", " << get<1>(value)
117         << ", "<< get<2>(value) << ", " << get<3>(value)
118         << ", "<< get<4>(value) << ", " << get<5>(value)
119         << ", "<< get<6>(value) << ", " << get<7>(value)
120         << ", "<< get<8>(value) << ", " << get<9>(value) << ")";
121  return stream.str();
122}
123
124# endif  // GTEST_HAS_COMBINE
125
126// Verifies that a sequence generated by the generator and accessed
127// via the iterator object matches the expected one using Google Test
128// assertions.
129template <typename T, size_t N>
130void VerifyGenerator(const ParamGenerator<T>& generator,
131                     const T (&expected_values)[N]) {
132  typename ParamGenerator<T>::iterator it = generator.begin();
133  for (size_t i = 0; i < N; ++i) {
134    ASSERT_FALSE(it == generator.end())
135        << "At element " << i << " when accessing via an iterator "
136        << "created with the copy constructor.\n";
137    // We cannot use EXPECT_EQ() here as the values may be tuples,
138    // which don't support <<.
139    EXPECT_TRUE(expected_values[i] == *it)
140        << "where i is " << i
141        << ", expected_values[i] is " << PrintValue(expected_values[i])
142        << ", *it is " << PrintValue(*it)
143        << ", and 'it' is an iterator created with the copy constructor.\n";
144    it++;
145  }
146  EXPECT_TRUE(it == generator.end())
147        << "At the presumed end of sequence when accessing via an iterator "
148        << "created with the copy constructor.\n";
149
150  // Test the iterator assignment. The following lines verify that
151  // the sequence accessed via an iterator initialized via the
152  // assignment operator (as opposed to a copy constructor) matches
153  // just the same.
154  it = generator.begin();
155  for (size_t i = 0; i < N; ++i) {
156    ASSERT_FALSE(it == generator.end())
157        << "At element " << i << " when accessing via an iterator "
158        << "created with the assignment operator.\n";
159    EXPECT_TRUE(expected_values[i] == *it)
160        << "where i is " << i
161        << ", expected_values[i] is " << PrintValue(expected_values[i])
162        << ", *it is " << PrintValue(*it)
163        << ", and 'it' is an iterator created with the copy constructor.\n";
164    it++;
165  }
166  EXPECT_TRUE(it == generator.end())
167        << "At the presumed end of sequence when accessing via an iterator "
168        << "created with the assignment operator.\n";
169}
170
171template <typename T>
172void VerifyGeneratorIsEmpty(const ParamGenerator<T>& generator) {
173  typename ParamGenerator<T>::iterator it = generator.begin();
174  EXPECT_TRUE(it == generator.end());
175
176  it = generator.begin();
177  EXPECT_TRUE(it == generator.end());
178}
179
180// Generator tests. They test that each of the provided generator functions
181// generates an expected sequence of values. The general test pattern
182// instantiates a generator using one of the generator functions,
183// checks the sequence produced by the generator using its iterator API,
184// and then resets the iterator back to the beginning of the sequence
185// and checks the sequence again.
186
187// Tests that iterators produced by generator functions conform to the
188// ForwardIterator concept.
189TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) {
190  const ParamGenerator<int> gen = Range(0, 10);
191  ParamGenerator<int>::iterator it = gen.begin();
192
193  // Verifies that iterator initialization works as expected.
194  ParamGenerator<int>::iterator it2 = it;
195  EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the "
196                           << "element same as its source points to";
197
198  // Verifies that iterator assignment works as expected.
199  it++;
200  EXPECT_FALSE(*it == *it2);
201  it2 = it;
202  EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the "
203                           << "element same as its source points to";
204
205  // Verifies that prefix operator++() returns *this.
206  EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be "
207                          << "refer to the original object";
208
209  // Verifies that the result of the postfix operator++ points to the value
210  // pointed to by the original iterator.
211  int original_value = *it;  // Have to compute it outside of macro call to be
212                             // unaffected by the parameter evaluation order.
213  EXPECT_EQ(original_value, *(it++));
214
215  // Verifies that prefix and postfix operator++() advance an iterator
216  // all the same.
217  it2 = it;
218  it++;
219  ++it2;
220  EXPECT_TRUE(*it == *it2);
221}
222
223// Tests that Range() generates the expected sequence.
224TEST(RangeTest, IntRangeWithDefaultStep) {
225  const ParamGenerator<int> gen = Range(0, 3);
226  const int expected_values[] = {0, 1, 2};
227  VerifyGenerator(gen, expected_values);
228}
229
230// Edge case. Tests that Range() generates the single element sequence
231// as expected when provided with range limits that are equal.
232TEST(RangeTest, IntRangeSingleValue) {
233  const ParamGenerator<int> gen = Range(0, 1);
234  const int expected_values[] = {0};
235  VerifyGenerator(gen, expected_values);
236}
237
238// Edge case. Tests that Range() with generates empty sequence when
239// supplied with an empty range.
240TEST(RangeTest, IntRangeEmpty) {
241  const ParamGenerator<int> gen = Range(0, 0);
242  VerifyGeneratorIsEmpty(gen);
243}
244
245// Tests that Range() with custom step (greater then one) generates
246// the expected sequence.
247TEST(RangeTest, IntRangeWithCustomStep) {
248  const ParamGenerator<int> gen = Range(0, 9, 3);
249  const int expected_values[] = {0, 3, 6};
250  VerifyGenerator(gen, expected_values);
251}
252
253// Tests that Range() with custom step (greater then one) generates
254// the expected sequence when the last element does not fall on the
255// upper range limit. Sequences generated by Range() must not have
256// elements beyond the range limits.
257TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) {
258  const ParamGenerator<int> gen = Range(0, 4, 3);
259  const int expected_values[] = {0, 3};
260  VerifyGenerator(gen, expected_values);
261}
262
263// Verifies that Range works with user-defined types that define
264// copy constructor, operator=(), operator+(), and operator<().
265class DogAdder {
266 public:
267  explicit DogAdder(const char* a_value) : value_(a_value) {}
268  DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
269
270  DogAdder operator=(const DogAdder& other) {
271    if (this != &other)
272      value_ = other.value_;
273    return *this;
274  }
275  DogAdder operator+(const DogAdder& other) const {
276    Message msg;
277    msg << value_.c_str() << other.value_.c_str();
278    return DogAdder(msg.GetString().c_str());
279  }
280  bool operator<(const DogAdder& other) const {
281    return value_ < other.value_;
282  }
283  const std::string& value() const { return value_; }
284
285 private:
286  std::string value_;
287};
288
289TEST(RangeTest, WorksWithACustomType) {
290  const ParamGenerator<DogAdder> gen =
291      Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog"));
292  ParamGenerator<DogAdder>::iterator it = gen.begin();
293
294  ASSERT_FALSE(it == gen.end());
295  EXPECT_STREQ("cat", it->value().c_str());
296
297  ASSERT_FALSE(++it == gen.end());
298  EXPECT_STREQ("catdog", it->value().c_str());
299
300  EXPECT_TRUE(++it == gen.end());
301}
302
303class IntWrapper {
304 public:
305  explicit IntWrapper(int a_value) : value_(a_value) {}
306  IntWrapper(const IntWrapper& other) : value_(other.value_) {}
307
308  IntWrapper operator=(const IntWrapper& other) {
309    value_ = other.value_;
310    return *this;
311  }
312  // operator+() adds a different type.
313  IntWrapper operator+(int other) const { return IntWrapper(value_ + other); }
314  bool operator<(const IntWrapper& other) const {
315    return value_ < other.value_;
316  }
317  int value() const { return value_; }
318
319 private:
320  int value_;
321};
322
323TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) {
324  const ParamGenerator<IntWrapper> gen = Range(IntWrapper(0), IntWrapper(2));
325  ParamGenerator<IntWrapper>::iterator it = gen.begin();
326
327  ASSERT_FALSE(it == gen.end());
328  EXPECT_EQ(0, it->value());
329
330  ASSERT_FALSE(++it == gen.end());
331  EXPECT_EQ(1, it->value());
332
333  EXPECT_TRUE(++it == gen.end());
334}
335
336// Tests that ValuesIn() with an array parameter generates
337// the expected sequence.
338TEST(ValuesInTest, ValuesInArray) {
339  int array[] = {3, 5, 8};
340  const ParamGenerator<int> gen = ValuesIn(array);
341  VerifyGenerator(gen, array);
342}
343
344// Tests that ValuesIn() with a const array parameter generates
345// the expected sequence.
346TEST(ValuesInTest, ValuesInConstArray) {
347  const int array[] = {3, 5, 8};
348  const ParamGenerator<int> gen = ValuesIn(array);
349  VerifyGenerator(gen, array);
350}
351
352// Edge case. Tests that ValuesIn() with an array parameter containing a
353// single element generates the single element sequence.
354TEST(ValuesInTest, ValuesInSingleElementArray) {
355  int array[] = {42};
356  const ParamGenerator<int> gen = ValuesIn(array);
357  VerifyGenerator(gen, array);
358}
359
360// Tests that ValuesIn() generates the expected sequence for an STL
361// container (vector).
362TEST(ValuesInTest, ValuesInVector) {
363  typedef ::std::vector<int> ContainerType;
364  ContainerType values;
365  values.push_back(3);
366  values.push_back(5);
367  values.push_back(8);
368  const ParamGenerator<int> gen = ValuesIn(values);
369
370  const int expected_values[] = {3, 5, 8};
371  VerifyGenerator(gen, expected_values);
372}
373
374// Tests that ValuesIn() generates the expected sequence.
375TEST(ValuesInTest, ValuesInIteratorRange) {
376  typedef ::std::vector<int> ContainerType;
377  ContainerType values;
378  values.push_back(3);
379  values.push_back(5);
380  values.push_back(8);
381  const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
382
383  const int expected_values[] = {3, 5, 8};
384  VerifyGenerator(gen, expected_values);
385}
386
387// Edge case. Tests that ValuesIn() provided with an iterator range specifying a
388// single value generates a single-element sequence.
389TEST(ValuesInTest, ValuesInSingleElementIteratorRange) {
390  typedef ::std::vector<int> ContainerType;
391  ContainerType values;
392  values.push_back(42);
393  const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
394
395  const int expected_values[] = {42};
396  VerifyGenerator(gen, expected_values);
397}
398
399// Edge case. Tests that ValuesIn() provided with an empty iterator range
400// generates an empty sequence.
401TEST(ValuesInTest, ValuesInEmptyIteratorRange) {
402  typedef ::std::vector<int> ContainerType;
403  ContainerType values;
404  const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
405
406  VerifyGeneratorIsEmpty(gen);
407}
408
409// Tests that the Values() generates the expected sequence.
410TEST(ValuesTest, ValuesWorks) {
411  const ParamGenerator<int> gen = Values(3, 5, 8);
412
413  const int expected_values[] = {3, 5, 8};
414  VerifyGenerator(gen, expected_values);
415}
416
417// Tests that Values() generates the expected sequences from elements of
418// different types convertible to ParamGenerator's parameter type.
419TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
420  const ParamGenerator<double> gen = Values(3, 5.0f, 8.0);
421
422  const double expected_values[] = {3.0, 5.0, 8.0};
423  VerifyGenerator(gen, expected_values);
424}
425
426TEST(ValuesTest, ValuesWorksForMaxLengthList) {
427  const ParamGenerator<int> gen = Values(
428      10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
429      110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
430      210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
431      310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
432      410, 420, 430, 440, 450, 460, 470, 480, 490, 500);
433
434  const int expected_values[] = {
435      10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
436      110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
437      210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
438      310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
439      410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
440  VerifyGenerator(gen, expected_values);
441}
442
443// Edge case test. Tests that single-parameter Values() generates the sequence
444// with the single value.
445TEST(ValuesTest, ValuesWithSingleParameter) {
446  const ParamGenerator<int> gen = Values(42);
447
448  const int expected_values[] = {42};
449  VerifyGenerator(gen, expected_values);
450}
451
452// Tests that Bool() generates sequence (false, true).
453TEST(BoolTest, BoolWorks) {
454  const ParamGenerator<bool> gen = Bool();
455
456  const bool expected_values[] = {false, true};
457  VerifyGenerator(gen, expected_values);
458}
459
460# if GTEST_HAS_COMBINE
461
462// Tests that Combine() with two parameters generates the expected sequence.
463TEST(CombineTest, CombineWithTwoParameters) {
464  const char* foo = "foo";
465  const char* bar = "bar";
466  const ParamGenerator<tuple<const char*, int> > gen =
467      Combine(Values(foo, bar), Values(3, 4));
468
469  tuple<const char*, int> expected_values[] = {
470    make_tuple(foo, 3), make_tuple(foo, 4),
471    make_tuple(bar, 3), make_tuple(bar, 4)};
472  VerifyGenerator(gen, expected_values);
473}
474
475// Tests that Combine() with three parameters generates the expected sequence.
476TEST(CombineTest, CombineWithThreeParameters) {
477  const ParamGenerator<tuple<int, int, int> > gen = Combine(Values(0, 1),
478                                                            Values(3, 4),
479                                                            Values(5, 6));
480  tuple<int, int, int> expected_values[] = {
481    make_tuple(0, 3, 5), make_tuple(0, 3, 6),
482    make_tuple(0, 4, 5), make_tuple(0, 4, 6),
483    make_tuple(1, 3, 5), make_tuple(1, 3, 6),
484    make_tuple(1, 4, 5), make_tuple(1, 4, 6)};
485  VerifyGenerator(gen, expected_values);
486}
487
488// Tests that the Combine() with the first parameter generating a single value
489// sequence generates a sequence with the number of elements equal to the
490// number of elements in the sequence generated by the second parameter.
491TEST(CombineTest, CombineWithFirstParameterSingleValue) {
492  const ParamGenerator<tuple<int, int> > gen = Combine(Values(42),
493                                                       Values(0, 1));
494
495  tuple<int, int> expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)};
496  VerifyGenerator(gen, expected_values);
497}
498
499// Tests that the Combine() with the second parameter generating a single value
500// sequence generates a sequence with the number of elements equal to the
501// number of elements in the sequence generated by the first parameter.
502TEST(CombineTest, CombineWithSecondParameterSingleValue) {
503  const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1),
504                                                       Values(42));
505
506  tuple<int, int> expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)};
507  VerifyGenerator(gen, expected_values);
508}
509
510// Tests that when the first parameter produces an empty sequence,
511// Combine() produces an empty sequence, too.
512TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
513  const ParamGenerator<tuple<int, int> > gen = Combine(Range(0, 0),
514                                                       Values(0, 1));
515  VerifyGeneratorIsEmpty(gen);
516}
517
518// Tests that when the second parameter produces an empty sequence,
519// Combine() produces an empty sequence, too.
520TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
521  const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1),
522                                                       Range(1, 1));
523  VerifyGeneratorIsEmpty(gen);
524}
525
526// Edge case. Tests that combine works with the maximum number
527// of parameters supported by Google Test (currently 10).
528TEST(CombineTest, CombineWithMaxNumberOfParameters) {
529  const char* foo = "foo";
530  const char* bar = "bar";
531  const ParamGenerator<tuple<const char*, int, int, int, int, int, int, int,
532                             int, int> > gen = Combine(Values(foo, bar),
533                                                       Values(1), Values(2),
534                                                       Values(3), Values(4),
535                                                       Values(5), Values(6),
536                                                       Values(7), Values(8),
537                                                       Values(9));
538
539  tuple<const char*, int, int, int, int, int, int, int, int, int>
540      expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9),
541                           make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)};
542  VerifyGenerator(gen, expected_values);
543}
544
545# endif  // GTEST_HAS_COMBINE
546
547// Tests that an generator produces correct sequence after being
548// assigned from another generator.
549TEST(ParamGeneratorTest, AssignmentWorks) {
550  ParamGenerator<int> gen = Values(1, 2);
551  const ParamGenerator<int> gen2 = Values(3, 4);
552  gen = gen2;
553
554  const int expected_values[] = {3, 4};
555  VerifyGenerator(gen, expected_values);
556}
557
558// This test verifies that the tests are expanded and run as specified:
559// one test per element from the sequence produced by the generator
560// specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's
561// fixture constructor, SetUp(), and TearDown() have run and have been
562// supplied with the correct parameters.
563
564// The use of environment object allows detection of the case where no test
565// case functionality is run at all. In this case TestCaseTearDown will not
566// be able to detect missing tests, naturally.
567template <int kExpectedCalls>
568class TestGenerationEnvironment : public ::testing::Environment {
569 public:
570  static TestGenerationEnvironment* Instance() {
571    static TestGenerationEnvironment* instance = new TestGenerationEnvironment;
572    return instance;
573  }
574
575  void FixtureConstructorExecuted() { fixture_constructor_count_++; }
576  void SetUpExecuted() { set_up_count_++; }
577  void TearDownExecuted() { tear_down_count_++; }
578  void TestBodyExecuted() { test_body_count_++; }
579
580  virtual void TearDown() {
581    // If all MultipleTestGenerationTest tests have been de-selected
582    // by the filter flag, the following checks make no sense.
583    bool perform_check = false;
584
585    for (int i = 0; i < kExpectedCalls; ++i) {
586      Message msg;
587      msg << "TestsExpandedAndRun/" << i;
588      if (UnitTestOptions::FilterMatchesTest(
589             "TestExpansionModule/MultipleTestGenerationTest",
590              msg.GetString().c_str())) {
591        perform_check = true;
592      }
593    }
594    if (perform_check) {
595      EXPECT_EQ(kExpectedCalls, fixture_constructor_count_)
596          << "Fixture constructor of ParamTestGenerationTest test case "
597          << "has not been run as expected.";
598      EXPECT_EQ(kExpectedCalls, set_up_count_)
599          << "Fixture SetUp method of ParamTestGenerationTest test case "
600          << "has not been run as expected.";
601      EXPECT_EQ(kExpectedCalls, tear_down_count_)
602          << "Fixture TearDown method of ParamTestGenerationTest test case "
603          << "has not been run as expected.";
604      EXPECT_EQ(kExpectedCalls, test_body_count_)
605          << "Test in ParamTestGenerationTest test case "
606          << "has not been run as expected.";
607    }
608  }
609
610 private:
611  TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0),
612                                tear_down_count_(0), test_body_count_(0) {}
613
614  int fixture_constructor_count_;
615  int set_up_count_;
616  int tear_down_count_;
617  int test_body_count_;
618
619  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment);
620};
621
622const int test_generation_params[] = {36, 42, 72};
623
624class TestGenerationTest : public TestWithParam<int> {
625 public:
626  enum {
627    PARAMETER_COUNT =
628        sizeof(test_generation_params)/sizeof(test_generation_params[0])
629  };
630
631  typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
632
633  TestGenerationTest() {
634    Environment::Instance()->FixtureConstructorExecuted();
635    current_parameter_ = GetParam();
636  }
637  virtual void SetUp() {
638    Environment::Instance()->SetUpExecuted();
639    EXPECT_EQ(current_parameter_, GetParam());
640  }
641  virtual void TearDown() {
642    Environment::Instance()->TearDownExecuted();
643    EXPECT_EQ(current_parameter_, GetParam());
644  }
645
646  static void SetUpTestCase() {
647    bool all_tests_in_test_case_selected = true;
648
649    for (int i = 0; i < PARAMETER_COUNT; ++i) {
650      Message test_name;
651      test_name << "TestsExpandedAndRun/" << i;
652      if ( !UnitTestOptions::FilterMatchesTest(
653                "TestExpansionModule/MultipleTestGenerationTest",
654                test_name.GetString())) {
655        all_tests_in_test_case_selected = false;
656      }
657    }
658    EXPECT_TRUE(all_tests_in_test_case_selected)
659        << "When running the TestGenerationTest test case all of its tests\n"
660        << "must be selected by the filter flag for the test case to pass.\n"
661        << "If not all of them are enabled, we can't reliably conclude\n"
662        << "that the correct number of tests have been generated.";
663
664    collected_parameters_.clear();
665  }
666
667  static void TearDownTestCase() {
668    vector<int> expected_values(test_generation_params,
669                                test_generation_params + PARAMETER_COUNT);
670    // Test execution order is not guaranteed by Google Test,
671    // so the order of values in collected_parameters_ can be
672    // different and we have to sort to compare.
673    sort(expected_values.begin(), expected_values.end());
674    sort(collected_parameters_.begin(), collected_parameters_.end());
675
676    EXPECT_TRUE(collected_parameters_ == expected_values);
677  }
678
679 protected:
680  int current_parameter_;
681  static vector<int> collected_parameters_;
682
683 private:
684  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest);
685};
686vector<int> TestGenerationTest::collected_parameters_;
687
688TEST_P(TestGenerationTest, TestsExpandedAndRun) {
689  Environment::Instance()->TestBodyExecuted();
690  EXPECT_EQ(current_parameter_, GetParam());
691  collected_parameters_.push_back(GetParam());
692}
693INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest,
694                        ValuesIn(test_generation_params));
695
696// This test verifies that the element sequence (third parameter of
697// INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at
698// the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS().  For
699// that, we declare param_value_ to be a static member of
700// GeneratorEvaluationTest and initialize it to 0.  We set it to 1 in
701// main(), just before invocation of InitGoogleTest().  After calling
702// InitGoogleTest(), we set the value to 2.  If the sequence is evaluated
703// before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a
704// test with parameter other than 1, and the test body will fail the
705// assertion.
706class GeneratorEvaluationTest : public TestWithParam<int> {
707 public:
708  static int param_value() { return param_value_; }
709  static void set_param_value(int param_value) { param_value_ = param_value; }
710
711 private:
712  static int param_value_;
713};
714int GeneratorEvaluationTest::param_value_ = 0;
715
716TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) {
717  EXPECT_EQ(1, GetParam());
718}
719INSTANTIATE_TEST_CASE_P(GenEvalModule,
720                        GeneratorEvaluationTest,
721                        Values(GeneratorEvaluationTest::param_value()));
722
723// Tests that generators defined in a different translation unit are
724// functional. Generator extern_gen is defined in gtest-param-test_test2.cc.
725extern ParamGenerator<int> extern_gen;
726class ExternalGeneratorTest : public TestWithParam<int> {};
727TEST_P(ExternalGeneratorTest, ExternalGenerator) {
728  // Sequence produced by extern_gen contains only a single value
729  // which we verify here.
730  EXPECT_EQ(GetParam(), 33);
731}
732INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule,
733                        ExternalGeneratorTest,
734                        extern_gen);
735
736// Tests that a parameterized test case can be defined in one translation
737// unit and instantiated in another. This test will be instantiated in
738// gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is
739// defined in gtest-param-test_test.h.
740TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
741  EXPECT_EQ(0, GetParam() % 33);
742}
743
744// Tests that a parameterized test case can be instantiated with multiple
745// generators.
746class MultipleInstantiationTest : public TestWithParam<int> {};
747TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {
748}
749INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
750INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
751
752// Tests that a parameterized test case can be instantiated
753// in multiple translation units. This test will be instantiated
754// here and in gtest-param-test_test2.cc.
755// InstantiationInMultipleTranslationUnitsTest fixture class
756// is defined in gtest-param-test_test.h.
757TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) {
758  EXPECT_EQ(0, GetParam() % 42);
759}
760INSTANTIATE_TEST_CASE_P(Sequence1,
761                        InstantiationInMultipleTranslaionUnitsTest,
762                        Values(42, 42*2));
763
764// Tests that each iteration of parameterized test runs in a separate test
765// object.
766class SeparateInstanceTest : public TestWithParam<int> {
767 public:
768  SeparateInstanceTest() : count_(0) {}
769
770  static void TearDownTestCase() {
771    EXPECT_GE(global_count_, 2)
772        << "If some (but not all) SeparateInstanceTest tests have been "
773        << "filtered out this test will fail. Make sure that all "
774        << "GeneratorEvaluationTest are selected or de-selected together "
775        << "by the test filter.";
776  }
777
778 protected:
779  int count_;
780  static int global_count_;
781};
782int SeparateInstanceTest::global_count_ = 0;
783
784TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) {
785  EXPECT_EQ(0, count_++);
786  global_count_++;
787}
788INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4));
789
790// Tests that all instantiations of a test have named appropriately. Test
791// defined with TEST_P(TestCaseName, TestName) and instantiated with
792// INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named
793// SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the
794// sequence element used to instantiate the test.
795class NamingTest : public TestWithParam<int> {};
796
797TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
798  const ::testing::TestInfo* const test_info =
799     ::testing::UnitTest::GetInstance()->current_test_info();
800
801  EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name());
802
803  Message index_stream;
804  index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam();
805  EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name());
806
807  EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
808}
809
810INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));
811
812// Tests that user supplied custom parameter names are working correctly.
813// Runs the test with a builtin helper method which uses PrintToString,
814// as well as a custom function and custom functor to ensure all possible
815// uses work correctly.
816class CustomFunctorNamingTest : public TestWithParam<std::string> {};
817TEST_P(CustomFunctorNamingTest, CustomTestNames) {}
818
819struct CustomParamNameFunctor {
820  std::string operator()(const ::testing::TestParamInfo<std::string>& info) {
821    return info.param;
822  }
823};
824
825INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor,
826                        CustomFunctorNamingTest,
827                        Values(std::string("FunctorName")),
828                        CustomParamNameFunctor());
829
830INSTANTIATE_TEST_CASE_P(AllAllowedCharacters,
831                        CustomFunctorNamingTest,
832                        Values("abcdefghijklmnopqrstuvwxyz",
833                               "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
834                               "01234567890_"),
835                        CustomParamNameFunctor());
836
837inline std::string CustomParamNameFunction(
838    const ::testing::TestParamInfo<std::string>& info) {
839  return info.param;
840}
841
842class CustomFunctionNamingTest : public TestWithParam<std::string> {};
843TEST_P(CustomFunctionNamingTest, CustomTestNames) {}
844
845INSTANTIATE_TEST_CASE_P(CustomParamNameFunction,
846                        CustomFunctionNamingTest,
847                        Values(std::string("FunctionName")),
848                        CustomParamNameFunction);
849
850#if GTEST_LANG_CXX11
851
852// Test custom naming with a lambda
853
854class CustomLambdaNamingTest : public TestWithParam<std::string> {};
855TEST_P(CustomLambdaNamingTest, CustomTestNames) {}
856
857INSTANTIATE_TEST_CASE_P(CustomParamNameLambda,
858                        CustomLambdaNamingTest,
859                        Values(std::string("LambdaName")),
860                        [](const ::testing::TestParamInfo<std::string>& info) {
861                          return info.param;
862                        });
863
864#endif  // GTEST_LANG_CXX11
865
866TEST(CustomNamingTest, CheckNameRegistry) {
867  ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance();
868  std::set<std::string> test_names;
869  for (int case_num = 0;
870       case_num < unit_test->total_test_case_count();
871       ++case_num) {
872    const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num);
873    for (int test_num = 0;
874         test_num < test_case->total_test_count();
875         ++test_num) {
876      const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num);
877      test_names.insert(std::string(test_info->name()));
878    }
879  }
880  EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName"));
881  EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName"));
882#if GTEST_LANG_CXX11
883  EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName"));
884#endif  // GTEST_LANG_CXX11
885}
886
887// Test a numeric name to ensure PrintToStringParamName works correctly.
888
889class CustomIntegerNamingTest : public TestWithParam<int> {};
890
891TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
892  const ::testing::TestInfo* const test_info =
893     ::testing::UnitTest::GetInstance()->current_test_info();
894  Message test_name_stream;
895  test_name_stream << "TestsReportCorrectNames/" << GetParam();
896  EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
897}
898
899INSTANTIATE_TEST_CASE_P(PrintToString,
900                        CustomIntegerNamingTest,
901                        Range(0, 5),
902                        ::testing::PrintToStringParamName());
903
904// Test a custom struct with PrintToString.
905
906struct CustomStruct {
907  explicit CustomStruct(int value) : x(value) {}
908  int x;
909};
910
911std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) {
912  stream << val.x;
913  return stream;
914}
915
916class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
917
918TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
919  const ::testing::TestInfo* const test_info =
920     ::testing::UnitTest::GetInstance()->current_test_info();
921  Message test_name_stream;
922  test_name_stream << "TestsReportCorrectNames/" << GetParam();
923  EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
924}
925
926INSTANTIATE_TEST_CASE_P(PrintToString,
927                        CustomStructNamingTest,
928                        Values(CustomStruct(0), CustomStruct(1)),
929                        ::testing::PrintToStringParamName());
930
931// Test that using a stateful parameter naming function works as expected.
932
933struct StatefulNamingFunctor {
934  StatefulNamingFunctor() : sum(0) {}
935  std::string operator()(const ::testing::TestParamInfo<int>& info) {
936    int value = info.param + sum;
937    sum += info.param;
938    return ::testing::PrintToString(value);
939  }
940  int sum;
941};
942
943class StatefulNamingTest : public ::testing::TestWithParam<int> {
944 protected:
945  StatefulNamingTest() : sum_(0) {}
946  int sum_;
947};
948
949TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
950  const ::testing::TestInfo* const test_info =
951     ::testing::UnitTest::GetInstance()->current_test_info();
952  sum_ += GetParam();
953  Message test_name_stream;
954  test_name_stream << "TestsReportCorrectNames/" << sum_;
955  EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
956}
957
958INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor,
959                        StatefulNamingTest,
960                        Range(0, 5),
961                        StatefulNamingFunctor());
962
963// Class that cannot be streamed into an ostream.  It needs to be copyable
964// (and, in case of MSVC, also assignable) in order to be a test parameter
965// type.  Its default copy constructor and assignment operator do exactly
966// what we need.
967class Unstreamable {
968 public:
969  explicit Unstreamable(int value) : value_(value) {}
970
971 private:
972  int value_;
973};
974
975class CommentTest : public TestWithParam<Unstreamable> {};
976
977TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
978  const ::testing::TestInfo* const test_info =
979     ::testing::UnitTest::GetInstance()->current_test_info();
980
981  EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
982}
983
984INSTANTIATE_TEST_CASE_P(InstantiationWithComments,
985                        CommentTest,
986                        Values(Unstreamable(1)));
987
988// Verify that we can create a hierarchy of test fixtures, where the base
989// class fixture is not parameterized and the derived class is. In this case
990// ParameterizedDerivedTest inherits from NonParameterizedBaseTest.  We
991// perform simple tests on both.
992class NonParameterizedBaseTest : public ::testing::Test {
993 public:
994  NonParameterizedBaseTest() : n_(17) { }
995 protected:
996  int n_;
997};
998
999class ParameterizedDerivedTest : public NonParameterizedBaseTest,
1000                                 public ::testing::WithParamInterface<int> {
1001 protected:
1002  ParameterizedDerivedTest() : count_(0) { }
1003  int count_;
1004  static int global_count_;
1005};
1006
1007int ParameterizedDerivedTest::global_count_ = 0;
1008
1009TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) {
1010  EXPECT_EQ(17, n_);
1011}
1012
1013TEST_P(ParameterizedDerivedTest, SeesSequence) {
1014  EXPECT_EQ(17, n_);
1015  EXPECT_EQ(0, count_++);
1016  EXPECT_EQ(GetParam(), global_count_++);
1017}
1018
1019class ParameterizedDeathTest : public ::testing::TestWithParam<int> { };
1020
1021TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
1022  EXPECT_DEATH_IF_SUPPORTED(GetParam(),
1023                            ".* value-parameterized test .*");
1024}
1025
1026INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5));
1027
1028#endif  // GTEST_HAS_PARAM_TEST
1029
1030TEST(CompileTest, CombineIsDefinedOnlyWhenGtestHasParamTestIsDefined) {
1031#if GTEST_HAS_COMBINE && !GTEST_HAS_PARAM_TEST
1032  FAIL() << "GTEST_HAS_COMBINE is defined while GTEST_HAS_PARAM_TEST is not\n"
1033#endif
1034}
1035
1036int main(int argc, char **argv) {
1037#if GTEST_HAS_PARAM_TEST
1038  // Used in TestGenerationTest test case.
1039  AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
1040  // Used in GeneratorEvaluationTest test case. Tests that the updated value
1041  // will be picked up for instantiating tests in GeneratorEvaluationTest.
1042  GeneratorEvaluationTest::set_param_value(1);
1043#endif  // GTEST_HAS_PARAM_TEST
1044
1045  ::testing::InitGoogleTest(&argc, argv);
1046
1047#if GTEST_HAS_PARAM_TEST
1048  // Used in GeneratorEvaluationTest test case. Tests that value updated
1049  // here will NOT be used for instantiating tests in
1050  // GeneratorEvaluationTest.
1051  GeneratorEvaluationTest::set_param_value(2);
1052#endif  // GTEST_HAS_PARAM_TEST
1053
1054  return RUN_ALL_TESTS();
1055}
trunk/3rdparty/googletest/googletest/test/gtest-param-test_test.h
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: vladl@google.com (Vlad Losev)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file provides classes and functions used internally
35// for testing Google Test itself.
36
37#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
38#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
39
40#include "gtest/gtest.h"
41
42#if GTEST_HAS_PARAM_TEST
43
44// Test fixture for testing definition and instantiation of a test
45// in separate translation units.
46class ExternalInstantiationTest : public ::testing::TestWithParam<int> {
47};
48
49// Test fixture for testing instantiation of a test in multiple
50// translation units.
51class InstantiationInMultipleTranslaionUnitsTest
52    : public ::testing::TestWithParam<int> {
53};
54
55#endif  // GTEST_HAS_PARAM_TEST
56
57#endif  // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
trunk/3rdparty/googletest/googletest/test/gtest-port_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan)
31//
32// This file tests the internal cross-platform support utilities.
33
34#include "gtest/internal/gtest-port.h"
35
36#include <stdio.h>
37
38#if GTEST_OS_MAC
39# include <time.h>
40#endif  // GTEST_OS_MAC
41
42#include <list>
43#include <utility>  // For std::pair and std::make_pair.
44#include <vector>
45
46#include "gtest/gtest.h"
47#include "gtest/gtest-spi.h"
48
49// Indicates that this translation unit is part of Google Test's
50// implementation.  It must come before gtest-internal-inl.h is
51// included, or there will be a compiler error.  This trick is to
52// prevent a user from accidentally including gtest-internal-inl.h in
53// his code.
54#define GTEST_IMPLEMENTATION_ 1
55#include "src/gtest-internal-inl.h"
56#undef GTEST_IMPLEMENTATION_
57
58using std::make_pair;
59using std::pair;
60
61namespace testing {
62namespace internal {
63
64TEST(IsXDigitTest, WorksForNarrowAscii) {
65  EXPECT_TRUE(IsXDigit('0'));
66  EXPECT_TRUE(IsXDigit('9'));
67  EXPECT_TRUE(IsXDigit('A'));
68  EXPECT_TRUE(IsXDigit('F'));
69  EXPECT_TRUE(IsXDigit('a'));
70  EXPECT_TRUE(IsXDigit('f'));
71
72  EXPECT_FALSE(IsXDigit('-'));
73  EXPECT_FALSE(IsXDigit('g'));
74  EXPECT_FALSE(IsXDigit('G'));
75}
76
77TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
78  EXPECT_FALSE(IsXDigit(static_cast<char>(0x80)));
79  EXPECT_FALSE(IsXDigit(static_cast<char>('0' | 0x80)));
80}
81
82TEST(IsXDigitTest, WorksForWideAscii) {
83  EXPECT_TRUE(IsXDigit(L'0'));
84  EXPECT_TRUE(IsXDigit(L'9'));
85  EXPECT_TRUE(IsXDigit(L'A'));
86  EXPECT_TRUE(IsXDigit(L'F'));
87  EXPECT_TRUE(IsXDigit(L'a'));
88  EXPECT_TRUE(IsXDigit(L'f'));
89
90  EXPECT_FALSE(IsXDigit(L'-'));
91  EXPECT_FALSE(IsXDigit(L'g'));
92  EXPECT_FALSE(IsXDigit(L'G'));
93}
94
95TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
96  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
97  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
98  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
99}
100
101class Base {
102 public:
103  // Copy constructor and assignment operator do exactly what we need, so we
104  // use them.
105  Base() : member_(0) {}
106  explicit Base(int n) : member_(n) {}
107  virtual ~Base() {}
108  int member() { return member_; }
109
110 private:
111  int member_;
112};
113
114class Derived : public Base {
115 public:
116  explicit Derived(int n) : Base(n) {}
117};
118
119TEST(ImplicitCastTest, ConvertsPointers) {
120  Derived derived(0);
121  EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
122}
123
124TEST(ImplicitCastTest, CanUseInheritance) {
125  Derived derived(1);
126  Base base = ::testing::internal::ImplicitCast_<Base>(derived);
127  EXPECT_EQ(derived.member(), base.member());
128}
129
130class Castable {
131 public:
132  explicit Castable(bool* converted) : converted_(converted) {}
133  operator Base() {
134    *converted_ = true;
135    return Base();
136  }
137
138 private:
139  bool* converted_;
140};
141
142TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
143  bool converted = false;
144  Castable castable(&converted);
145  Base base = ::testing::internal::ImplicitCast_<Base>(castable);
146  EXPECT_TRUE(converted);
147}
148
149class ConstCastable {
150 public:
151  explicit ConstCastable(bool* converted) : converted_(converted) {}
152  operator Base() const {
153    *converted_ = true;
154    return Base();
155  }
156
157 private:
158  bool* converted_;
159};
160
161TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
162  bool converted = false;
163  const ConstCastable const_castable(&converted);
164  Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
165  EXPECT_TRUE(converted);
166}
167
168class ConstAndNonConstCastable {
169 public:
170  ConstAndNonConstCastable(bool* converted, bool* const_converted)
171      : converted_(converted), const_converted_(const_converted) {}
172  operator Base() {
173    *converted_ = true;
174    return Base();
175  }
176  operator Base() const {
177    *const_converted_ = true;
178    return Base();
179  }
180
181 private:
182  bool* converted_;
183  bool* const_converted_;
184};
185
186TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
187  bool converted = false;
188  bool const_converted = false;
189  ConstAndNonConstCastable castable(&converted, &const_converted);
190  Base base = ::testing::internal::ImplicitCast_<Base>(castable);
191  EXPECT_TRUE(converted);
192  EXPECT_FALSE(const_converted);
193
194  converted = false;
195  const_converted = false;
196  const ConstAndNonConstCastable const_castable(&converted, &const_converted);
197  base = ::testing::internal::ImplicitCast_<Base>(const_castable);
198  EXPECT_FALSE(converted);
199  EXPECT_TRUE(const_converted);
200}
201
202class To {
203 public:
204  To(bool* converted) { *converted = true; }  // NOLINT
205};
206
207TEST(ImplicitCastTest, CanUseImplicitConstructor) {
208  bool converted = false;
209  To to = ::testing::internal::ImplicitCast_<To>(&converted);
210  (void)to;
211  EXPECT_TRUE(converted);
212}
213
214TEST(IteratorTraitsTest, WorksForSTLContainerIterators) {
215  StaticAssertTypeEq<int,
216      IteratorTraits< ::std::vector<int>::const_iterator>::value_type>();
217  StaticAssertTypeEq<bool,
218      IteratorTraits< ::std::list<bool>::iterator>::value_type>();
219}
220
221TEST(IteratorTraitsTest, WorksForPointerToNonConst) {
222  StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>();
223  StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>();
224}
225
226TEST(IteratorTraitsTest, WorksForPointerToConst) {
227  StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>();
228  StaticAssertTypeEq<const void*,
229      IteratorTraits<const void* const*>::value_type>();
230}
231
232// Tests that the element_type typedef is available in scoped_ptr and refers
233// to the parameter type.
234TEST(ScopedPtrTest, DefinesElementType) {
235  StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
236}
237
238// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests.
239
240TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
241  if (AlwaysFalse())
242    GTEST_CHECK_(false) << "This should never be executed; "
243                           "It's a compilation test only.";
244
245  if (AlwaysTrue())
246    GTEST_CHECK_(true);
247  else
248    ;  // NOLINT
249
250  if (AlwaysFalse())
251    ;  // NOLINT
252  else
253    GTEST_CHECK_(true) << "";
254}
255
256TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
257  switch (0) {
258    case 1:
259      break;
260    default:
261      GTEST_CHECK_(true);
262  }
263
264  switch (0)
265    case 0:
266      GTEST_CHECK_(true) << "Check failed in switch case";
267}
268
269// Verifies behavior of FormatFileLocation.
270TEST(FormatFileLocationTest, FormatsFileLocation) {
271  EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
272  EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
273}
274
275TEST(FormatFileLocationTest, FormatsUnknownFile) {
276  EXPECT_PRED_FORMAT2(
277      IsSubstring, "unknown file", FormatFileLocation(NULL, 42));
278  EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42));
279}
280
281TEST(FormatFileLocationTest, FormatsUknownLine) {
282  EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
283}
284
285TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
286  EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1));
287}
288
289// Verifies behavior of FormatCompilerIndependentFileLocation.
290TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
291  EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
292}
293
294TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
295  EXPECT_EQ("unknown file:42",
296            FormatCompilerIndependentFileLocation(NULL, 42));
297}
298
299TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
300  EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
301}
302
303TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
304  EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
305}
306
307#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
308void* ThreadFunc(void* data) {
309  internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
310  mutex->Lock();
311  mutex->Unlock();
312  return NULL;
313}
314
315TEST(GetThreadCountTest, ReturnsCorrectValue) {
316  const size_t starting_count = GetThreadCount();
317  pthread_t       thread_id;
318
319  internal::Mutex mutex;
320  {
321    internal::MutexLock lock(&mutex);
322    pthread_attr_t  attr;
323    ASSERT_EQ(0, pthread_attr_init(&attr));
324    ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
325
326    const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
327    ASSERT_EQ(0, pthread_attr_destroy(&attr));
328    ASSERT_EQ(0, status);
329    EXPECT_EQ(starting_count + 1, GetThreadCount());
330  }
331
332  void* dummy;
333  ASSERT_EQ(0, pthread_join(thread_id, &dummy));
334
335  // The OS may not immediately report the updated thread count after
336  // joining a thread, causing flakiness in this test. To counter that, we
337  // wait for up to .5 seconds for the OS to report the correct value.
338  for (int i = 0; i < 5; ++i) {
339    if (GetThreadCount() == starting_count)
340      break;
341
342    SleepMilliseconds(100);
343  }
344
345  EXPECT_EQ(starting_count, GetThreadCount());
346}
347#else
348TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
349  EXPECT_EQ(0U, GetThreadCount());
350}
351#endif  // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
352
353TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
354  const bool a_false_condition = false;
355  const char regex[] =
356#ifdef _MSC_VER
357     "gtest-port_test\\.cc\\(\\d+\\):"
358#elif GTEST_USES_POSIX_RE
359     "gtest-port_test\\.cc:[0-9]+"
360#else
361     "gtest-port_test\\.cc:\\d+"
362#endif  // _MSC_VER
363     ".*a_false_condition.*Extra info.*";
364
365  EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
366                            regex);
367}
368
369#if GTEST_HAS_DEATH_TEST
370
371TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
372  EXPECT_EXIT({
373      GTEST_CHECK_(true) << "Extra info";
374      ::std::cerr << "Success\n";
375      exit(0); },
376      ::testing::ExitedWithCode(0), "Success");
377}
378
379#endif  // GTEST_HAS_DEATH_TEST
380
381// Verifies that Google Test choose regular expression engine appropriate to
382// the platform. The test will produce compiler errors in case of failure.
383// For simplicity, we only cover the most important platforms here.
384TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
385#if !GTEST_USES_PCRE
386# if GTEST_HAS_POSIX_RE
387
388  EXPECT_TRUE(GTEST_USES_POSIX_RE);
389
390# else
391
392  EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
393
394# endif
395#endif  // !GTEST_USES_PCRE
396}
397
398#if GTEST_USES_POSIX_RE
399
400# if GTEST_HAS_TYPED_TEST
401
402template <typename Str>
403class RETest : public ::testing::Test {};
404
405// Defines StringTypes as the list of all string types that class RE
406// supports.
407typedef testing::Types<
408    ::std::string,
409#  if GTEST_HAS_GLOBAL_STRING
410    ::string,
411#  endif  // GTEST_HAS_GLOBAL_STRING
412    const char*> StringTypes;
413
414TYPED_TEST_CASE(RETest, StringTypes);
415
416// Tests RE's implicit constructors.
417TYPED_TEST(RETest, ImplicitConstructorWorks) {
418  const RE empty(TypeParam(""));
419  EXPECT_STREQ("", empty.pattern());
420
421  const RE simple(TypeParam("hello"));
422  EXPECT_STREQ("hello", simple.pattern());
423
424  const RE normal(TypeParam(".*(\\w+)"));
425  EXPECT_STREQ(".*(\\w+)", normal.pattern());
426}
427
428// Tests that RE's constructors reject invalid regular expressions.
429TYPED_TEST(RETest, RejectsInvalidRegex) {
430  EXPECT_NONFATAL_FAILURE({
431    const RE invalid(TypeParam("?"));
432  }, "\"?\" is not a valid POSIX Extended regular expression.");
433}
434
435// Tests RE::FullMatch().
436TYPED_TEST(RETest, FullMatchWorks) {
437  const RE empty(TypeParam(""));
438  EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
439  EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
440
441  const RE re(TypeParam("a.*z"));
442  EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
443  EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
444  EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
445  EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
446}
447
448// Tests RE::PartialMatch().
449TYPED_TEST(RETest, PartialMatchWorks) {
450  const RE empty(TypeParam(""));
451  EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
452  EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
453
454  const RE re(TypeParam("a.*z"));
455  EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
456  EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
457  EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
458  EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
459  EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
460}
461
462# endif  // GTEST_HAS_TYPED_TEST
463
464#elif GTEST_USES_SIMPLE_RE
465
466TEST(IsInSetTest, NulCharIsNotInAnySet) {
467  EXPECT_FALSE(IsInSet('\0', ""));
468  EXPECT_FALSE(IsInSet('\0', "\0"));
469  EXPECT_FALSE(IsInSet('\0', "a"));
470}
471
472TEST(IsInSetTest, WorksForNonNulChars) {
473  EXPECT_FALSE(IsInSet('a', "Ab"));
474  EXPECT_FALSE(IsInSet('c', ""));
475
476  EXPECT_TRUE(IsInSet('b', "bcd"));
477  EXPECT_TRUE(IsInSet('b', "ab"));
478}
479
480TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
481  EXPECT_FALSE(IsAsciiDigit('\0'));
482  EXPECT_FALSE(IsAsciiDigit(' '));
483  EXPECT_FALSE(IsAsciiDigit('+'));
484  EXPECT_FALSE(IsAsciiDigit('-'));
485  EXPECT_FALSE(IsAsciiDigit('.'));
486  EXPECT_FALSE(IsAsciiDigit('a'));
487}
488
489TEST(IsAsciiDigitTest, IsTrueForDigit) {
490  EXPECT_TRUE(IsAsciiDigit('0'));
491  EXPECT_TRUE(IsAsciiDigit('1'));
492  EXPECT_TRUE(IsAsciiDigit('5'));
493  EXPECT_TRUE(IsAsciiDigit('9'));
494}
495
496TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
497  EXPECT_FALSE(IsAsciiPunct('\0'));
498  EXPECT_FALSE(IsAsciiPunct(' '));
499  EXPECT_FALSE(IsAsciiPunct('\n'));
500  EXPECT_FALSE(IsAsciiPunct('a'));
501  EXPECT_FALSE(IsAsciiPunct('0'));
502}
503
504TEST(IsAsciiPunctTest, IsTrueForPunct) {
505  for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
506    EXPECT_PRED1(IsAsciiPunct, *p);
507  }
508}
509
510TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
511  EXPECT_FALSE(IsRepeat('\0'));
512  EXPECT_FALSE(IsRepeat(' '));
513  EXPECT_FALSE(IsRepeat('a'));
514  EXPECT_FALSE(IsRepeat('1'));
515  EXPECT_FALSE(IsRepeat('-'));
516}
517
518TEST(IsRepeatTest, IsTrueForRepeatChar) {
519  EXPECT_TRUE(IsRepeat('?'));
520  EXPECT_TRUE(IsRepeat('*'));
521  EXPECT_TRUE(IsRepeat('+'));
522}
523
524TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
525  EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
526  EXPECT_FALSE(IsAsciiWhiteSpace('a'));
527  EXPECT_FALSE(IsAsciiWhiteSpace('1'));
528  EXPECT_FALSE(IsAsciiWhiteSpace('+'));
529  EXPECT_FALSE(IsAsciiWhiteSpace('_'));
530}
531
532TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
533  EXPECT_TRUE(IsAsciiWhiteSpace(' '));
534  EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
535  EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
536  EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
537  EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
538  EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
539}
540
541TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
542  EXPECT_FALSE(IsAsciiWordChar('\0'));
543  EXPECT_FALSE(IsAsciiWordChar('+'));
544  EXPECT_FALSE(IsAsciiWordChar('.'));
545  EXPECT_FALSE(IsAsciiWordChar(' '));
546  EXPECT_FALSE(IsAsciiWordChar('\n'));
547}
548
549TEST(IsAsciiWordCharTest, IsTrueForLetter) {
550  EXPECT_TRUE(IsAsciiWordChar('a'));
551  EXPECT_TRUE(IsAsciiWordChar('b'));
552  EXPECT_TRUE(IsAsciiWordChar('A'));
553  EXPECT_TRUE(IsAsciiWordChar('Z'));
554}
555
556TEST(IsAsciiWordCharTest, IsTrueForDigit) {
557  EXPECT_TRUE(IsAsciiWordChar('0'));
558  EXPECT_TRUE(IsAsciiWordChar('1'));
559  EXPECT_TRUE(IsAsciiWordChar('7'));
560  EXPECT_TRUE(IsAsciiWordChar('9'));
561}
562
563TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
564  EXPECT_TRUE(IsAsciiWordChar('_'));
565}
566
567TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
568  EXPECT_FALSE(IsValidEscape('\0'));
569  EXPECT_FALSE(IsValidEscape('\007'));
570}
571
572TEST(IsValidEscapeTest, IsFalseForDigit) {
573  EXPECT_FALSE(IsValidEscape('0'));
574  EXPECT_FALSE(IsValidEscape('9'));
575}
576
577TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
578  EXPECT_FALSE(IsValidEscape(' '));
579  EXPECT_FALSE(IsValidEscape('\n'));
580}
581
582TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
583  EXPECT_FALSE(IsValidEscape('a'));
584  EXPECT_FALSE(IsValidEscape('Z'));
585}
586
587TEST(IsValidEscapeTest, IsTrueForPunct) {
588  EXPECT_TRUE(IsValidEscape('.'));
589  EXPECT_TRUE(IsValidEscape('-'));
590  EXPECT_TRUE(IsValidEscape('^'));
591  EXPECT_TRUE(IsValidEscape('$'));
592  EXPECT_TRUE(IsValidEscape('('));
593  EXPECT_TRUE(IsValidEscape(']'));
594  EXPECT_TRUE(IsValidEscape('{'));
595  EXPECT_TRUE(IsValidEscape('|'));
596}
597
598TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
599  EXPECT_TRUE(IsValidEscape('d'));
600  EXPECT_TRUE(IsValidEscape('D'));
601  EXPECT_TRUE(IsValidEscape('s'));
602  EXPECT_TRUE(IsValidEscape('S'));
603  EXPECT_TRUE(IsValidEscape('w'));
604  EXPECT_TRUE(IsValidEscape('W'));
605}
606
607TEST(AtomMatchesCharTest, EscapedPunct) {
608  EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
609  EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
610  EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
611  EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
612
613  EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
614  EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
615  EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
616  EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
617}
618
619TEST(AtomMatchesCharTest, Escaped_d) {
620  EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
621  EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
622  EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
623
624  EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
625  EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
626}
627
628TEST(AtomMatchesCharTest, Escaped_D) {
629  EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
630  EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
631
632  EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
633  EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
634  EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
635}
636
637TEST(AtomMatchesCharTest, Escaped_s) {
638  EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
639  EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
640  EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
641  EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
642
643  EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
644  EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
645  EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
646}
647
648TEST(AtomMatchesCharTest, Escaped_S) {
649  EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
650  EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
651
652  EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
653  EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
654  EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
655}
656
657TEST(AtomMatchesCharTest, Escaped_w) {
658  EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
659  EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
660  EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
661  EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
662
663  EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
664  EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
665  EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
666  EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
667}
668
669TEST(AtomMatchesCharTest, Escaped_W) {
670  EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
671  EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
672  EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
673  EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
674
675  EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
676  EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
677  EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
678}
679
680TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
681  EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
682  EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
683  EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
684  EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
685  EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
686  EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
687  EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
688  EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
689  EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
690  EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
691
692  EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
693  EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
694  EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
695  EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
696  EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
697}
698
699TEST(AtomMatchesCharTest, UnescapedDot) {
700  EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
701
702  EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
703  EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
704  EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
705  EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
706}
707
708TEST(AtomMatchesCharTest, UnescapedChar) {
709  EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
710  EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
711  EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
712
713  EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
714  EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
715  EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
716}
717
718TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
719  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
720                          "NULL is not a valid simple regular expression");
721  EXPECT_NONFATAL_FAILURE(
722      ASSERT_FALSE(ValidateRegex("a\\")),
723      "Syntax error at index 1 in simple regular expression \"a\\\": ");
724  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
725                          "'\\' cannot appear at the end");
726  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
727                          "'\\' cannot appear at the end");
728  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
729                          "invalid escape sequence \"\\h\"");
730  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
731                          "'^' can only appear at the beginning");
732  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
733                          "'^' can only appear at the beginning");
734  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
735                          "'$' can only appear at the end");
736  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
737                          "'$' can only appear at the end");
738  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
739                          "'(' is unsupported");
740  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
741                          "')' is unsupported");
742  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
743                          "'[' is unsupported");
744  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
745                          "'{' is unsupported");
746  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
747                          "'?' can only follow a repeatable token");
748  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
749                          "'*' can only follow a repeatable token");
750  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
751                          "'+' can only follow a repeatable token");
752}
753
754TEST(ValidateRegexTest, ReturnsTrueForValid) {
755  EXPECT_TRUE(ValidateRegex(""));
756  EXPECT_TRUE(ValidateRegex("a"));
757  EXPECT_TRUE(ValidateRegex(".*"));
758  EXPECT_TRUE(ValidateRegex("^a_+"));
759  EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
760  EXPECT_TRUE(ValidateRegex("09*$"));
761  EXPECT_TRUE(ValidateRegex("^Z$"));
762  EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
763}
764
765TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
766  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
767  // Repeating more than once.
768  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
769
770  // Repeating zero times.
771  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
772  // Repeating once.
773  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
774  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
775}
776
777TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
778  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
779
780  // Repeating zero times.
781  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
782  // Repeating once.
783  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
784  // Repeating more than once.
785  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
786}
787
788TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
789  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
790  // Repeating zero times.
791  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
792
793  // Repeating once.
794  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
795  // Repeating more than once.
796  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
797}
798
799TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
800  EXPECT_TRUE(MatchRegexAtHead("", ""));
801  EXPECT_TRUE(MatchRegexAtHead("", "ab"));
802}
803
804TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
805  EXPECT_FALSE(MatchRegexAtHead("$", "a"));
806
807  EXPECT_TRUE(MatchRegexAtHead("$", ""));
808  EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
809}
810
811TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
812  EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
813  EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
814
815  EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
816  EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
817}
818
819TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
820  EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
821  EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
822
823  EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
824  EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
825  EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
826}
827
828TEST(MatchRegexAtHeadTest,
829     WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
830  EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
831  EXPECT_FALSE(MatchRegexAtHead("\\s?b", "  b"));
832
833  EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
834  EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
835  EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
836  EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
837}
838
839TEST(MatchRegexAtHeadTest, MatchesSequentially) {
840  EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
841
842  EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
843}
844
845TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
846  EXPECT_FALSE(MatchRegexAnywhere("", NULL));
847}
848
849TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
850  EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
851  EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
852
853  EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
854  EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
855  EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
856}
857
858TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
859  EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
860  EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
861}
862
863TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
864  EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
865  EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
866  EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
867}
868
869TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
870  EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
871  EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "=  ...="));
872}
873
874// Tests RE's implicit constructors.
875TEST(RETest, ImplicitConstructorWorks) {
876  const RE empty("");
877  EXPECT_STREQ("", empty.pattern());
878
879  const RE simple("hello");
880  EXPECT_STREQ("hello", simple.pattern());
881}
882
883// Tests that RE's constructors reject invalid regular expressions.
884TEST(RETest, RejectsInvalidRegex) {
885  EXPECT_NONFATAL_FAILURE({
886    const RE normal(NULL);
887  }, "NULL is not a valid simple regular expression");
888
889  EXPECT_NONFATAL_FAILURE({
890    const RE normal(".*(\\w+");
891  }, "'(' is unsupported");
892
893  EXPECT_NONFATAL_FAILURE({
894    const RE invalid("^?");
895  }, "'?' can only follow a repeatable token");
896}
897
898// Tests RE::FullMatch().
899TEST(RETest, FullMatchWorks) {
900  const RE empty("");
901  EXPECT_TRUE(RE::FullMatch("", empty));
902  EXPECT_FALSE(RE::FullMatch("a", empty));
903
904  const RE re1("a");
905  EXPECT_TRUE(RE::FullMatch("a", re1));
906
907  const RE re("a.*z");
908  EXPECT_TRUE(RE::FullMatch("az", re));
909  EXPECT_TRUE(RE::FullMatch("axyz", re));
910  EXPECT_FALSE(RE::FullMatch("baz", re));
911  EXPECT_FALSE(RE::FullMatch("azy", re));
912}
913
914// Tests RE::PartialMatch().
915TEST(RETest, PartialMatchWorks) {
916  const RE empty("");
917  EXPECT_TRUE(RE::PartialMatch("", empty));
918  EXPECT_TRUE(RE::PartialMatch("a", empty));
919
920  const RE re("a.*z");
921  EXPECT_TRUE(RE::PartialMatch("az", re));
922  EXPECT_TRUE(RE::PartialMatch("axyz", re));
923  EXPECT_TRUE(RE::PartialMatch("baz", re));
924  EXPECT_TRUE(RE::PartialMatch("azy", re));
925  EXPECT_FALSE(RE::PartialMatch("zza", re));
926}
927
928#endif  // GTEST_USES_POSIX_RE
929
930#if !GTEST_OS_WINDOWS_MOBILE
931
932TEST(CaptureTest, CapturesStdout) {
933  CaptureStdout();
934  fprintf(stdout, "abc");
935  EXPECT_STREQ("abc", GetCapturedStdout().c_str());
936
937  CaptureStdout();
938  fprintf(stdout, "def%cghi", '\0');
939  EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
940}
941
942TEST(CaptureTest, CapturesStderr) {
943  CaptureStderr();
944  fprintf(stderr, "jkl");
945  EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
946
947  CaptureStderr();
948  fprintf(stderr, "jkl%cmno", '\0');
949  EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
950}
951
952// Tests that stdout and stderr capture don't interfere with each other.
953TEST(CaptureTest, CapturesStdoutAndStderr) {
954  CaptureStdout();
955  CaptureStderr();
956  fprintf(stdout, "pqr");
957  fprintf(stderr, "stu");
958  EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
959  EXPECT_STREQ("stu", GetCapturedStderr().c_str());
960}
961
962TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
963  CaptureStdout();
964  EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
965                            "Only one stdout capturer can exist at a time");
966  GetCapturedStdout();
967
968  // We cannot test stderr capturing using death tests as they use it
969  // themselves.
970}
971
972#endif  // !GTEST_OS_WINDOWS_MOBILE
973
974TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
975  ThreadLocal<int> t1;
976  EXPECT_EQ(0, t1.get());
977
978  ThreadLocal<void*> t2;
979  EXPECT_TRUE(t2.get() == NULL);
980}
981
982TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
983  ThreadLocal<int> t1(123);
984  EXPECT_EQ(123, t1.get());
985
986  int i = 0;
987  ThreadLocal<int*> t2(&i);
988  EXPECT_EQ(&i, t2.get());
989}
990
991class NoDefaultContructor {
992 public:
993  explicit NoDefaultContructor(const char*) {}
994  NoDefaultContructor(const NoDefaultContructor&) {}
995};
996
997TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
998  ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
999  bar.pointer();
1000}
1001
1002TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
1003  ThreadLocal<std::string> thread_local_string;
1004
1005  EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1006
1007  // Verifies the condition still holds after calling set.
1008  thread_local_string.set("foo");
1009  EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1010}
1011
1012TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1013  ThreadLocal<std::string> thread_local_string;
1014  const ThreadLocal<std::string>& const_thread_local_string =
1015      thread_local_string;
1016
1017  EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1018
1019  thread_local_string.set("foo");
1020  EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1021}
1022
1023#if GTEST_IS_THREADSAFE
1024
1025void AddTwo(int* param) { *param += 2; }
1026
1027TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1028  int i = 40;
1029  ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
1030  thread.Join();
1031  EXPECT_EQ(42, i);
1032}
1033
1034TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1035  // AssertHeld() is flaky only in the presence of multiple threads accessing
1036  // the lock. In this case, the test is robust.
1037  EXPECT_DEATH_IF_SUPPORTED({
1038    Mutex m;
1039    { MutexLock lock(&m); }
1040    m.AssertHeld();
1041  },
1042  "thread .*hold");
1043}
1044
1045TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1046  Mutex m;
1047  MutexLock lock(&m);
1048  m.AssertHeld();
1049}
1050
1051class AtomicCounterWithMutex {
1052 public:
1053  explicit AtomicCounterWithMutex(Mutex* mutex) :
1054    value_(0), mutex_(mutex), random_(42) {}
1055
1056  void Increment() {
1057    MutexLock lock(mutex_);
1058    int temp = value_;
1059    {
1060      // We need to put up a memory barrier to prevent reads and writes to
1061      // value_ rearranged with the call to SleepMilliseconds when observed
1062      // from other threads.
1063#if GTEST_HAS_PTHREAD
1064      // On POSIX, locking a mutex puts up a memory barrier.  We cannot use
1065      // Mutex and MutexLock here or rely on their memory barrier
1066      // functionality as we are testing them here.
1067      pthread_mutex_t memory_barrier_mutex;
1068      GTEST_CHECK_POSIX_SUCCESS_(
1069          pthread_mutex_init(&memory_barrier_mutex, NULL));
1070      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1071
1072      SleepMilliseconds(random_.Generate(30));
1073
1074      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1075      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1076#elif GTEST_OS_WINDOWS
1077      // On Windows, performing an interlocked access puts up a memory barrier.
1078      volatile LONG dummy = 0;
1079      ::InterlockedIncrement(&dummy);
1080      SleepMilliseconds(random_.Generate(30));
1081      ::InterlockedIncrement(&dummy);
1082#else
1083# error "Memory barrier not implemented on this platform."
1084#endif  // GTEST_HAS_PTHREAD
1085    }
1086    value_ = temp + 1;
1087  }
1088  int value() const { return value_; }
1089
1090 private:
1091  volatile int value_;
1092  Mutex* const mutex_;  // Protects value_.
1093  Random       random_;
1094};
1095
1096void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1097  for (int i = 0; i < param.second; ++i)
1098      param.first->Increment();
1099}
1100
1101// Tests that the mutex only lets one thread at a time to lock it.
1102TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1103  Mutex mutex;
1104  AtomicCounterWithMutex locked_counter(&mutex);
1105
1106  typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1107  const int kCycleCount = 20;
1108  const int kThreadCount = 7;
1109  scoped_ptr<ThreadType> counting_threads[kThreadCount];
1110  Notification threads_can_start;
1111  // Creates and runs kThreadCount threads that increment locked_counter
1112  // kCycleCount times each.
1113  for (int i = 0; i < kThreadCount; ++i) {
1114    counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
1115                                             make_pair(&locked_counter,
1116                                                       kCycleCount),
1117                                             &threads_can_start));
1118  }
1119  threads_can_start.Notify();
1120  for (int i = 0; i < kThreadCount; ++i)
1121    counting_threads[i]->Join();
1122
1123  // If the mutex lets more than one thread to increment the counter at a
1124  // time, they are likely to encounter a race condition and have some
1125  // increments overwritten, resulting in the lower then expected counter
1126  // value.
1127  EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1128}
1129
1130template <typename T>
1131void RunFromThread(void (func)(T), T param) {
1132  ThreadWithParam<T> thread(func, param, NULL);
1133  thread.Join();
1134}
1135
1136void RetrieveThreadLocalValue(
1137    pair<ThreadLocal<std::string>*, std::string*> param) {
1138  *param.second = param.first->get();
1139}
1140
1141TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1142  ThreadLocal<std::string> thread_local_string("foo");
1143  EXPECT_STREQ("foo", thread_local_string.get().c_str());
1144
1145  thread_local_string.set("bar");
1146  EXPECT_STREQ("bar", thread_local_string.get().c_str());
1147
1148  std::string result;
1149  RunFromThread(&RetrieveThreadLocalValue,
1150                make_pair(&thread_local_string, &result));
1151  EXPECT_STREQ("foo", result.c_str());
1152}
1153
1154// Keeps track of whether of destructors being called on instances of
1155// DestructorTracker.  On Windows, waits for the destructor call reports.
1156class DestructorCall {
1157 public:
1158  DestructorCall() {
1159    invoked_ = false;
1160#if GTEST_OS_WINDOWS
1161    wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1162    GTEST_CHECK_(wait_event_.Get() != NULL);
1163#endif
1164  }
1165
1166  bool CheckDestroyed() const {
1167#if GTEST_OS_WINDOWS
1168    if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1169      return false;
1170#endif
1171    return invoked_;
1172  }
1173
1174  void ReportDestroyed() {
1175    invoked_ = true;
1176#if GTEST_OS_WINDOWS
1177    ::SetEvent(wait_event_.Get());
1178#endif
1179  }
1180
1181  static std::vector<DestructorCall*>& List() { return *list_; }
1182
1183  static void ResetList() {
1184    for (size_t i = 0; i < list_->size(); ++i) {
1185      delete list_->at(i);
1186    }
1187    list_->clear();
1188  }
1189
1190 private:
1191  bool invoked_;
1192#if GTEST_OS_WINDOWS
1193  AutoHandle wait_event_;
1194#endif
1195  static std::vector<DestructorCall*>* const list_;
1196
1197  GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
1198};
1199
1200std::vector<DestructorCall*>* const DestructorCall::list_ =
1201    new std::vector<DestructorCall*>;
1202
1203// DestructorTracker keeps track of whether its instances have been
1204// destroyed.
1205class DestructorTracker {
1206 public:
1207  DestructorTracker() : index_(GetNewIndex()) {}
1208  DestructorTracker(const DestructorTracker& /* rhs */)
1209      : index_(GetNewIndex()) {}
1210  ~DestructorTracker() {
1211    // We never access DestructorCall::List() concurrently, so we don't need
1212    // to protect this acccess with a mutex.
1213    DestructorCall::List()[index_]->ReportDestroyed();
1214  }
1215
1216 private:
1217  static size_t GetNewIndex() {
1218    DestructorCall::List().push_back(new DestructorCall);
1219    return DestructorCall::List().size() - 1;
1220  }
1221  const size_t index_;
1222
1223  GTEST_DISALLOW_ASSIGN_(DestructorTracker);
1224};
1225
1226typedef ThreadLocal<DestructorTracker>* ThreadParam;
1227
1228void CallThreadLocalGet(ThreadParam thread_local_param) {
1229  thread_local_param->get();
1230}
1231
1232// Tests that when a ThreadLocal object dies in a thread, it destroys
1233// the managed object for that thread.
1234TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1235  DestructorCall::ResetList();
1236
1237  {
1238    ThreadLocal<DestructorTracker> thread_local_tracker;
1239    ASSERT_EQ(0U, DestructorCall::List().size());
1240
1241    // This creates another DestructorTracker object for the main thread.
1242    thread_local_tracker.get();
1243    ASSERT_EQ(1U, DestructorCall::List().size());
1244    ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1245  }
1246
1247  // Now thread_local_tracker has died.
1248  ASSERT_EQ(1U, DestructorCall::List().size());
1249  EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1250
1251  DestructorCall::ResetList();
1252}
1253
1254// Tests that when a thread exits, the thread-local object for that
1255// thread is destroyed.
1256TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1257  DestructorCall::ResetList();
1258
1259  {
1260    ThreadLocal<DestructorTracker> thread_local_tracker;
1261    ASSERT_EQ(0U, DestructorCall::List().size());
1262
1263    // This creates another DestructorTracker object in the new thread.
1264    ThreadWithParam<ThreadParam> thread(
1265        &CallThreadLocalGet, &thread_local_tracker, NULL);
1266    thread.Join();
1267
1268    // The thread has exited, and we should have a DestroyedTracker
1269    // instance created for it. But it may not have been destroyed yet.
1270    ASSERT_EQ(1U, DestructorCall::List().size());
1271  }
1272
1273  // The thread has exited and thread_local_tracker has died.
1274  ASSERT_EQ(1U, DestructorCall::List().size());
1275  EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1276
1277  DestructorCall::ResetList();
1278}
1279
1280TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1281  ThreadLocal<std::string> thread_local_string;
1282  thread_local_string.set("Foo");
1283  EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1284
1285  std::string result;
1286  RunFromThread(&RetrieveThreadLocalValue,
1287                make_pair(&thread_local_string, &result));
1288  EXPECT_TRUE(result.empty());
1289}
1290
1291#endif  // GTEST_IS_THREADSAFE
1292
1293#if GTEST_OS_WINDOWS
1294TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1295  StaticAssertTypeEq<HANDLE, void*>();
1296}
1297
1298TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1299  StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1300}
1301#endif  // GTEST_OS_WINDOWS
1302
1303}  // namespace internal
1304}  // namespace testing
trunk/3rdparty/googletest/googletest/test/gtest-printers_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Test - The Google C++ Testing Framework
33//
34// This file tests the universal value printer.
35
36#include "gtest/gtest-printers.h"
37
38#include <ctype.h>
39#include <limits.h>
40#include <string.h>
41#include <algorithm>
42#include <deque>
43#include <list>
44#include <map>
45#include <set>
46#include <sstream>
47#include <string>
48#include <utility>
49#include <vector>
50
51#include "gtest/gtest.h"
52
53// hash_map and hash_set are available under Visual C++, or on Linux.
54#if GTEST_HAS_HASH_MAP_
55# include <hash_map>            // NOLINT
56#endif  // GTEST_HAS_HASH_MAP_
57#if GTEST_HAS_HASH_SET_
58# include <hash_set>            // NOLINT
59#endif  // GTEST_HAS_HASH_SET_
60
61#if GTEST_HAS_STD_FORWARD_LIST_
62# include <forward_list> // NOLINT
63#endif  // GTEST_HAS_STD_FORWARD_LIST_
64
65// Some user-defined types for testing the universal value printer.
66
67// An anonymous enum type.
68enum AnonymousEnum {
69  kAE1 = -1,
70  kAE2 = 1
71};
72
73// An enum without a user-defined printer.
74enum EnumWithoutPrinter {
75  kEWP1 = -2,
76  kEWP2 = 42
77};
78
79// An enum with a << operator.
80enum EnumWithStreaming {
81  kEWS1 = 10
82};
83
84std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
85  return os << (e == kEWS1 ? "kEWS1" : "invalid");
86}
87
88// An enum with a PrintTo() function.
89enum EnumWithPrintTo {
90  kEWPT1 = 1
91};
92
93void PrintTo(EnumWithPrintTo e, std::ostream* os) {
94  *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
95}
96
97// A class implicitly convertible to BiggestInt.
98class BiggestIntConvertible {
99 public:
100  operator ::testing::internal::BiggestInt() const { return 42; }
101};
102
103// A user-defined unprintable class template in the global namespace.
104template <typename T>
105class UnprintableTemplateInGlobal {
106 public:
107  UnprintableTemplateInGlobal() : value_() {}
108 private:
109  T value_;
110};
111
112// A user-defined streamable type in the global namespace.
113class StreamableInGlobal {
114 public:
115  virtual ~StreamableInGlobal() {}
116};
117
118inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
119  os << "StreamableInGlobal";
120}
121
122void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
123  os << "StreamableInGlobal*";
124}
125
126namespace foo {
127
128// A user-defined unprintable type in a user namespace.
129class UnprintableInFoo {
130 public:
131  UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
132  double z() const { return z_; }
133 private:
134  char xy_[8];
135  double z_;
136};
137
138// A user-defined printable type in a user-chosen namespace.
139struct PrintableViaPrintTo {
140  PrintableViaPrintTo() : value() {}
141  int value;
142};
143
144void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
145  *os << "PrintableViaPrintTo: " << x.value;
146}
147
148// A type with a user-defined << for printing its pointer.
149struct PointerPrintable {
150};
151
152::std::ostream& operator<<(::std::ostream& os,
153                           const PointerPrintable* /* x */) {
154  return os << "PointerPrintable*";
155}
156
157// A user-defined printable class template in a user-chosen namespace.
158template <typename T>
159class PrintableViaPrintToTemplate {
160 public:
161  explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
162
163  const T& value() const { return value_; }
164 private:
165  T value_;
166};
167
168template <typename T>
169void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
170  *os << "PrintableViaPrintToTemplate: " << x.value();
171}
172
173// A user-defined streamable class template in a user namespace.
174template <typename T>
175class StreamableTemplateInFoo {
176 public:
177  StreamableTemplateInFoo() : value_() {}
178
179  const T& value() const { return value_; }
180 private:
181  T value_;
182};
183
184template <typename T>
185inline ::std::ostream& operator<<(::std::ostream& os,
186                                  const StreamableTemplateInFoo<T>& x) {
187  return os << "StreamableTemplateInFoo: " << x.value();
188}
189
190}  // namespace foo
191
192namespace testing {
193namespace gtest_printers_test {
194
195using ::std::deque;
196using ::std::list;
197using ::std::make_pair;
198using ::std::map;
199using ::std::multimap;
200using ::std::multiset;
201using ::std::pair;
202using ::std::set;
203using ::std::vector;
204using ::testing::PrintToString;
205using ::testing::internal::FormatForComparisonFailureMessage;
206using ::testing::internal::ImplicitCast_;
207using ::testing::internal::NativeArray;
208using ::testing::internal::RE;
209using ::testing::internal::RelationToSourceReference;
210using ::testing::internal::Strings;
211using ::testing::internal::UniversalPrint;
212using ::testing::internal::UniversalPrinter;
213using ::testing::internal::UniversalTersePrint;
214using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
215using ::testing::internal::string;
216
217// The hash_* classes are not part of the C++ standard.  STLport
218// defines them in namespace std.  MSVC defines them in ::stdext.  GCC
219// defines them in ::.
220#ifdef _STLP_HASH_MAP  // We got <hash_map> from STLport.
221using ::std::hash_map;
222using ::std::hash_set;
223using ::std::hash_multimap;
224using ::std::hash_multiset;
225#elif _MSC_VER
226using ::stdext::hash_map;
227using ::stdext::hash_set;
228using ::stdext::hash_multimap;
229using ::stdext::hash_multiset;
230#endif
231
232// Prints a value to a string using the universal value printer.  This
233// is a helper for testing UniversalPrinter<T>::Print() for various types.
234template <typename T>
235string Print(const T& value) {
236  ::std::stringstream ss;
237  UniversalPrinter<T>::Print(value, &ss);
238  return ss.str();
239}
240
241// Prints a value passed by reference to a string, using the universal
242// value printer.  This is a helper for testing
243// UniversalPrinter<T&>::Print() for various types.
244template <typename T>
245string PrintByRef(const T& value) {
246  ::std::stringstream ss;
247  UniversalPrinter<T&>::Print(value, &ss);
248  return ss.str();
249}
250
251// Tests printing various enum types.
252
253TEST(PrintEnumTest, AnonymousEnum) {
254  EXPECT_EQ("-1", Print(kAE1));
255  EXPECT_EQ("1", Print(kAE2));
256}
257
258TEST(PrintEnumTest, EnumWithoutPrinter) {
259  EXPECT_EQ("-2", Print(kEWP1));
260  EXPECT_EQ("42", Print(kEWP2));
261}
262
263TEST(PrintEnumTest, EnumWithStreaming) {
264  EXPECT_EQ("kEWS1", Print(kEWS1));
265  EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
266}
267
268TEST(PrintEnumTest, EnumWithPrintTo) {
269  EXPECT_EQ("kEWPT1", Print(kEWPT1));
270  EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
271}
272
273// Tests printing a class implicitly convertible to BiggestInt.
274
275TEST(PrintClassTest, BiggestIntConvertible) {
276  EXPECT_EQ("42", Print(BiggestIntConvertible()));
277}
278
279// Tests printing various char types.
280
281// char.
282TEST(PrintCharTest, PlainChar) {
283  EXPECT_EQ("'\\0'", Print('\0'));
284  EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
285  EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
286  EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
287  EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
288  EXPECT_EQ("'\\a' (7)", Print('\a'));
289  EXPECT_EQ("'\\b' (8)", Print('\b'));
290  EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
291  EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
292  EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
293  EXPECT_EQ("'\\t' (9)", Print('\t'));
294  EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
295  EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
296  EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
297  EXPECT_EQ("' ' (32, 0x20)", Print(' '));
298  EXPECT_EQ("'a' (97, 0x61)", Print('a'));
299}
300
301// signed char.
302TEST(PrintCharTest, SignedChar) {
303  EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
304  EXPECT_EQ("'\\xCE' (-50)",
305            Print(static_cast<signed char>(-50)));
306}
307
308// unsigned char.
309TEST(PrintCharTest, UnsignedChar) {
310  EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
311  EXPECT_EQ("'b' (98, 0x62)",
312            Print(static_cast<unsigned char>('b')));
313}
314
315// Tests printing other simple, built-in types.
316
317// bool.
318TEST(PrintBuiltInTypeTest, Bool) {
319  EXPECT_EQ("false", Print(false));
320  EXPECT_EQ("true", Print(true));
321}
322
323// wchar_t.
324TEST(PrintBuiltInTypeTest, Wchar_t) {
325  EXPECT_EQ("L'\\0'", Print(L'\0'));
326  EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
327  EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
328  EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
329  EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
330  EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
331  EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
332  EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
333  EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
334  EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
335  EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
336  EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
337  EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
338  EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
339  EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
340  EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
341  EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
342  EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
343}
344
345// Test that Int64 provides more storage than wchar_t.
346TEST(PrintTypeSizeTest, Wchar_t) {
347  EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64));
348}
349
350// Various integer types.
351TEST(PrintBuiltInTypeTest, Integer) {
352  EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255)));  // uint8
353  EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128)));  // int8
354  EXPECT_EQ("65535", Print(USHRT_MAX));  // uint16
355  EXPECT_EQ("-32768", Print(SHRT_MIN));  // int16
356  EXPECT_EQ("4294967295", Print(UINT_MAX));  // uint32
357  EXPECT_EQ("-2147483648", Print(INT_MIN));  // int32
358  EXPECT_EQ("18446744073709551615",
359            Print(static_cast<testing::internal::UInt64>(-1)));  // uint64
360  EXPECT_EQ("-9223372036854775808",
361            Print(static_cast<testing::internal::Int64>(1) << 63));  // int64
362}
363
364// Size types.
365TEST(PrintBuiltInTypeTest, Size_t) {
366  EXPECT_EQ("1", Print(sizeof('a')));  // size_t.
367#if !GTEST_OS_WINDOWS
368  // Windows has no ssize_t type.
369  EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2)));  // ssize_t.
370#endif  // !GTEST_OS_WINDOWS
371}
372
373// Floating-points.
374TEST(PrintBuiltInTypeTest, FloatingPoints) {
375  EXPECT_EQ("1.5", Print(1.5f));   // float
376  EXPECT_EQ("-2.5", Print(-2.5));  // double
377}
378
379// Since ::std::stringstream::operator<<(const void *) formats the pointer
380// output differently with different compilers, we have to create the expected
381// output first and use it as our expectation.
382static string PrintPointer(const void *p) {
383  ::std::stringstream expected_result_stream;
384  expected_result_stream << p;
385  return expected_result_stream.str();
386}
387
388// Tests printing C strings.
389
390// const char*.
391TEST(PrintCStringTest, Const) {
392  const char* p = "World";
393  EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
394}
395
396// char*.
397TEST(PrintCStringTest, NonConst) {
398  char p[] = "Hi";
399  EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
400            Print(static_cast<char*>(p)));
401}
402
403// NULL C string.
404TEST(PrintCStringTest, Null) {
405  const char* p = NULL;
406  EXPECT_EQ("NULL", Print(p));
407}
408
409// Tests that C strings are escaped properly.
410TEST(PrintCStringTest, EscapesProperly) {
411  const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
412  EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
413            "\\n\\r\\t\\v\\x7F\\xFF a\"",
414            Print(p));
415}
416
417// MSVC compiler can be configured to define whar_t as a typedef
418// of unsigned short. Defining an overload for const wchar_t* in that case
419// would cause pointers to unsigned shorts be printed as wide strings,
420// possibly accessing more memory than intended and causing invalid
421// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
422// wchar_t is implemented as a native type.
423#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
424
425// const wchar_t*.
426TEST(PrintWideCStringTest, Const) {
427  const wchar_t* p = L"World";
428  EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
429}
430
431// wchar_t*.
432TEST(PrintWideCStringTest, NonConst) {
433  wchar_t p[] = L"Hi";
434  EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
435            Print(static_cast<wchar_t*>(p)));
436}
437
438// NULL wide C string.
439TEST(PrintWideCStringTest, Null) {
440  const wchar_t* p = NULL;
441  EXPECT_EQ("NULL", Print(p));
442}
443
444// Tests that wide C strings are escaped properly.
445TEST(PrintWideCStringTest, EscapesProperly) {
446  const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
447                       '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
448  EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
449            "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
450            Print(static_cast<const wchar_t*>(s)));
451}
452#endif  // native wchar_t
453
454// Tests printing pointers to other char types.
455
456// signed char*.
457TEST(PrintCharPointerTest, SignedChar) {
458  signed char* p = reinterpret_cast<signed char*>(0x1234);
459  EXPECT_EQ(PrintPointer(p), Print(p));
460  p = NULL;
461  EXPECT_EQ("NULL", Print(p));
462}
463
464// const signed char*.
465TEST(PrintCharPointerTest, ConstSignedChar) {
466  signed char* p = reinterpret_cast<signed char*>(0x1234);
467  EXPECT_EQ(PrintPointer(p), Print(p));
468  p = NULL;
469  EXPECT_EQ("NULL", Print(p));
470}
471
472// unsigned char*.
473TEST(PrintCharPointerTest, UnsignedChar) {
474  unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
475  EXPECT_EQ(PrintPointer(p), Print(p));
476  p = NULL;
477  EXPECT_EQ("NULL", Print(p));
478}
479
480// const unsigned char*.
481TEST(PrintCharPointerTest, ConstUnsignedChar) {
482  const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
483  EXPECT_EQ(PrintPointer(p), Print(p));
484  p = NULL;
485  EXPECT_EQ("NULL", Print(p));
486}
487
488// Tests printing pointers to simple, built-in types.
489
490// bool*.
491TEST(PrintPointerToBuiltInTypeTest, Bool) {
492  bool* p = reinterpret_cast<bool*>(0xABCD);
493  EXPECT_EQ(PrintPointer(p), Print(p));
494  p = NULL;
495  EXPECT_EQ("NULL", Print(p));
496}
497
498// void*.
499TEST(PrintPointerToBuiltInTypeTest, Void) {
500  void* p = reinterpret_cast<void*>(0xABCD);
501  EXPECT_EQ(PrintPointer(p), Print(p));
502  p = NULL;
503  EXPECT_EQ("NULL", Print(p));
504}
505
506// const void*.
507TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
508  const void* p = reinterpret_cast<const void*>(0xABCD);
509  EXPECT_EQ(PrintPointer(p), Print(p));
510  p = NULL;
511  EXPECT_EQ("NULL", Print(p));
512}
513
514// Tests printing pointers to pointers.
515TEST(PrintPointerToPointerTest, IntPointerPointer) {
516  int** p = reinterpret_cast<int**>(0xABCD);
517  EXPECT_EQ(PrintPointer(p), Print(p));
518  p = NULL;
519  EXPECT_EQ("NULL", Print(p));
520}
521
522// Tests printing (non-member) function pointers.
523
524void MyFunction(int /* n */) {}
525
526TEST(PrintPointerTest, NonMemberFunctionPointer) {
527  // We cannot directly cast &MyFunction to const void* because the
528  // standard disallows casting between pointers to functions and
529  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
530  // this limitation.
531  EXPECT_EQ(
532      PrintPointer(reinterpret_cast<const void*>(
533          reinterpret_cast<internal::BiggestInt>(&MyFunction))),
534      Print(&MyFunction));
535  int (*p)(bool) = NULL;  // NOLINT
536  EXPECT_EQ("NULL", Print(p));
537}
538
539// An assertion predicate determining whether a one string is a prefix for
540// another.
541template <typename StringType>
542AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
543  if (str.find(prefix, 0) == 0)
544    return AssertionSuccess();
545
546  const bool is_wide_string = sizeof(prefix[0]) > 1;
547  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
548  return AssertionFailure()
549      << begin_string_quote << prefix << "\" is not a prefix of "
550      << begin_string_quote << str << "\"\n";
551}
552
553// Tests printing member variable pointers.  Although they are called
554// pointers, they don't point to a location in the address space.
555// Their representation is implementation-defined.  Thus they will be
556// printed as raw bytes.
557
558struct Foo {
559 public:
560  virtual ~Foo() {}
561  int MyMethod(char x) { return x + 1; }
562  virtual char MyVirtualMethod(int /* n */) { return 'a'; }
563
564  int value;
565};
566
567TEST(PrintPointerTest, MemberVariablePointer) {
568  EXPECT_TRUE(HasPrefix(Print(&Foo::value),
569                        Print(sizeof(&Foo::value)) + "-byte object "));
570  int (Foo::*p) = NULL;  // NOLINT
571  EXPECT_TRUE(HasPrefix(Print(p),
572                        Print(sizeof(p)) + "-byte object "));
573}
574
575// Tests printing member function pointers.  Although they are called
576// pointers, they don't point to a location in the address space.
577// Their representation is implementation-defined.  Thus they will be
578// printed as raw bytes.
579TEST(PrintPointerTest, MemberFunctionPointer) {
580  EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
581                        Print(sizeof(&Foo::MyMethod)) + "-byte object "));
582  EXPECT_TRUE(
583      HasPrefix(Print(&Foo::MyVirtualMethod),
584                Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
585  int (Foo::*p)(char) = NULL;  // NOLINT
586  EXPECT_TRUE(HasPrefix(Print(p),
587                        Print(sizeof(p)) + "-byte object "));
588}
589
590// Tests printing C arrays.
591
592// The difference between this and Print() is that it ensures that the
593// argument is a reference to an array.
594template <typename T, size_t N>
595string PrintArrayHelper(T (&a)[N]) {
596  return Print(a);
597}
598
599// One-dimensional array.
600TEST(PrintArrayTest, OneDimensionalArray) {
601  int a[5] = { 1, 2, 3, 4, 5 };
602  EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
603}
604
605// Two-dimensional array.
606TEST(PrintArrayTest, TwoDimensionalArray) {
607  int a[2][5] = {
608    { 1, 2, 3, 4, 5 },
609    { 6, 7, 8, 9, 0 }
610  };
611  EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
612}
613
614// Array of const elements.
615TEST(PrintArrayTest, ConstArray) {
616  const bool a[1] = { false };
617  EXPECT_EQ("{ false }", PrintArrayHelper(a));
618}
619
620// char array without terminating NUL.
621TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
622  // Array a contains '\0' in the middle and doesn't end with '\0'.
623  char a[] = { 'H', '\0', 'i' };
624  EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
625}
626
627// const char array with terminating NUL.
628TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) {
629  const char a[] = "\0Hi";
630  EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
631}
632
633// const wchar_t array without terminating NUL.
634TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
635  // Array a contains '\0' in the middle and doesn't end with '\0'.
636  const wchar_t a[] = { L'H', L'\0', L'i' };
637  EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
638}
639
640// wchar_t array with terminating NUL.
641TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
642  const wchar_t a[] = L"\0Hi";
643  EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
644}
645
646// Array of objects.
647TEST(PrintArrayTest, ObjectArray) {
648  string a[3] = { "Hi", "Hello", "Ni hao" };
649  EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
650}
651
652// Array with many elements.
653TEST(PrintArrayTest, BigArray) {
654  int a[100] = { 1, 2, 3 };
655  EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
656            PrintArrayHelper(a));
657}
658
659// Tests printing ::string and ::std::string.
660
661#if GTEST_HAS_GLOBAL_STRING
662// ::string.
663TEST(PrintStringTest, StringInGlobalNamespace) {
664  const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
665  const ::string str(s, sizeof(s));
666  EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
667            Print(str));
668}
669#endif  // GTEST_HAS_GLOBAL_STRING
670
671// ::std::string.
672TEST(PrintStringTest, StringInStdNamespace) {
673  const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
674  const ::std::string str(s, sizeof(s));
675  EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
676            Print(str));
677}
678
679TEST(PrintStringTest, StringAmbiguousHex) {
680  // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
681  // '\x6', '\x6B', or '\x6BA'.
682
683  // a hex escaping sequence following by a decimal digit
684  EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
685  // a hex escaping sequence following by a hex digit (lower-case)
686  EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
687  // a hex escaping sequence following by a hex digit (upper-case)
688  EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
689  // a hex escaping sequence following by a non-xdigit
690  EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
691}
692
693// Tests printing ::wstring and ::std::wstring.
694
695#if GTEST_HAS_GLOBAL_WSTRING
696// ::wstring.
697TEST(PrintWideStringTest, StringInGlobalNamespace) {
698  const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
699  const ::wstring str(s, sizeof(s)/sizeof(wchar_t));
700  EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
701            "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
702            Print(str));
703}
704#endif  // GTEST_HAS_GLOBAL_WSTRING
705
706#if GTEST_HAS_STD_WSTRING
707// ::std::wstring.
708TEST(PrintWideStringTest, StringInStdNamespace) {
709  const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
710  const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
711  EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
712            "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
713            Print(str));
714}
715
716TEST(PrintWideStringTest, StringAmbiguousHex) {
717  // same for wide strings.
718  EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
719  EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
720            Print(::std::wstring(L"mm\x6" L"bananas")));
721  EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
722            Print(::std::wstring(L"NOM\x6" L"BANANA")));
723  EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
724}
725#endif  // GTEST_HAS_STD_WSTRING
726
727// Tests printing types that support generic streaming (i.e. streaming
728// to std::basic_ostream<Char, CharTraits> for any valid Char and
729// CharTraits types).
730
731// Tests printing a non-template type that supports generic streaming.
732
733class AllowsGenericStreaming {};
734
735template <typename Char, typename CharTraits>
736std::basic_ostream<Char, CharTraits>& operator<<(
737    std::basic_ostream<Char, CharTraits>& os,
738    const AllowsGenericStreaming& /* a */) {
739  return os << "AllowsGenericStreaming";
740}
741
742TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
743  AllowsGenericStreaming a;
744  EXPECT_EQ("AllowsGenericStreaming", Print(a));
745}
746
747// Tests printing a template type that supports generic streaming.
748
749template <typename T>
750class AllowsGenericStreamingTemplate {};
751
752template <typename Char, typename CharTraits, typename T>
753std::basic_ostream<Char, CharTraits>& operator<<(
754    std::basic_ostream<Char, CharTraits>& os,
755    const AllowsGenericStreamingTemplate<T>& /* a */) {
756  return os << "AllowsGenericStreamingTemplate";
757}
758
759TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
760  AllowsGenericStreamingTemplate<int> a;
761  EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
762}
763
764// Tests printing a type that supports generic streaming and can be
765// implicitly converted to another printable type.
766
767template <typename T>
768class AllowsGenericStreamingAndImplicitConversionTemplate {
769 public:
770  operator bool() const { return false; }
771};
772
773template <typename Char, typename CharTraits, typename T>
774std::basic_ostream<Char, CharTraits>& operator<<(
775    std::basic_ostream<Char, CharTraits>& os,
776    const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
777  return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
778}
779
780TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
781  AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
782  EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
783}
784
785#if GTEST_HAS_STRING_PIECE_
786
787// Tests printing StringPiece.
788
789TEST(PrintStringPieceTest, SimpleStringPiece) {
790  const StringPiece sp = "Hello";
791  EXPECT_EQ("\"Hello\"", Print(sp));
792}
793
794TEST(PrintStringPieceTest, UnprintableCharacters) {
795  const char str[] = "NUL (\0) and \r\t";
796  const StringPiece sp(str, sizeof(str) - 1);
797  EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
798}
799
800#endif  // GTEST_HAS_STRING_PIECE_
801
802// Tests printing STL containers.
803
804TEST(PrintStlContainerTest, EmptyDeque) {
805  deque<char> empty;
806  EXPECT_EQ("{}", Print(empty));
807}
808
809TEST(PrintStlContainerTest, NonEmptyDeque) {
810  deque<int> non_empty;
811  non_empty.push_back(1);
812  non_empty.push_back(3);
813  EXPECT_EQ("{ 1, 3 }", Print(non_empty));
814}
815
816#if GTEST_HAS_HASH_MAP_
817
818TEST(PrintStlContainerTest, OneElementHashMap) {
819  hash_map<int, char> map1;
820  map1[1] = 'a';
821  EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
822}
823
824TEST(PrintStlContainerTest, HashMultiMap) {
825  hash_multimap<int, bool> map1;
826  map1.insert(make_pair(5, true));
827  map1.insert(make_pair(5, false));
828
829  // Elements of hash_multimap can be printed in any order.
830  const string result = Print(map1);
831  EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
832              result == "{ (5, false), (5, true) }")
833                  << " where Print(map1) returns \"" << result << "\".";
834}
835
836#endif  // GTEST_HAS_HASH_MAP_
837
838#if GTEST_HAS_HASH_SET_
839
840TEST(PrintStlContainerTest, HashSet) {
841  hash_set<string> set1;
842  set1.insert("hello");
843  EXPECT_EQ("{ \"hello\" }", Print(set1));
844}
845
846TEST(PrintStlContainerTest, HashMultiSet) {
847  const int kSize = 5;
848  int a[kSize] = { 1, 1, 2, 5, 1 };
849  hash_multiset<int> set1(a, a + kSize);
850
851  // Elements of hash_multiset can be printed in any order.
852  const string result = Print(set1);
853  const string expected_pattern = "{ d, d, d, d, d }";  // d means a digit.
854
855  // Verifies the result matches the expected pattern; also extracts
856  // the numbers in the result.
857  ASSERT_EQ(expected_pattern.length(), result.length());
858  std::vector<int> numbers;
859  for (size_t i = 0; i != result.length(); i++) {
860    if (expected_pattern[i] == 'd') {
861      ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
862      numbers.push_back(result[i] - '0');
863    } else {
864      EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
865                                                << result;
866    }
867  }
868
869  // Makes sure the result contains the right numbers.
870  std::sort(numbers.begin(), numbers.end());
871  std::sort(a, a + kSize);
872  EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
873}
874
875#endif  // GTEST_HAS_HASH_SET_
876
877TEST(PrintStlContainerTest, List) {
878  const string a[] = {
879    "hello",
880    "world"
881  };
882  const list<string> strings(a, a + 2);
883  EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
884}
885
886TEST(PrintStlContainerTest, Map) {
887  map<int, bool> map1;
888  map1[1] = true;
889  map1[5] = false;
890  map1[3] = true;
891  EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
892}
893
894TEST(PrintStlContainerTest, MultiMap) {
895  multimap<bool, int> map1;
896  // The make_pair template function would deduce the type as
897  // pair<bool, int> here, and since the key part in a multimap has to
898  // be constant, without a templated ctor in the pair class (as in
899  // libCstd on Solaris), make_pair call would fail to compile as no
900  // implicit conversion is found.  Thus explicit typename is used
901  // here instead.
902  map1.insert(pair<const bool, int>(true, 0));
903  map1.insert(pair<const bool, int>(true, 1));
904  map1.insert(pair<const bool, int>(false, 2));
905  EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
906}
907
908TEST(PrintStlContainerTest, Set) {
909  const unsigned int a[] = { 3, 0, 5 };
910  set<unsigned int> set1(a, a + 3);
911  EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
912}
913
914TEST(PrintStlContainerTest, MultiSet) {
915  const int a[] = { 1, 1, 2, 5, 1 };
916  multiset<int> set1(a, a + 5);
917  EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
918}
919
920#if GTEST_HAS_STD_FORWARD_LIST_
921// <slist> is available on Linux in the google3 mode, but not on
922// Windows or Mac OS X.
923
924TEST(PrintStlContainerTest, SinglyLinkedList) {
925  int a[] = { 9, 2, 8 };
926  const std::forward_list<int> ints(a, a + 3);
927  EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
928}
929#endif  // GTEST_HAS_STD_FORWARD_LIST_
930
931TEST(PrintStlContainerTest, Pair) {
932  pair<const bool, int> p(true, 5);
933  EXPECT_EQ("(true, 5)", Print(p));
934}
935
936TEST(PrintStlContainerTest, Vector) {
937  vector<int> v;
938  v.push_back(1);
939  v.push_back(2);
940  EXPECT_EQ("{ 1, 2 }", Print(v));
941}
942
943TEST(PrintStlContainerTest, LongSequence) {
944  const int a[100] = { 1, 2, 3 };
945  const vector<int> v(a, a + 100);
946  EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
947            "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
948}
949
950TEST(PrintStlContainerTest, NestedContainer) {
951  const int a1[] = { 1, 2 };
952  const int a2[] = { 3, 4, 5 };
953  const list<int> l1(a1, a1 + 2);
954  const list<int> l2(a2, a2 + 3);
955
956  vector<list<int> > v;
957  v.push_back(l1);
958  v.push_back(l2);
959  EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
960}
961
962TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
963  const int a[3] = { 1, 2, 3 };
964  NativeArray<int> b(a, 3, RelationToSourceReference());
965  EXPECT_EQ("{ 1, 2, 3 }", Print(b));
966}
967
968TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
969  const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
970  NativeArray<int[3]> b(a, 2, RelationToSourceReference());
971  EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
972}
973
974// Tests that a class named iterator isn't treated as a container.
975
976struct iterator {
977  char x;
978};
979
980TEST(PrintStlContainerTest, Iterator) {
981  iterator it = {};
982  EXPECT_EQ("1-byte object <00>", Print(it));
983}
984
985// Tests that a class named const_iterator isn't treated as a container.
986
987struct const_iterator {
988  char x;
989};
990
991TEST(PrintStlContainerTest, ConstIterator) {
992  const_iterator it = {};
993  EXPECT_EQ("1-byte object <00>", Print(it));
994}
995
996#if GTEST_HAS_TR1_TUPLE
997// Tests printing ::std::tr1::tuples.
998
999// Tuples of various arities.
1000TEST(PrintTr1TupleTest, VariousSizes) {
1001  ::std::tr1::tuple<> t0;
1002  EXPECT_EQ("()", Print(t0));
1003
1004  ::std::tr1::tuple<int> t1(5);
1005  EXPECT_EQ("(5)", Print(t1));
1006
1007  ::std::tr1::tuple<char, bool> t2('a', true);
1008  EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1009
1010  ::std::tr1::tuple<bool, int, int> t3(false, 2, 3);
1011  EXPECT_EQ("(false, 2, 3)", Print(t3));
1012
1013  ::std::tr1::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1014  EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1015
1016  ::std::tr1::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
1017  EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
1018
1019  ::std::tr1::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
1020  EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
1021
1022  ::std::tr1::tuple<bool, int, int, int, bool, int, int> t7(
1023      false, 2, 3, 4, true, 6, 7);
1024  EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
1025
1026  ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool> t8(
1027      false, 2, 3, 4, true, 6, 7, true);
1028  EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
1029
1030  ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
1031      false, 2, 3, 4, true, 6, 7, true, 9);
1032  EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
1033
1034  const char* const str = "8";
1035  // VC++ 2010's implementation of tuple of C++0x is deficient, requiring
1036  // an explicit type cast of NULL to be used.
1037  ::std::tr1::tuple<bool, char, short, testing::internal::Int32,  // NOLINT
1038      testing::internal::Int64, float, double, const char*, void*, string>
1039      t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str,
1040          ImplicitCast_<void*>(NULL), "10");
1041  EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1042            " pointing to \"8\", NULL, \"10\")",
1043            Print(t10));
1044}
1045
1046// Nested tuples.
1047TEST(PrintTr1TupleTest, NestedTuple) {
1048  ::std::tr1::tuple< ::std::tr1::tuple<int, bool>, char> nested(
1049      ::std::tr1::make_tuple(5, true), 'a');
1050  EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1051}
1052
1053#endif  // GTEST_HAS_TR1_TUPLE
1054
1055#if GTEST_HAS_STD_TUPLE_
1056// Tests printing ::std::tuples.
1057
1058// Tuples of various arities.
1059TEST(PrintStdTupleTest, VariousSizes) {
1060  ::std::tuple<> t0;
1061  EXPECT_EQ("()", Print(t0));
1062
1063  ::std::tuple<int> t1(5);
1064  EXPECT_EQ("(5)", Print(t1));
1065
1066  ::std::tuple<char, bool> t2('a', true);
1067  EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1068
1069  ::std::tuple<bool, int, int> t3(false, 2, 3);
1070  EXPECT_EQ("(false, 2, 3)", Print(t3));
1071
1072  ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1073  EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1074
1075  ::std::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
1076  EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
1077
1078  ::std::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
1079  EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
1080
1081  ::std::tuple<bool, int, int, int, bool, int, int> t7(
1082      false, 2, 3, 4, true, 6, 7);
1083  EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
1084
1085  ::std::tuple<bool, int, int, int, bool, int, int, bool> t8(
1086      false, 2, 3, 4, true, 6, 7, true);
1087  EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
1088
1089  ::std::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
1090      false, 2, 3, 4, true, 6, 7, true, 9);
1091  EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
1092
1093  const char* const str = "8";
1094  // VC++ 2010's implementation of tuple of C++0x is deficient, requiring
1095  // an explicit type cast of NULL to be used.
1096  ::std::tuple<bool, char, short, testing::internal::Int32,  // NOLINT
1097      testing::internal::Int64, float, double, const char*, void*, string>
1098      t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str,
1099          ImplicitCast_<void*>(NULL), "10");
1100  EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1101            " pointing to \"8\", NULL, \"10\")",
1102            Print(t10));
1103}
1104
1105// Nested tuples.
1106TEST(PrintStdTupleTest, NestedTuple) {
1107  ::std::tuple< ::std::tuple<int, bool>, char> nested(
1108      ::std::make_tuple(5, true), 'a');
1109  EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1110}
1111
1112#endif  // GTEST_LANG_CXX11
1113
1114// Tests printing user-defined unprintable types.
1115
1116// Unprintable types in the global namespace.
1117TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1118  EXPECT_EQ("1-byte object <00>",
1119            Print(UnprintableTemplateInGlobal<char>()));
1120}
1121
1122// Unprintable types in a user namespace.
1123TEST(PrintUnprintableTypeTest, InUserNamespace) {
1124  EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1125            Print(::foo::UnprintableInFoo()));
1126}
1127
1128// Unprintable types are that too big to be printed completely.
1129
1130struct Big {
1131  Big() { memset(array, 0, sizeof(array)); }
1132  char array[257];
1133};
1134
1135TEST(PrintUnpritableTypeTest, BigObject) {
1136  EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1137            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1138            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1139            "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1140            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1141            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1142            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1143            Print(Big()));
1144}
1145
1146// Tests printing user-defined streamable types.
1147
1148// Streamable types in the global namespace.
1149TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1150  StreamableInGlobal x;
1151  EXPECT_EQ("StreamableInGlobal", Print(x));
1152  EXPECT_EQ("StreamableInGlobal*", Print(&x));
1153}
1154
1155// Printable template types in a user namespace.
1156TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1157  EXPECT_EQ("StreamableTemplateInFoo: 0",
1158            Print(::foo::StreamableTemplateInFoo<int>()));
1159}
1160
1161// Tests printing user-defined types that have a PrintTo() function.
1162TEST(PrintPrintableTypeTest, InUserNamespace) {
1163  EXPECT_EQ("PrintableViaPrintTo: 0",
1164            Print(::foo::PrintableViaPrintTo()));
1165}
1166
1167// Tests printing a pointer to a user-defined type that has a <<
1168// operator for its pointer.
1169TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1170  ::foo::PointerPrintable x;
1171  EXPECT_EQ("PointerPrintable*", Print(&x));
1172}
1173
1174// Tests printing user-defined class template that have a PrintTo() function.
1175TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1176  EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1177            Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1178}
1179
1180// Tests that the universal printer prints both the address and the
1181// value of a reference.
1182TEST(PrintReferenceTest, PrintsAddressAndValue) {
1183  int n = 5;
1184  EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1185
1186  int a[2][3] = {
1187    { 0, 1, 2 },
1188    { 3, 4, 5 }
1189  };
1190  EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1191            PrintByRef(a));
1192
1193  const ::foo::UnprintableInFoo x;
1194  EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
1195            "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1196            PrintByRef(x));
1197}
1198
1199// Tests that the universal printer prints a function pointer passed by
1200// reference.
1201TEST(PrintReferenceTest, HandlesFunctionPointer) {
1202  void (*fp)(int n) = &MyFunction;
1203  const string fp_pointer_string =
1204      PrintPointer(reinterpret_cast<const void*>(&fp));
1205  // We cannot directly cast &MyFunction to const void* because the
1206  // standard disallows casting between pointers to functions and
1207  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1208  // this limitation.
1209  const string fp_string = PrintPointer(reinterpret_cast<const void*>(
1210      reinterpret_cast<internal::BiggestInt>(fp)));
1211  EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
1212            PrintByRef(fp));
1213}
1214
1215// Tests that the universal printer prints a member function pointer
1216// passed by reference.
1217TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1218  int (Foo::*p)(char ch) = &Foo::MyMethod;
1219  EXPECT_TRUE(HasPrefix(
1220      PrintByRef(p),
1221      "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
1222          Print(sizeof(p)) + "-byte object "));
1223
1224  char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1225  EXPECT_TRUE(HasPrefix(
1226      PrintByRef(p2),
1227      "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
1228          Print(sizeof(p2)) + "-byte object "));
1229}
1230
1231// Tests that the universal printer prints a member variable pointer
1232// passed by reference.
1233TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1234  int (Foo::*p) = &Foo::value;  // NOLINT
1235  EXPECT_TRUE(HasPrefix(
1236      PrintByRef(p),
1237      "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
1238}
1239
1240// Tests that FormatForComparisonFailureMessage(), which is used to print
1241// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1242// fails, formats the operand in the desired way.
1243
1244// scalar
1245TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1246  EXPECT_STREQ("123",
1247               FormatForComparisonFailureMessage(123, 124).c_str());
1248}
1249
1250// non-char pointer
1251TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1252  int n = 0;
1253  EXPECT_EQ(PrintPointer(&n),
1254            FormatForComparisonFailureMessage(&n, &n).c_str());
1255}
1256
1257// non-char array
1258TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1259  // In expression 'array == x', 'array' is compared by pointer.
1260  // Therefore we want to print an array operand as a pointer.
1261  int n[] = { 1, 2, 3 };
1262  EXPECT_EQ(PrintPointer(n),
1263            FormatForComparisonFailureMessage(n, n).c_str());
1264}
1265
1266// Tests formatting a char pointer when it's compared with another pointer.
1267// In this case we want to print it as a raw pointer, as the comparision is by
1268// pointer.
1269
1270// char pointer vs pointer
1271TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1272  // In expression 'p == x', where 'p' and 'x' are (const or not) char
1273  // pointers, the operands are compared by pointer.  Therefore we
1274  // want to print 'p' as a pointer instead of a C string (we don't
1275  // even know if it's supposed to point to a valid C string).
1276
1277  // const char*
1278  const char* s = "hello";
1279  EXPECT_EQ(PrintPointer(s),
1280            FormatForComparisonFailureMessage(s, s).c_str());
1281
1282  // char*
1283  char ch = 'a';
1284  EXPECT_EQ(PrintPointer(&ch),
1285            FormatForComparisonFailureMessage(&ch, &ch).c_str());
1286}
1287
1288// wchar_t pointer vs pointer
1289TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1290  // In expression 'p == x', where 'p' and 'x' are (const or not) char
1291  // pointers, the operands are compared by pointer.  Therefore we
1292  // want to print 'p' as a pointer instead of a wide C string (we don't
1293  // even know if it's supposed to point to a valid wide C string).
1294
1295  // const wchar_t*
1296  const wchar_t* s = L"hello";
1297  EXPECT_EQ(PrintPointer(s),
1298            FormatForComparisonFailureMessage(s, s).c_str());
1299
1300  // wchar_t*
1301  wchar_t ch = L'a';
1302  EXPECT_EQ(PrintPointer(&ch),
1303            FormatForComparisonFailureMessage(&ch, &ch).c_str());
1304}
1305
1306// Tests formatting a char pointer when it's compared to a string object.
1307// In this case we want to print the char pointer as a C string.
1308
1309#if GTEST_HAS_GLOBAL_STRING
1310// char pointer vs ::string
1311TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) {
1312  const char* s = "hello \"world";
1313  EXPECT_STREQ("\"hello \\\"world\"",  // The string content should be escaped.
1314               FormatForComparisonFailureMessage(s, ::string()).c_str());
1315
1316  // char*
1317  char str[] = "hi\1";
1318  char* p = str;
1319  EXPECT_STREQ("\"hi\\x1\"",  // The string content should be escaped.
1320               FormatForComparisonFailureMessage(p, ::string()).c_str());
1321}
1322#endif
1323
1324// char pointer vs std::string
1325TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1326  const char* s = "hello \"world";
1327  EXPECT_STREQ("\"hello \\\"world\"",  // The string content should be escaped.
1328               FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1329
1330  // char*
1331  char str[] = "hi\1";
1332  char* p = str;
1333  EXPECT_STREQ("\"hi\\x1\"",  // The string content should be escaped.
1334               FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1335}
1336
1337#if GTEST_HAS_GLOBAL_WSTRING
1338// wchar_t pointer vs ::wstring
1339TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) {
1340  const wchar_t* s = L"hi \"world";
1341  EXPECT_STREQ("L\"hi \\\"world\"",  // The string content should be escaped.
1342               FormatForComparisonFailureMessage(s, ::wstring()).c_str());
1343
1344  // wchar_t*
1345  wchar_t str[] = L"hi\1";
1346  wchar_t* p = str;
1347  EXPECT_STREQ("L\"hi\\x1\"",  // The string content should be escaped.
1348               FormatForComparisonFailureMessage(p, ::wstring()).c_str());
1349}
1350#endif
1351
1352#if GTEST_HAS_STD_WSTRING
1353// wchar_t pointer vs std::wstring
1354TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1355  const wchar_t* s = L"hi \"world";
1356  EXPECT_STREQ("L\"hi \\\"world\"",  // The string content should be escaped.
1357               FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1358
1359  // wchar_t*
1360  wchar_t str[] = L"hi\1";
1361  wchar_t* p = str;
1362  EXPECT_STREQ("L\"hi\\x1\"",  // The string content should be escaped.
1363               FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1364}
1365#endif
1366
1367// Tests formatting a char array when it's compared with a pointer or array.
1368// In this case we want to print the array as a row pointer, as the comparison
1369// is by pointer.
1370
1371// char array vs pointer
1372TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1373  char str[] = "hi \"world\"";
1374  char* p = NULL;
1375  EXPECT_EQ(PrintPointer(str),
1376            FormatForComparisonFailureMessage(str, p).c_str());
1377}
1378
1379// char array vs char array
1380TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1381  const char str[] = "hi \"world\"";
1382  EXPECT_EQ(PrintPointer(str),
1383            FormatForComparisonFailureMessage(str, str).c_str());
1384}
1385
1386// wchar_t array vs pointer
1387TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1388  wchar_t str[] = L"hi \"world\"";
1389  wchar_t* p = NULL;
1390  EXPECT_EQ(PrintPointer(str),
1391            FormatForComparisonFailureMessage(str, p).c_str());
1392}
1393
1394// wchar_t array vs wchar_t array
1395TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1396  const wchar_t str[] = L"hi \"world\"";
1397  EXPECT_EQ(PrintPointer(str),
1398            FormatForComparisonFailureMessage(str, str).c_str());
1399}
1400
1401// Tests formatting a char array when it's compared with a string object.
1402// In this case we want to print the array as a C string.
1403
1404#if GTEST_HAS_GLOBAL_STRING
1405// char array vs string
1406TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) {
1407  const char str[] = "hi \"w\0rld\"";
1408  EXPECT_STREQ("\"hi \\\"w\"",  // The content should be escaped.
1409                                // Embedded NUL terminates the string.
1410               FormatForComparisonFailureMessage(str, ::string()).c_str());
1411}
1412#endif
1413
1414// char array vs std::string
1415TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1416  const char str[] = "hi \"world\"";
1417  EXPECT_STREQ("\"hi \\\"world\\\"\"",  // The content should be escaped.
1418               FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1419}
1420
1421#if GTEST_HAS_GLOBAL_WSTRING
1422// wchar_t array vs wstring
1423TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) {
1424  const wchar_t str[] = L"hi \"world\"";
1425  EXPECT_STREQ("L\"hi \\\"world\\\"\"",  // The content should be escaped.
1426               FormatForComparisonFailureMessage(str, ::wstring()).c_str());
1427}
1428#endif
1429
1430#if GTEST_HAS_STD_WSTRING
1431// wchar_t array vs std::wstring
1432TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1433  const wchar_t str[] = L"hi \"w\0rld\"";
1434  EXPECT_STREQ(
1435      "L\"hi \\\"w\"",  // The content should be escaped.
1436                        // Embedded NUL terminates the string.
1437      FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1438}
1439#endif
1440
1441// Useful for testing PrintToString().  We cannot use EXPECT_EQ()
1442// there as its implementation uses PrintToString().  The caller must
1443// ensure that 'value' has no side effect.
1444#define EXPECT_PRINT_TO_STRING_(value, expected_string)         \
1445  EXPECT_TRUE(PrintToString(value) == (expected_string))        \
1446      << " where " #value " prints as " << (PrintToString(value))
1447
1448TEST(PrintToStringTest, WorksForScalar) {
1449  EXPECT_PRINT_TO_STRING_(123, "123");
1450}
1451
1452TEST(PrintToStringTest, WorksForPointerToConstChar) {
1453  const char* p = "hello";
1454  EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1455}
1456
1457TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1458  char s[] = "hello";
1459  char* p = s;
1460  EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1461}
1462
1463TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1464  const char* p = "hello\n";
1465  EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1466}
1467
1468TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1469  char s[] = "hello\1";
1470  char* p = s;
1471  EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1472}
1473
1474TEST(PrintToStringTest, WorksForArray) {
1475  int n[3] = { 1, 2, 3 };
1476  EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1477}
1478
1479TEST(PrintToStringTest, WorksForCharArray) {
1480  char s[] = "hello";
1481  EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1482}
1483
1484TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1485  const char str_with_nul[] = "hello\0 world";
1486  EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1487
1488  char mutable_str_with_nul[] = "hello\0 world";
1489  EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1490}
1491
1492#undef EXPECT_PRINT_TO_STRING_
1493
1494TEST(UniversalTersePrintTest, WorksForNonReference) {
1495  ::std::stringstream ss;
1496  UniversalTersePrint(123, &ss);
1497  EXPECT_EQ("123", ss.str());
1498}
1499
1500TEST(UniversalTersePrintTest, WorksForReference) {
1501  const int& n = 123;
1502  ::std::stringstream ss;
1503  UniversalTersePrint(n, &ss);
1504  EXPECT_EQ("123", ss.str());
1505}
1506
1507TEST(UniversalTersePrintTest, WorksForCString) {
1508  const char* s1 = "abc";
1509  ::std::stringstream ss1;
1510  UniversalTersePrint(s1, &ss1);
1511  EXPECT_EQ("\"abc\"", ss1.str());
1512
1513  char* s2 = const_cast<char*>(s1);
1514  ::std::stringstream ss2;
1515  UniversalTersePrint(s2, &ss2);
1516  EXPECT_EQ("\"abc\"", ss2.str());
1517
1518  const char* s3 = NULL;
1519  ::std::stringstream ss3;
1520  UniversalTersePrint(s3, &ss3);
1521  EXPECT_EQ("NULL", ss3.str());
1522}
1523
1524TEST(UniversalPrintTest, WorksForNonReference) {
1525  ::std::stringstream ss;
1526  UniversalPrint(123, &ss);
1527  EXPECT_EQ("123", ss.str());
1528}
1529
1530TEST(UniversalPrintTest, WorksForReference) {
1531  const int& n = 123;
1532  ::std::stringstream ss;
1533  UniversalPrint(n, &ss);
1534  EXPECT_EQ("123", ss.str());
1535}
1536
1537TEST(UniversalPrintTest, WorksForCString) {
1538  const char* s1 = "abc";
1539  ::std::stringstream ss1;
1540  UniversalPrint(s1, &ss1);
1541  EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", string(ss1.str()));
1542
1543  char* s2 = const_cast<char*>(s1);
1544  ::std::stringstream ss2;
1545  UniversalPrint(s2, &ss2);
1546  EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", string(ss2.str()));
1547
1548  const char* s3 = NULL;
1549  ::std::stringstream ss3;
1550  UniversalPrint(s3, &ss3);
1551  EXPECT_EQ("NULL", ss3.str());
1552}
1553
1554TEST(UniversalPrintTest, WorksForCharArray) {
1555  const char str[] = "\"Line\0 1\"\nLine 2";
1556  ::std::stringstream ss1;
1557  UniversalPrint(str, &ss1);
1558  EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1559
1560  const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1561  ::std::stringstream ss2;
1562  UniversalPrint(mutable_str, &ss2);
1563  EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1564}
1565
1566#if GTEST_HAS_TR1_TUPLE
1567
1568TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) {
1569  Strings result = UniversalTersePrintTupleFieldsToStrings(
1570      ::std::tr1::make_tuple());
1571  EXPECT_EQ(0u, result.size());
1572}
1573
1574TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) {
1575  Strings result = UniversalTersePrintTupleFieldsToStrings(
1576      ::std::tr1::make_tuple(1));
1577  ASSERT_EQ(1u, result.size());
1578  EXPECT_EQ("1", result[0]);
1579}
1580
1581TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) {
1582  Strings result = UniversalTersePrintTupleFieldsToStrings(
1583      ::std::tr1::make_tuple(1, 'a'));
1584  ASSERT_EQ(2u, result.size());
1585  EXPECT_EQ("1", result[0]);
1586  EXPECT_EQ("'a' (97, 0x61)", result[1]);
1587}
1588
1589TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) {
1590  const int n = 1;
1591  Strings result = UniversalTersePrintTupleFieldsToStrings(
1592      ::std::tr1::tuple<const int&, const char*>(n, "a"));
1593  ASSERT_EQ(2u, result.size());
1594  EXPECT_EQ("1", result[0]);
1595  EXPECT_EQ("\"a\"", result[1]);
1596}
1597
1598#endif  // GTEST_HAS_TR1_TUPLE
1599
1600#if GTEST_HAS_STD_TUPLE_
1601
1602TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1603  Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1604  EXPECT_EQ(0u, result.size());
1605}
1606
1607TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1608  Strings result = UniversalTersePrintTupleFieldsToStrings(
1609      ::std::make_tuple(1));
1610  ASSERT_EQ(1u, result.size());
1611  EXPECT_EQ("1", result[0]);
1612}
1613
1614TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1615  Strings result = UniversalTersePrintTupleFieldsToStrings(
1616      ::std::make_tuple(1, 'a'));
1617  ASSERT_EQ(2u, result.size());
1618  EXPECT_EQ("1", result[0]);
1619  EXPECT_EQ("'a' (97, 0x61)", result[1]);
1620}
1621
1622TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1623  const int n = 1;
1624  Strings result = UniversalTersePrintTupleFieldsToStrings(
1625      ::std::tuple<const int&, const char*>(n, "a"));
1626  ASSERT_EQ(2u, result.size());
1627  EXPECT_EQ("1", result[0]);
1628  EXPECT_EQ("\"a\"", result[1]);
1629}
1630
1631#endif  // GTEST_HAS_STD_TUPLE_
1632
1633}  // namespace gtest_printers_test
1634}  // namespace testing
1635
trunk/3rdparty/googletest/googletest/test/gtest-test-part_test.cc
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: mheule@google.com (Markus Heule)
31//
32
33#include "gtest/gtest-test-part.h"
34
35#include "gtest/gtest.h"
36
37using testing::Message;
38using testing::Test;
39using testing::TestPartResult;
40using testing::TestPartResultArray;
41
42namespace {
43
44// Tests the TestPartResult class.
45
46// The test fixture for testing TestPartResult.
47class TestPartResultTest : public Test {
48 protected:
49  TestPartResultTest()
50      : r1_(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"),
51        r2_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure!"),
52        r3_(TestPartResult::kFatalFailure, NULL, -1, "Failure!") {}
53
54  TestPartResult r1_, r2_, r3_;
55};
56
57
58TEST_F(TestPartResultTest, ConstructorWorks) {
59  Message message;
60  message << "something is terribly wrong";
61  message << static_cast<const char*>(testing::internal::kStackTraceMarker);
62  message << "some unimportant stack trace";
63
64  const TestPartResult result(TestPartResult::kNonFatalFailure,
65                              "some_file.cc",
66                              42,
67                              message.GetString().c_str());
68
69  EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type());
70  EXPECT_STREQ("some_file.cc", result.file_name());
71  EXPECT_EQ(42, result.line_number());
72  EXPECT_STREQ(message.GetString().c_str(), result.message());
73  EXPECT_STREQ("something is terribly wrong", result.summary());
74}
75
76TEST_F(TestPartResultTest, ResultAccessorsWork) {
77  const TestPartResult success(TestPartResult::kSuccess,
78                               "file.cc",
79                               42,
80                               "message");
81  EXPECT_TRUE(success.passed());
82  EXPECT_FALSE(success.failed());
83  EXPECT_FALSE(success.nonfatally_failed());
84  EXPECT_FALSE(success.fatally_failed());
85
86  const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure,
87                                        "file.cc",
88                                        42,
89                                        "message");
90  EXPECT_FALSE(nonfatal_failure.passed());
91  EXPECT_TRUE(nonfatal_failure.failed());
92  EXPECT_TRUE(nonfatal_failure.nonfatally_failed());
93  EXPECT_FALSE(nonfatal_failure.fatally_failed());
94
95  const TestPartResult fatal_failure(TestPartResult::kFatalFailure,
96                                     "file.cc",
97                                     42,
98                                     "message");
99  EXPECT_FALSE(fatal_failure.passed());
100  EXPECT_TRUE(fatal_failure.failed());
101  EXPECT_FALSE(fatal_failure.nonfatally_failed());
102  EXPECT_TRUE(fatal_failure.fatally_failed());
103}
104
105// Tests TestPartResult::type().
106TEST_F(TestPartResultTest, type) {
107  EXPECT_EQ(TestPartResult::kSuccess, r1_.type());
108  EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type());
109  EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type());
110}
111
112// Tests TestPartResult::file_name().
113TEST_F(TestPartResultTest, file_name) {
114  EXPECT_STREQ("foo/bar.cc", r1_.file_name());
115  EXPECT_STREQ(NULL, r3_.file_name());
116}
117
118// Tests TestPartResult::line_number().
119TEST_F(TestPartResultTest, line_number) {
120  EXPECT_EQ(10, r1_.line_number());
121  EXPECT_EQ(-1, r2_.line_number());
122}
123
124// Tests TestPartResult::message().
125TEST_F(TestPartResultTest, message) {
126  EXPECT_STREQ("Success!", r1_.message());
127}
128
129// Tests TestPartResult::passed().
130TEST_F(TestPartResultTest, Passed) {
131  EXPECT_TRUE(r1_.passed());
132  EXPECT_FALSE(r2_.passed());
133  EXPECT_FALSE(r3_.passed());
134}
135
136// Tests TestPartResult::failed().
137TEST_F(TestPartResultTest, Failed) {
138  EXPECT_FALSE(r1_.failed());
139  EXPECT_TRUE(r2_.failed());
140  EXPECT_TRUE(r3_.failed());
141}
142
143// Tests TestPartResult::fatally_failed().
144TEST_F(TestPartResultTest, FatallyFailed) {
145  EXPECT_FALSE(r1_.fatally_failed());
146  EXPECT_FALSE(r2_.fatally_failed());
147  EXPECT_TRUE(r3_.fatally_failed());
148}
149
150// Tests TestPartResult::nonfatally_failed().
151TEST_F(TestPartResultTest, NonfatallyFailed) {
152  EXPECT_FALSE(r1_.nonfatally_failed());
153  EXPECT_TRUE(r2_.nonfatally_failed());
154  EXPECT_FALSE(r3_.nonfatally_failed());
155}
156
157// Tests the TestPartResultArray class.
158
159class TestPartResultArrayTest : public Test {
160 protected:
161  TestPartResultArrayTest()
162      : r1_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure 1"),
163        r2_(TestPartResult::kFatalFailure, "foo/bar.cc", -1, "Failure 2") {}
164
165  const TestPartResult r1_, r2_;
166};
167
168// Tests that TestPartResultArray initially has size 0.
169TEST_F(TestPartResultArrayTest, InitialSizeIsZero) {
170  TestPartResultArray results;
171  EXPECT_EQ(0, results.size());
172}
173
174// Tests that TestPartResultArray contains the given TestPartResult
175// after one Append() operation.
176TEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) {
177  TestPartResultArray results;
178  results.Append(r1_);
179  EXPECT_EQ(1, results.size());
180  EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message());
181}
182
183// Tests that TestPartResultArray contains the given TestPartResults
184// after two Append() operations.
185TEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) {
186  TestPartResultArray results;
187  results.Append(r1_);
188  results.Append(r2_);
189  EXPECT_EQ(2, results.size());
190  EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message());
191  EXPECT_STREQ("Failure 2", results.GetTestPartResult(1).message());
192}
193
194typedef TestPartResultArrayTest TestPartResultArrayDeathTest;
195
196// Tests that the program dies when GetTestPartResult() is called with
197// an invalid index.
198TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) {
199  TestPartResultArray results;
200  results.Append(r1_);
201
202  EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(-1), "");
203  EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), "");
204}
205
206// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper.
207
208}  // namespace
trunk/3rdparty/googletest/googletest/test/gtest-tuple_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gtest/internal/gtest-tuple.h"
33#include <utility>
34#include "gtest/gtest.h"
35
36namespace {
37
38using ::std::tr1::get;
39using ::std::tr1::make_tuple;
40using ::std::tr1::tuple;
41using ::std::tr1::tuple_element;
42using ::std::tr1::tuple_size;
43using ::testing::StaticAssertTypeEq;
44
45// Tests that tuple_element<K, tuple<T0, T1, ..., TN> >::type returns TK.
46TEST(tuple_element_Test, ReturnsElementType) {
47  StaticAssertTypeEq<int, tuple_element<0, tuple<int, char> >::type>();
48  StaticAssertTypeEq<int&, tuple_element<1, tuple<double, int&> >::type>();
49  StaticAssertTypeEq<bool, tuple_element<2, tuple<double, int, bool> >::type>();
50}
51
52// Tests that tuple_size<T>::value gives the number of fields in tuple
53// type T.
54TEST(tuple_size_Test, ReturnsNumberOfFields) {
55  EXPECT_EQ(0, +tuple_size<tuple<> >::value);
56  EXPECT_EQ(1, +tuple_size<tuple<void*> >::value);
57  EXPECT_EQ(1, +tuple_size<tuple<char> >::value);
58  EXPECT_EQ(1, +(tuple_size<tuple<tuple<int, double> > >::value));
59  EXPECT_EQ(2, +(tuple_size<tuple<int&, const char> >::value));
60  EXPECT_EQ(3, +(tuple_size<tuple<char*, void, const bool&> >::value));
61}
62
63// Tests comparing a tuple with itself.
64TEST(ComparisonTest, ComparesWithSelf) {
65  const tuple<int, char, bool> a(5, 'a', false);
66
67  EXPECT_TRUE(a == a);
68  EXPECT_FALSE(a != a);
69}
70
71// Tests comparing two tuples with the same value.
72TEST(ComparisonTest, ComparesEqualTuples) {
73  const tuple<int, bool> a(5, true), b(5, true);
74
75  EXPECT_TRUE(a == b);
76  EXPECT_FALSE(a != b);
77}
78
79// Tests comparing two different tuples that have no reference fields.
80TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) {
81  typedef tuple<const int, char> FooTuple;
82
83  const FooTuple a(0, 'x');
84  const FooTuple b(1, 'a');
85
86  EXPECT_TRUE(a != b);
87  EXPECT_FALSE(a == b);
88
89  const FooTuple c(1, 'b');
90
91  EXPECT_TRUE(b != c);
92  EXPECT_FALSE(b == c);
93}
94
95// Tests comparing two different tuples that have reference fields.
96TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) {
97  typedef tuple<int&, const char&> FooTuple;
98
99  int i = 5;
100  const char ch = 'a';
101  const FooTuple a(i, ch);
102
103  int j = 6;
104  const FooTuple b(j, ch);
105
106  EXPECT_TRUE(a != b);
107  EXPECT_FALSE(a == b);
108
109  j = 5;
110  const char ch2 = 'b';
111  const FooTuple c(j, ch2);
112
113  EXPECT_TRUE(b != c);
114  EXPECT_FALSE(b == c);
115}
116
117// Tests that a tuple field with a reference type is an alias of the
118// variable it's supposed to reference.
119TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) {
120  int n = 0;
121  tuple<bool, int&> t(true, n);
122
123  n = 1;
124  EXPECT_EQ(n, get<1>(t))
125      << "Changing a underlying variable should update the reference field.";
126
127  // Makes sure that the implementation doesn't do anything funny with
128  // the & operator for the return type of get<>().
129  EXPECT_EQ(&n, &(get<1>(t)))
130      << "The address of a reference field should equal the address of "
131      << "the underlying variable.";
132
133  get<1>(t) = 2;
134  EXPECT_EQ(2, n)
135      << "Changing a reference field should update the underlying variable.";
136}
137
138// Tests that tuple's default constructor default initializes each field.
139// This test needs to compile without generating warnings.
140TEST(TupleConstructorTest, DefaultConstructorDefaultInitializesEachField) {
141  // The TR1 report requires that tuple's default constructor default
142  // initializes each field, even if it's a primitive type.  If the
143  // implementation forgets to do this, this test will catch it by
144  // generating warnings about using uninitialized variables (assuming
145  // a decent compiler).
146
147  tuple<> empty;
148
149  tuple<int> a1, b1;
150  b1 = a1;
151  EXPECT_EQ(0, get<0>(b1));
152
153  tuple<int, double> a2, b2;
154  b2 = a2;
155  EXPECT_EQ(0, get<0>(b2));
156  EXPECT_EQ(0.0, get<1>(b2));
157
158  tuple<double, char, bool*> a3, b3;
159  b3 = a3;
160  EXPECT_EQ(0.0, get<0>(b3));
161  EXPECT_EQ('\0', get<1>(b3));
162  EXPECT_TRUE(get<2>(b3) == NULL);
163
164  tuple<int, int, int, int, int, int, int, int, int, int> a10, b10;
165  b10 = a10;
166  EXPECT_EQ(0, get<0>(b10));
167  EXPECT_EQ(0, get<1>(b10));
168  EXPECT_EQ(0, get<2>(b10));
169  EXPECT_EQ(0, get<3>(b10));
170  EXPECT_EQ(0, get<4>(b10));
171  EXPECT_EQ(0, get<5>(b10));
172  EXPECT_EQ(0, get<6>(b10));
173  EXPECT_EQ(0, get<7>(b10));
174  EXPECT_EQ(0, get<8>(b10));
175  EXPECT_EQ(0, get<9>(b10));
176}
177
178// Tests constructing a tuple from its fields.
179TEST(TupleConstructorTest, ConstructsFromFields) {
180  int n = 1;
181  // Reference field.
182  tuple<int&> a(n);
183  EXPECT_EQ(&n, &(get<0>(a)));
184
185  // Non-reference fields.
186  tuple<int, char> b(5, 'a');
187  EXPECT_EQ(5, get<0>(b));
188  EXPECT_EQ('a', get<1>(b));
189
190  // Const reference field.
191  const int m = 2;
192  tuple<bool, const int&> c(true, m);
193  EXPECT_TRUE(get<0>(c));
194  EXPECT_EQ(&m, &(get<1>(c)));
195}
196
197// Tests tuple's copy constructor.
198TEST(TupleConstructorTest, CopyConstructor) {
199  tuple<double, bool> a(0.0, true);
200  tuple<double, bool> b(a);
201
202  EXPECT_DOUBLE_EQ(0.0, get<0>(b));
203  EXPECT_TRUE(get<1>(b));
204}
205
206// Tests constructing a tuple from another tuple that has a compatible
207// but different type.
208TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) {
209  tuple<int, int, char> a(0, 1, 'a');
210  tuple<double, long, int> b(a);
211
212  EXPECT_DOUBLE_EQ(0.0, get<0>(b));
213  EXPECT_EQ(1, get<1>(b));
214  EXPECT_EQ('a', get<2>(b));
215}
216
217// Tests constructing a 2-tuple from an std::pair.
218TEST(TupleConstructorTest, ConstructsFromPair) {
219  ::std::pair<int, char> a(1, 'a');
220  tuple<int, char> b(a);
221  tuple<int, const char&> c(a);
222}
223
224// Tests assigning a tuple to another tuple with the same type.
225TEST(TupleAssignmentTest, AssignsToSameTupleType) {
226  const tuple<int, long> a(5, 7L);
227  tuple<int, long> b;
228  b = a;
229  EXPECT_EQ(5, get<0>(b));
230  EXPECT_EQ(7L, get<1>(b));
231}
232
233// Tests assigning a tuple to another tuple with a different but
234// compatible type.
235TEST(TupleAssignmentTest, AssignsToDifferentTupleType) {
236  const tuple<int, long, bool> a(1, 7L, true);
237  tuple<long, int, bool> b;
238  b = a;
239  EXPECT_EQ(1L, get<0>(b));
240  EXPECT_EQ(7, get<1>(b));
241  EXPECT_TRUE(get<2>(b));
242}
243
244// Tests assigning an std::pair to a 2-tuple.
245TEST(TupleAssignmentTest, AssignsFromPair) {
246  const ::std::pair<int, bool> a(5, true);
247  tuple<int, bool> b;
248  b = a;
249  EXPECT_EQ(5, get<0>(b));
250  EXPECT_TRUE(get<1>(b));
251
252  tuple<long, bool> c;
253  c = a;
254  EXPECT_EQ(5L, get<0>(c));
255  EXPECT_TRUE(get<1>(c));
256}
257
258// A fixture for testing big tuples.
259class BigTupleTest : public testing::Test {
260 protected:
261  typedef tuple<int, int, int, int, int, int, int, int, int, int> BigTuple;
262
263  BigTupleTest() :
264      a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2),
265      b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {}
266
267  BigTuple a_, b_;
268};
269
270// Tests constructing big tuples.
271TEST_F(BigTupleTest, Construction) {
272  BigTuple a;
273  BigTuple b(b_);
274}
275
276// Tests that get<N>(t) returns the N-th (0-based) field of tuple t.
277TEST_F(BigTupleTest, get) {
278  EXPECT_EQ(1, get<0>(a_));
279  EXPECT_EQ(2, get<9>(a_));
280
281  // Tests that get() works on a const tuple too.
282  const BigTuple a(a_);
283  EXPECT_EQ(1, get<0>(a));
284  EXPECT_EQ(2, get<9>(a));
285}
286
287// Tests comparing big tuples.
288TEST_F(BigTupleTest, Comparisons) {
289  EXPECT_TRUE(a_ == a_);
290  EXPECT_FALSE(a_ != a_);
291
292  EXPECT_TRUE(a_ != b_);
293  EXPECT_FALSE(a_ == b_);
294}
295
296TEST(MakeTupleTest, WorksForScalarTypes) {
297  tuple<bool, int> a;
298  a = make_tuple(true, 5);
299  EXPECT_TRUE(get<0>(a));
300  EXPECT_EQ(5, get<1>(a));
301
302  tuple<char, int, long> b;
303  b = make_tuple('a', 'b', 5);
304  EXPECT_EQ('a', get<0>(b));
305  EXPECT_EQ('b', get<1>(b));
306  EXPECT_EQ(5, get<2>(b));
307}
308
309TEST(MakeTupleTest, WorksForPointers) {
310  int a[] = { 1, 2, 3, 4 };
311  const char* const str = "hi";
312  int* const p = a;
313
314  tuple<const char*, int*> t;
315  t = make_tuple(str, p);
316  EXPECT_EQ(str, get<0>(t));
317  EXPECT_EQ(p, get<1>(t));
318}
319
320}  // namespace
trunk/3rdparty/googletest/googletest/test/gtest-typed-test2_test.cc
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include <vector>
33
34#include "test/gtest-typed-test_test.h"
35#include "gtest/gtest.h"
36
37#if GTEST_HAS_TYPED_TEST_P
38
39// Tests that the same type-parameterized test case can be
40// instantiated in different translation units linked together.
41// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)
42INSTANTIATE_TYPED_TEST_CASE_P(Vector, ContainerTest,
43                              testing::Types<std::vector<int> >);
44
45#endif  // GTEST_HAS_TYPED_TEST_P
trunk/3rdparty/googletest/googletest/test/gtest-typed-test_test.cc
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "test/gtest-typed-test_test.h"
33
34#include <set>
35#include <vector>
36
37#include "gtest/gtest.h"
38
39using testing::Test;
40
41// Used for testing that SetUpTestCase()/TearDownTestCase(), fixture
42// ctor/dtor, and SetUp()/TearDown() work correctly in typed tests and
43// type-parameterized test.
44template <typename T>
45class CommonTest : public Test {
46  // For some technical reason, SetUpTestCase() and TearDownTestCase()
47  // must be public.
48 public:
49  static void SetUpTestCase() {
50    shared_ = new T(5);
51  }
52
53  static void TearDownTestCase() {
54    delete shared_;
55    shared_ = NULL;
56  }
57
58  // This 'protected:' is optional.  There's no harm in making all
59  // members of this fixture class template public.
60 protected:
61  // We used to use std::list here, but switched to std::vector since
62  // MSVC's <list> doesn't compile cleanly with /W4.
63  typedef std::vector<T> Vector;
64  typedef std::set<int> IntSet;
65
66  CommonTest() : value_(1) {}
67
68  virtual ~CommonTest() { EXPECT_EQ(3, value_); }
69
70  virtual void SetUp() {
71    EXPECT_EQ(1, value_);
72    value_++;
73  }
74
75  virtual void TearDown() {
76    EXPECT_EQ(2, value_);
77    value_++;
78  }
79
80  T value_;
81  static T* shared_;
82};
83
84template <typename T>
85T* CommonTest<T>::shared_ = NULL;
86
87// This #ifdef block tests typed tests.
88#if GTEST_HAS_TYPED_TEST
89
90using testing::Types;
91
92// Tests that SetUpTestCase()/TearDownTestCase(), fixture ctor/dtor,
93// and SetUp()/TearDown() work correctly in typed tests
94
95typedef Types<char, int> TwoTypes;
96TYPED_TEST_CASE(CommonTest, TwoTypes);
97
98TYPED_TEST(CommonTest, ValuesAreCorrect) {
99  // Static members of the fixture class template can be visited via
100  // the TestFixture:: prefix.
101  EXPECT_EQ(5, *TestFixture::shared_);
102
103  // Typedefs in the fixture class template can be visited via the
104  // "typename TestFixture::" prefix.
105  typename TestFixture::Vector empty;
106  EXPECT_EQ(0U, empty.size());
107
108  typename TestFixture::IntSet empty2;
109  EXPECT_EQ(0U, empty2.size());
110
111  // Non-static members of the fixture class must be visited via
112  // 'this', as required by C++ for class templates.
113  EXPECT_EQ(2, this->value_);
114}
115
116// The second test makes sure shared_ is not deleted after the first
117// test.
118TYPED_TEST(CommonTest, ValuesAreStillCorrect) {
119  // Static members of the fixture class template can also be visited
120  // via 'this'.
121  ASSERT_TRUE(this->shared_ != NULL);
122  EXPECT_EQ(5, *this->shared_);
123
124  // TypeParam can be used to refer to the type parameter.
125  EXPECT_EQ(static_cast<TypeParam>(2), this->value_);
126}
127
128// Tests that multiple TYPED_TEST_CASE's can be defined in the same
129// translation unit.
130
131template <typename T>
132class TypedTest1 : public Test {
133};
134
135// Verifies that the second argument of TYPED_TEST_CASE can be a
136// single type.
137TYPED_TEST_CASE(TypedTest1, int);
138TYPED_TEST(TypedTest1, A) {}
139
140template <typename T>
141class TypedTest2 : public Test {
142};
143
144// Verifies that the second argument of TYPED_TEST_CASE can be a
145// Types<...> type list.
146TYPED_TEST_CASE(TypedTest2, Types<int>);
147
148// This also verifies that tests from different typed test cases can
149// share the same name.
150TYPED_TEST(TypedTest2, A) {}
151
152// Tests that a typed test case can be defined in a namespace.
153
154namespace library1 {
155
156template <typename T>
157class NumericTest : public Test {
158};
159
160typedef Types<int, long> NumericTypes;
161TYPED_TEST_CASE(NumericTest, NumericTypes);
162
163TYPED_TEST(NumericTest, DefaultIsZero) {
164  EXPECT_EQ(0, TypeParam());
165}
166
167}  // namespace library1
168
169#endif  // GTEST_HAS_TYPED_TEST
170
171// This #ifdef block tests type-parameterized tests.
172#if GTEST_HAS_TYPED_TEST_P
173
174using testing::Types;
175using testing::internal::TypedTestCasePState;
176
177// Tests TypedTestCasePState.
178
179class TypedTestCasePStateTest : public Test {
180 protected:
181  virtual void SetUp() {
182    state_.AddTestName("foo.cc", 0, "FooTest", "A");
183    state_.AddTestName("foo.cc", 0, "FooTest", "B");
184    state_.AddTestName("foo.cc", 0, "FooTest", "C");
185  }
186
187  TypedTestCasePState state_;
188};
189
190TEST_F(TypedTestCasePStateTest, SucceedsForMatchingList) {
191  const char* tests = "A, B, C";
192  EXPECT_EQ(tests,
193            state_.VerifyRegisteredTestNames("foo.cc", 1, tests));
194}
195
196// Makes sure that the order of the tests and spaces around the names
197// don't matter.
198TEST_F(TypedTestCasePStateTest, IgnoresOrderAndSpaces) {
199  const char* tests = "A,C,   B";
200  EXPECT_EQ(tests,
201            state_.VerifyRegisteredTestNames("foo.cc", 1, tests));
202}
203
204typedef TypedTestCasePStateTest TypedTestCasePStateDeathTest;
205
206TEST_F(TypedTestCasePStateDeathTest, DetectsDuplicates) {
207  EXPECT_DEATH_IF_SUPPORTED(
208      state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, A, C"),
209      "foo\\.cc.1.?: Test A is listed more than once\\.");
210}
211
212TEST_F(TypedTestCasePStateDeathTest, DetectsExtraTest) {
213  EXPECT_DEATH_IF_SUPPORTED(
214      state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C, D"),
215      "foo\\.cc.1.?: No test named D can be found in this test case\\.");
216}
217
218TEST_F(TypedTestCasePStateDeathTest, DetectsMissedTest) {
219  EXPECT_DEATH_IF_SUPPORTED(
220      state_.VerifyRegisteredTestNames("foo.cc", 1, "A, C"),
221      "foo\\.cc.1.?: You forgot to list test B\\.");
222}
223
224// Tests that defining a test for a parameterized test case generates
225// a run-time error if the test case has been registered.
226TEST_F(TypedTestCasePStateDeathTest, DetectsTestAfterRegistration) {
227  state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C");
228  EXPECT_DEATH_IF_SUPPORTED(
229      state_.AddTestName("foo.cc", 2, "FooTest", "D"),
230      "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_CASE_P"
231      "\\(FooTest, \\.\\.\\.\\)\\.");
232}
233
234// Tests that SetUpTestCase()/TearDownTestCase(), fixture ctor/dtor,
235// and SetUp()/TearDown() work correctly in type-parameterized tests.
236
237template <typename T>
238class DerivedTest : public CommonTest<T> {
239};
240
241TYPED_TEST_CASE_P(DerivedTest);
242
243TYPED_TEST_P(DerivedTest, ValuesAreCorrect) {
244  // Static members of the fixture class template can be visited via
245  // the TestFixture:: prefix.
246  EXPECT_EQ(5, *TestFixture::shared_);
247
248  // Non-static members of the fixture class must be visited via
249  // 'this', as required by C++ for class templates.
250  EXPECT_EQ(2, this->value_);
251}
252
253// The second test makes sure shared_ is not deleted after the first
254// test.
255TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) {
256  // Static members of the fixture class template can also be visited
257  // via 'this'.
258  ASSERT_TRUE(this->shared_ != NULL);
259  EXPECT_EQ(5, *this->shared_);
260  EXPECT_EQ(2, this->value_);
261}
262
263REGISTER_TYPED_TEST_CASE_P(DerivedTest,
264                           ValuesAreCorrect, ValuesAreStillCorrect);
265
266typedef Types<short, long> MyTwoTypes;
267INSTANTIATE_TYPED_TEST_CASE_P(My, DerivedTest, MyTwoTypes);
268
269// Tests that multiple TYPED_TEST_CASE_P's can be defined in the same
270// translation unit.
271
272template <typename T>
273class TypedTestP1 : public Test {
274};
275
276TYPED_TEST_CASE_P(TypedTestP1);
277
278// For testing that the code between TYPED_TEST_CASE_P() and
279// TYPED_TEST_P() is not enclosed in a namespace.
280typedef int IntAfterTypedTestCaseP;
281
282TYPED_TEST_P(TypedTestP1, A) {}
283TYPED_TEST_P(TypedTestP1, B) {}
284
285// For testing that the code between TYPED_TEST_P() and
286// REGISTER_TYPED_TEST_CASE_P() is not enclosed in a namespace.
287typedef int IntBeforeRegisterTypedTestCaseP;
288
289REGISTER_TYPED_TEST_CASE_P(TypedTestP1, A, B);
290
291template <typename T>
292class TypedTestP2 : public Test {
293};
294
295TYPED_TEST_CASE_P(TypedTestP2);
296
297// This also verifies that tests from different type-parameterized
298// test cases can share the same name.
299TYPED_TEST_P(TypedTestP2, A) {}
300
301REGISTER_TYPED_TEST_CASE_P(TypedTestP2, A);
302
303// Verifies that the code between TYPED_TEST_CASE_P() and
304// REGISTER_TYPED_TEST_CASE_P() is not enclosed in a namespace.
305IntAfterTypedTestCaseP after = 0;
306IntBeforeRegisterTypedTestCaseP before = 0;
307
308// Verifies that the last argument of INSTANTIATE_TYPED_TEST_CASE_P()
309// can be either a single type or a Types<...> type list.
310INSTANTIATE_TYPED_TEST_CASE_P(Int, TypedTestP1, int);
311INSTANTIATE_TYPED_TEST_CASE_P(Int, TypedTestP2, Types<int>);
312
313// Tests that the same type-parameterized test case can be
314// instantiated more than once in the same translation unit.
315INSTANTIATE_TYPED_TEST_CASE_P(Double, TypedTestP2, Types<double>);
316
317// Tests that the same type-parameterized test case can be
318// instantiated in different translation units linked together.
319// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)
320typedef Types<std::vector<double>, std::set<char> > MyContainers;
321INSTANTIATE_TYPED_TEST_CASE_P(My, ContainerTest, MyContainers);
322
323// Tests that a type-parameterized test case can be defined and
324// instantiated in a namespace.
325
326namespace library2 {
327
328template <typename T>
329class NumericTest : public Test {
330};
331
332TYPED_TEST_CASE_P(NumericTest);
333
334TYPED_TEST_P(NumericTest, DefaultIsZero) {
335  EXPECT_EQ(0, TypeParam());
336}
337
338TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) {
339  EXPECT_LT(TypeParam(0), TypeParam(1));
340}
341
342REGISTER_TYPED_TEST_CASE_P(NumericTest,
343                           DefaultIsZero, ZeroIsLessThanOne);
344typedef Types<int, double> NumericTypes;
345INSTANTIATE_TYPED_TEST_CASE_P(My, NumericTest, NumericTypes);
346
347static const char* GetTestName() {
348  return testing::UnitTest::GetInstance()->current_test_info()->name();
349}
350// Test the stripping of space from test names
351template <typename T> class TrimmedTest : public Test { };
352TYPED_TEST_CASE_P(TrimmedTest);
353TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); }
354TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); }
355TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); }
356TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); }
357TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); }
358REGISTER_TYPED_TEST_CASE_P(
359    TrimmedTest,
360    Test1, Test2,Test3 , Test4 ,Test5 );  // NOLINT
361template <typename T1, typename T2> struct MyPair {};
362// Be sure to try a type with a comma in its name just in case it matters.
363typedef Types<int, double, MyPair<int, int> > TrimTypes;
364INSTANTIATE_TYPED_TEST_CASE_P(My, TrimmedTest, TrimTypes);
365
366}  // namespace library2
367
368#endif  // GTEST_HAS_TYPED_TEST_P
369
370#if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
371
372// Google Test may not support type-parameterized tests with some
373// compilers. If we use conditional compilation to compile out all
374// code referring to the gtest_main library, MSVC linker will not link
375// that library at all and consequently complain about missing entry
376// point defined in that library (fatal error LNK1561: entry point
377// must be defined). This dummy test keeps gtest_main linked in.
378TEST(DummyTest, TypedTestsAreNotSupportedOnThisPlatform) {}
379
380#endif  // #if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
trunk/3rdparty/googletest/googletest/test/gtest-typed-test_test.h
r0r249096
1// Copyright 2008 Google Inc.
2// All Rights Reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
33#define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
34
35#include "gtest/gtest.h"
36
37#if GTEST_HAS_TYPED_TEST_P
38
39using testing::Test;
40
41// For testing that the same type-parameterized test case can be
42// instantiated in different translation units linked together.
43// ContainerTest will be instantiated in both gtest-typed-test_test.cc
44// and gtest-typed-test2_test.cc.
45
46template <typename T>
47class ContainerTest : public Test {
48};
49
50TYPED_TEST_CASE_P(ContainerTest);
51
52TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) {
53  TypeParam container;
54}
55
56TYPED_TEST_P(ContainerTest, InitialSizeIsZero) {
57  TypeParam container;
58  EXPECT_EQ(0U, container.size());
59}
60
61REGISTER_TYPED_TEST_CASE_P(ContainerTest,
62                           CanBeDefaultConstructed, InitialSizeIsZero);
63
64#endif  // GTEST_HAS_TYPED_TEST_P
65
66#endif  // GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
trunk/3rdparty/googletest/googletest/test/gtest-unittest-api_test.cc
r0r249096
1// Copyright 2009 Google Inc.  All rights reserved.
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are
5// met:
6//
7//     * Redistributions of source code must retain the above copyright
8// notice, this list of conditions and the following disclaimer.
9//     * Redistributions in binary form must reproduce the above
10// copyright notice, this list of conditions and the following disclaimer
11// in the documentation and/or other materials provided with the
12// distribution.
13//     * Neither the name of Google Inc. nor the names of its
14// contributors may be used to endorse or promote products derived from
15// this software without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: vladl@google.com (Vlad Losev)
30//
31// The Google C++ Testing Framework (Google Test)
32//
33// This file contains tests verifying correctness of data provided via
34// UnitTest's public methods.
35
36#include "gtest/gtest.h"
37
38#include <string.h>  // For strcmp.
39#include <algorithm>
40
41using ::testing::InitGoogleTest;
42
43namespace testing {
44namespace internal {
45
46template <typename T>
47struct LessByName {
48  bool operator()(const T* a, const T* b) {
49    return strcmp(a->name(), b->name()) < 0;
50  }
51};
52
53class UnitTestHelper {
54 public:
55  // Returns the array of pointers to all test cases sorted by the test case
56  // name.  The caller is responsible for deleting the array.
57  static TestCase const** GetSortedTestCases() {
58    UnitTest& unit_test = *UnitTest::GetInstance();
59    TestCase const** const test_cases =
60        new const TestCase*[unit_test.total_test_case_count()];
61
62    for (int i = 0; i < unit_test.total_test_case_count(); ++i)
63      test_cases[i] = unit_test.GetTestCase(i);
64
65    std::sort(test_cases,
66              test_cases + unit_test.total_test_case_count(),
67              LessByName<TestCase>());
68    return test_cases;
69  }
70
71  // Returns the test case by its name.  The caller doesn't own the returned
72  // pointer.
73  static const TestCase* FindTestCase(const char* name) {
74    UnitTest& unit_test = *UnitTest::GetInstance();
75    for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
76      const TestCase* test_case = unit_test.GetTestCase(i);
77      if (0 == strcmp(test_case->name(), name))
78        return test_case;
79    }
80    return NULL;
81  }
82
83  // Returns the array of pointers to all tests in a particular test case
84  // sorted by the test name.  The caller is responsible for deleting the
85  // array.
86  static TestInfo const** GetSortedTests(const TestCase* test_case) {
87    TestInfo const** const tests =
88        new const TestInfo*[test_case->total_test_count()];
89
90    for (int i = 0; i < test_case->total_test_count(); ++i)
91      tests[i] = test_case->GetTestInfo(i);
92
93    std::sort(tests, tests + test_case->total_test_count(),
94              LessByName<TestInfo>());
95    return tests;
96  }
97};
98
99#if GTEST_HAS_TYPED_TEST
100template <typename T> class TestCaseWithCommentTest : public Test {};
101TYPED_TEST_CASE(TestCaseWithCommentTest, Types<int>);
102TYPED_TEST(TestCaseWithCommentTest, Dummy) {}
103
104const int kTypedTestCases = 1;
105const int kTypedTests = 1;
106#else
107const int kTypedTestCases = 0;
108const int kTypedTests = 0;
109#endif  // GTEST_HAS_TYPED_TEST
110
111// We can only test the accessors that do not change value while tests run.
112// Since tests can be run in any order, the values the accessors that track
113// test execution (such as failed_test_count) can not be predicted.
114TEST(ApiTest, UnitTestImmutableAccessorsWork) {
115  UnitTest* unit_test = UnitTest::GetInstance();
116
117  ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
118  EXPECT_EQ(1 + kTypedTestCases, unit_test->test_case_to_run_count());
119  EXPECT_EQ(2, unit_test->disabled_test_count());
120  EXPECT_EQ(5 + kTypedTests, unit_test->total_test_count());
121  EXPECT_EQ(3 + kTypedTests, unit_test->test_to_run_count());
122
123  const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
124
125  EXPECT_STREQ("ApiTest", test_cases[0]->name());
126  EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
127#if GTEST_HAS_TYPED_TEST
128  EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
129#endif  // GTEST_HAS_TYPED_TEST
130
131  delete[] test_cases;
132
133  // The following lines initiate actions to verify certain methods in
134  // FinalSuccessChecker::TearDown.
135
136  // Records a test property to verify TestResult::GetTestProperty().
137  RecordProperty("key", "value");
138}
139
140AssertionResult IsNull(const char* str) {
141  if (str != NULL) {
142    return testing::AssertionFailure() << "argument is " << str;
143  }
144  return AssertionSuccess();
145}
146
147TEST(ApiTest, TestCaseImmutableAccessorsWork) {
148  const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
149  ASSERT_TRUE(test_case != NULL);
150
151  EXPECT_STREQ("ApiTest", test_case->name());
152  EXPECT_TRUE(IsNull(test_case->type_param()));
153  EXPECT_TRUE(test_case->should_run());
154  EXPECT_EQ(1, test_case->disabled_test_count());
155  EXPECT_EQ(3, test_case->test_to_run_count());
156  ASSERT_EQ(4, test_case->total_test_count());
157
158  const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
159
160  EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
161  EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
162  EXPECT_TRUE(IsNull(tests[0]->value_param()));
163  EXPECT_TRUE(IsNull(tests[0]->type_param()));
164  EXPECT_FALSE(tests[0]->should_run());
165
166  EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
167  EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
168  EXPECT_TRUE(IsNull(tests[1]->value_param()));
169  EXPECT_TRUE(IsNull(tests[1]->type_param()));
170  EXPECT_TRUE(tests[1]->should_run());
171
172  EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
173  EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
174  EXPECT_TRUE(IsNull(tests[2]->value_param()));
175  EXPECT_TRUE(IsNull(tests[2]->type_param()));
176  EXPECT_TRUE(tests[2]->should_run());
177
178  EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
179  EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
180  EXPECT_TRUE(IsNull(tests[3]->value_param()));
181  EXPECT_TRUE(IsNull(tests[3]->type_param()));
182  EXPECT_TRUE(tests[3]->should_run());
183
184  delete[] tests;
185  tests = NULL;
186
187#if GTEST_HAS_TYPED_TEST
188  test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
189  ASSERT_TRUE(test_case != NULL);
190
191  EXPECT_STREQ("TestCaseWithCommentTest/0", test_case->name());
192  EXPECT_STREQ(GetTypeName<int>().c_str(), test_case->type_param());
193  EXPECT_TRUE(test_case->should_run());
194  EXPECT_EQ(0, test_case->disabled_test_count());
195  EXPECT_EQ(1, test_case->test_to_run_count());
196  ASSERT_EQ(1, test_case->total_test_count());
197
198  tests = UnitTestHelper::GetSortedTests(test_case);
199
200  EXPECT_STREQ("Dummy", tests[0]->name());
201  EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
202  EXPECT_TRUE(IsNull(tests[0]->value_param()));
203  EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
204  EXPECT_TRUE(tests[0]->should_run());
205
206  delete[] tests;
207#endif  // GTEST_HAS_TYPED_TEST
208}
209
210TEST(ApiTest, TestCaseDisabledAccessorsWork) {
211  const TestCase* test_case = UnitTestHelper::FindTestCase("DISABLED_Test");
212  ASSERT_TRUE(test_case != NULL);
213
214  EXPECT_STREQ("DISABLED_Test", test_case->name());
215  EXPECT_TRUE(IsNull(test_case->type_param()));
216  EXPECT_FALSE(test_case->should_run());
217  EXPECT_EQ(1, test_case->disabled_test_count());
218  EXPECT_EQ(0, test_case->test_to_run_count());
219  ASSERT_EQ(1, test_case->total_test_count());
220
221  const TestInfo* const test_info = test_case->GetTestInfo(0);
222  EXPECT_STREQ("Dummy2", test_info->name());
223  EXPECT_STREQ("DISABLED_Test", test_info->test_case_name());
224  EXPECT_TRUE(IsNull(test_info->value_param()));
225  EXPECT_TRUE(IsNull(test_info->type_param()));
226  EXPECT_FALSE(test_info->should_run());
227}
228
229// These two tests are here to provide support for testing
230// test_case_to_run_count, disabled_test_count, and test_to_run_count.
231TEST(ApiTest, DISABLED_Dummy1) {}
232TEST(DISABLED_Test, Dummy2) {}
233
234class FinalSuccessChecker : public Environment {
235 protected:
236  virtual void TearDown() {
237    UnitTest* unit_test = UnitTest::GetInstance();
238
239    EXPECT_EQ(1 + kTypedTestCases, unit_test->successful_test_case_count());
240    EXPECT_EQ(3 + kTypedTests, unit_test->successful_test_count());
241    EXPECT_EQ(0, unit_test->failed_test_case_count());
242    EXPECT_EQ(0, unit_test->failed_test_count());
243    EXPECT_TRUE(unit_test->Passed());
244    EXPECT_FALSE(unit_test->Failed());
245    ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
246
247    const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
248
249    EXPECT_STREQ("ApiTest", test_cases[0]->name());
250    EXPECT_TRUE(IsNull(test_cases[0]->type_param()));
251    EXPECT_TRUE(test_cases[0]->should_run());
252    EXPECT_EQ(1, test_cases[0]->disabled_test_count());
253    ASSERT_EQ(4, test_cases[0]->total_test_count());
254    EXPECT_EQ(3, test_cases[0]->successful_test_count());
255    EXPECT_EQ(0, test_cases[0]->failed_test_count());
256    EXPECT_TRUE(test_cases[0]->Passed());
257    EXPECT_FALSE(test_cases[0]->Failed());
258
259    EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
260    EXPECT_TRUE(IsNull(test_cases[1]->type_param()));
261    EXPECT_FALSE(test_cases[1]->should_run());
262    EXPECT_EQ(1, test_cases[1]->disabled_test_count());
263    ASSERT_EQ(1, test_cases[1]->total_test_count());
264    EXPECT_EQ(0, test_cases[1]->successful_test_count());
265    EXPECT_EQ(0, test_cases[1]->failed_test_count());
266
267#if GTEST_HAS_TYPED_TEST
268    EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
269    EXPECT_STREQ(GetTypeName<int>().c_str(), test_cases[2]->type_param());
270    EXPECT_TRUE(test_cases[2]->should_run());
271    EXPECT_EQ(0, test_cases[2]->disabled_test_count());
272    ASSERT_EQ(1, test_cases[2]->total_test_count());
273    EXPECT_EQ(1, test_cases[2]->successful_test_count());
274    EXPECT_EQ(0, test_cases[2]->failed_test_count());
275    EXPECT_TRUE(test_cases[2]->Passed());
276    EXPECT_FALSE(test_cases[2]->Failed());
277#endif  // GTEST_HAS_TYPED_TEST
278
279    const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
280    const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
281    EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
282    EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
283    EXPECT_FALSE(tests[0]->should_run());
284
285    EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
286    EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
287    EXPECT_TRUE(IsNull(tests[1]->value_param()));
288    EXPECT_TRUE(IsNull(tests[1]->type_param()));
289    EXPECT_TRUE(tests[1]->should_run());
290    EXPECT_TRUE(tests[1]->result()->Passed());
291    EXPECT_EQ(0, tests[1]->result()->test_property_count());
292
293    EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
294    EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
295    EXPECT_TRUE(IsNull(tests[2]->value_param()));
296    EXPECT_TRUE(IsNull(tests[2]->type_param()));
297    EXPECT_TRUE(tests[2]->should_run());
298    EXPECT_TRUE(tests[2]->result()->Passed());
299    EXPECT_EQ(0, tests[2]->result()->test_property_count());
300
301    EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
302    EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
303    EXPECT_TRUE(IsNull(tests[3]->value_param()));
304    EXPECT_TRUE(IsNull(tests[3]->type_param()));
305    EXPECT_TRUE(tests[3]->should_run());
306    EXPECT_TRUE(tests[3]->result()->Passed());
307    EXPECT_EQ(1, tests[3]->result()->test_property_count());
308    const TestProperty& property = tests[3]->result()->GetTestProperty(0);
309    EXPECT_STREQ("key", property.key());
310    EXPECT_STREQ("value", property.value());
311
312    delete[] tests;
313
314#if GTEST_HAS_TYPED_TEST
315    test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
316    tests = UnitTestHelper::GetSortedTests(test_case);
317
318    EXPECT_STREQ("Dummy", tests[0]->name());
319    EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
320    EXPECT_TRUE(IsNull(tests[0]->value_param()));
321    EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
322    EXPECT_TRUE(tests[0]->should_run());
323    EXPECT_TRUE(tests[0]->result()->Passed());
324    EXPECT_EQ(0, tests[0]->result()->test_property_count());
325
326    delete[] tests;
327#endif  // GTEST_HAS_TYPED_TEST
328    delete[] test_cases;
329  }
330};
331
332}  // namespace internal
333}  // namespace testing
334
335int main(int argc, char **argv) {
336  InitGoogleTest(&argc, argv);
337
338  AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker());
339
340  return RUN_ALL_TESTS();
341}
trunk/3rdparty/googletest/googletest/test/gtest_all_test.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for Google C++ Testing Framework (Google Test)
33//
34// Sometimes it's desirable to build most of Google Test's own tests
35// by compiling a single file.  This file serves this purpose.
36#include "test/gtest-filepath_test.cc"
37#include "test/gtest-linked_ptr_test.cc"
38#include "test/gtest-message_test.cc"
39#include "test/gtest-options_test.cc"
40#include "test/gtest-port_test.cc"
41#include "test/gtest_pred_impl_unittest.cc"
42#include "test/gtest_prod_test.cc"
43#include "test/gtest-test-part_test.cc"
44#include "test/gtest-typed-test_test.cc"
45#include "test/gtest-typed-test2_test.cc"
46#include "test/gtest_unittest.cc"
47#include "test/production.cc"
trunk/3rdparty/googletest/googletest/test/gtest_break_on_failure_unittest.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2006, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Unit test for Google Test's break-on-failure mode.
33
34A user can ask Google Test to seg-fault when an assertion fails, using
35either the GTEST_BREAK_ON_FAILURE environment variable or the
36--gtest_break_on_failure flag.  This script tests such functionality
37by invoking gtest_break_on_failure_unittest_ (a program written with
38Google Test) with different environments and command line flags.
39"""
40
41__author__ = 'wan@google.com (Zhanyong Wan)'
42
43import gtest_test_utils
44import os
45import sys
46
47
48# Constants.
49
50IS_WINDOWS = os.name == 'nt'
51
52# The environment variable for enabling/disabling the break-on-failure mode.
53BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
54
55# The command line flag for enabling/disabling the break-on-failure mode.
56BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
57
58# The environment variable for enabling/disabling the throw-on-failure mode.
59THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'
60
61# The environment variable for enabling/disabling the catch-exceptions mode.
62CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
63
64# Path to the gtest_break_on_failure_unittest_ program.
65EXE_PATH = gtest_test_utils.GetTestExecutablePath(
66    'gtest_break_on_failure_unittest_')
67
68
69environ = gtest_test_utils.environ
70SetEnvVar = gtest_test_utils.SetEnvVar
71
72# Tests in this file run a Google-Test-based test program and expect it
73# to terminate prematurely.  Therefore they are incompatible with
74# the premature-exit-file protocol by design.  Unset the
75# premature-exit filepath to prevent Google Test from creating
76# the file.
77SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
78
79
80def Run(command):
81  """Runs a command; returns 1 if it was killed by a signal, or 0 otherwise."""
82
83  p = gtest_test_utils.Subprocess(command, env=environ)
84  if p.terminated_by_signal:
85    return 1
86  else:
87    return 0
88
89
90# The tests.
91
92
93class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
94  """Tests using the GTEST_BREAK_ON_FAILURE environment variable or
95  the --gtest_break_on_failure flag to turn assertion failures into
96  segmentation faults.
97  """
98
99  def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
100    """Runs gtest_break_on_failure_unittest_ and verifies that it does
101    (or does not) have a seg-fault.
102
103    Args:
104      env_var_value:    value of the GTEST_BREAK_ON_FAILURE environment
105                        variable; None if the variable should be unset.
106      flag_value:       value of the --gtest_break_on_failure flag;
107                        None if the flag should not be present.
108      expect_seg_fault: 1 if the program is expected to generate a seg-fault;
109                        0 otherwise.
110    """
111
112    SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
113
114    if env_var_value is None:
115      env_var_value_msg = ' is not set'
116    else:
117      env_var_value_msg = '=' + env_var_value
118
119    if flag_value is None:
120      flag = ''
121    elif flag_value == '0':
122      flag = '--%s=0' % BREAK_ON_FAILURE_FLAG
123    else:
124      flag = '--%s' % BREAK_ON_FAILURE_FLAG
125
126    command = [EXE_PATH]
127    if flag:
128      command.append(flag)
129
130    if expect_seg_fault:
131      should_or_not = 'should'
132    else:
133      should_or_not = 'should not'
134
135    has_seg_fault = Run(command)
136
137    SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
138
139    msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
140           (BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
141            should_or_not))
142    self.assert_(has_seg_fault == expect_seg_fault, msg)
143
144  def testDefaultBehavior(self):
145    """Tests the behavior of the default mode."""
146
147    self.RunAndVerify(env_var_value=None,
148                      flag_value=None,
149                      expect_seg_fault=0)
150
151  def testEnvVar(self):
152    """Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
153
154    self.RunAndVerify(env_var_value='0',
155                      flag_value=None,
156                      expect_seg_fault=0)
157    self.RunAndVerify(env_var_value='1',
158                      flag_value=None,
159                      expect_seg_fault=1)
160
161  def testFlag(self):
162    """Tests using the --gtest_break_on_failure flag."""
163
164    self.RunAndVerify(env_var_value=None,
165                      flag_value='0',
166                      expect_seg_fault=0)
167    self.RunAndVerify(env_var_value=None,
168                      flag_value='1',
169                      expect_seg_fault=1)
170
171  def testFlagOverridesEnvVar(self):
172    """Tests that the flag overrides the environment variable."""
173
174    self.RunAndVerify(env_var_value='0',
175                      flag_value='0',
176                      expect_seg_fault=0)
177    self.RunAndVerify(env_var_value='0',
178                      flag_value='1',
179                      expect_seg_fault=1)
180    self.RunAndVerify(env_var_value='1',
181                      flag_value='0',
182                      expect_seg_fault=0)
183    self.RunAndVerify(env_var_value='1',
184                      flag_value='1',
185                      expect_seg_fault=1)
186
187  def testBreakOnFailureOverridesThrowOnFailure(self):
188    """Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
189
190    SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
191    try:
192      self.RunAndVerify(env_var_value=None,
193                        flag_value='1',
194                        expect_seg_fault=1)
195    finally:
196      SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
197
198  if IS_WINDOWS:
199    def testCatchExceptionsDoesNotInterfere(self):
200      """Tests that gtest_catch_exceptions doesn't interfere."""
201
202      SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
203      try:
204        self.RunAndVerify(env_var_value='1',
205                          flag_value='1',
206                          expect_seg_fault=1)
207      finally:
208        SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
209
210
211if __name__ == '__main__':
212  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_break_on_failure_unittest_.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Unit test for Google Test's break-on-failure mode.
33//
34// A user can ask Google Test to seg-fault when an assertion fails, using
35// either the GTEST_BREAK_ON_FAILURE environment variable or the
36// --gtest_break_on_failure flag.  This file is used for testing such
37// functionality.
38//
39// This program will be invoked from a Python unit test.  It is
40// expected to fail.  Don't run it directly.
41
42#include "gtest/gtest.h"
43
44#if GTEST_OS_WINDOWS
45# include <windows.h>
46# include <stdlib.h>
47#endif
48
49namespace {
50
51// A test that's expected to fail.
52TEST(Foo, Bar) {
53  EXPECT_EQ(2, 3);
54}
55
56#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
57// On Windows Mobile global exception handlers are not supported.
58LONG WINAPI ExitWithExceptionCode(
59    struct _EXCEPTION_POINTERS* exception_pointers) {
60  exit(exception_pointers->ExceptionRecord->ExceptionCode);
61}
62#endif
63
64}  // namespace
65
66int main(int argc, char **argv) {
67#if GTEST_OS_WINDOWS
68  // Suppresses display of the Windows error dialog upon encountering
69  // a general protection fault (segment violation).
70  SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
71
72# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
73
74  // The default unhandled exception filter does not always exit
75  // with the exception code as exit code - for example it exits with
76  // 0 for EXCEPTION_ACCESS_VIOLATION and 1 for EXCEPTION_BREAKPOINT
77  // if the application is compiled in debug mode. Thus we use our own
78  // filter which always exits with the exception code for unhandled
79  // exceptions.
80  SetUnhandledExceptionFilter(ExitWithExceptionCode);
81
82# endif
83#endif
84
85  testing::InitGoogleTest(&argc, argv);
86
87  return RUN_ALL_TESTS();
88}
trunk/3rdparty/googletest/googletest/test/gtest_catch_exceptions_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2010 Google Inc.  All Rights Reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9#     * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11#     * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15#     * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31"""Tests Google Test's exception catching behavior.
32
33This script invokes gtest_catch_exceptions_test_ and
34gtest_catch_exceptions_ex_test_ (programs written with
35Google Test) and verifies their output.
36"""
37
38__author__ = 'vladl@google.com (Vlad Losev)'
39
40import os
41
42import gtest_test_utils
43
44# Constants.
45FLAG_PREFIX = '--gtest_'
46LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
47NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0'
48FILTER_FLAG = FLAG_PREFIX + 'filter'
49
50# Path to the gtest_catch_exceptions_ex_test_ binary, compiled with
51# exceptions enabled.
52EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath(
53    'gtest_catch_exceptions_ex_test_')
54
55# Path to the gtest_catch_exceptions_test_ binary, compiled with
56# exceptions disabled.
57EXE_PATH = gtest_test_utils.GetTestExecutablePath(
58    'gtest_catch_exceptions_no_ex_test_')
59
60environ = gtest_test_utils.environ
61SetEnvVar = gtest_test_utils.SetEnvVar
62
63# Tests in this file run a Google-Test-based test program and expect it
64# to terminate prematurely.  Therefore they are incompatible with
65# the premature-exit-file protocol by design.  Unset the
66# premature-exit filepath to prevent Google Test from creating
67# the file.
68SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
69
70TEST_LIST = gtest_test_utils.Subprocess(
71    [EXE_PATH, LIST_TESTS_FLAG], env=environ).output
72
73SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST
74
75if SUPPORTS_SEH_EXCEPTIONS:
76  BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output
77
78EX_BINARY_OUTPUT = gtest_test_utils.Subprocess(
79    [EX_EXE_PATH], env=environ).output
80
81
82# The tests.
83if SUPPORTS_SEH_EXCEPTIONS:
84  # pylint:disable-msg=C6302
85  class CatchSehExceptionsTest(gtest_test_utils.TestCase):
86    """Tests exception-catching behavior."""
87
88
89    def TestSehExceptions(self, test_output):
90      self.assert_('SEH exception with code 0x2a thrown '
91                   'in the test fixture\'s constructor'
92                   in test_output)
93      self.assert_('SEH exception with code 0x2a thrown '
94                   'in the test fixture\'s destructor'
95                   in test_output)
96      self.assert_('SEH exception with code 0x2a thrown in SetUpTestCase()'
97                   in test_output)
98      self.assert_('SEH exception with code 0x2a thrown in TearDownTestCase()'
99                   in test_output)
100      self.assert_('SEH exception with code 0x2a thrown in SetUp()'
101                   in test_output)
102      self.assert_('SEH exception with code 0x2a thrown in TearDown()'
103                   in test_output)
104      self.assert_('SEH exception with code 0x2a thrown in the test body'
105                   in test_output)
106
107    def testCatchesSehExceptionsWithCxxExceptionsEnabled(self):
108      self.TestSehExceptions(EX_BINARY_OUTPUT)
109
110    def testCatchesSehExceptionsWithCxxExceptionsDisabled(self):
111      self.TestSehExceptions(BINARY_OUTPUT)
112
113
114class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
115  """Tests C++ exception-catching behavior.
116
117     Tests in this test case verify that:
118     * C++ exceptions are caught and logged as C++ (not SEH) exceptions
119     * Exception thrown affect the remainder of the test work flow in the
120       expected manner.
121  """
122
123  def testCatchesCxxExceptionsInFixtureConstructor(self):
124    self.assert_('C++ exception with description '
125                 '"Standard C++ exception" thrown '
126                 'in the test fixture\'s constructor'
127                 in EX_BINARY_OUTPUT)
128    self.assert_('unexpected' not in EX_BINARY_OUTPUT,
129                 'This failure belongs in this test only if '
130                 '"CxxExceptionInConstructorTest" (no quotes) '
131                 'appears on the same line as words "called unexpectedly"')
132
133  if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in
134      EX_BINARY_OUTPUT):
135
136    def testCatchesCxxExceptionsInFixtureDestructor(self):
137      self.assert_('C++ exception with description '
138                   '"Standard C++ exception" thrown '
139                   'in the test fixture\'s destructor'
140                   in EX_BINARY_OUTPUT)
141      self.assert_('CxxExceptionInDestructorTest::TearDownTestCase() '
142                   'called as expected.'
143                   in EX_BINARY_OUTPUT)
144
145  def testCatchesCxxExceptionsInSetUpTestCase(self):
146    self.assert_('C++ exception with description "Standard C++ exception"'
147                 ' thrown in SetUpTestCase()'
148                 in EX_BINARY_OUTPUT)
149    self.assert_('CxxExceptionInConstructorTest::TearDownTestCase() '
150                 'called as expected.'
151                 in EX_BINARY_OUTPUT)
152    self.assert_('CxxExceptionInSetUpTestCaseTest constructor '
153                 'called as expected.'
154                 in EX_BINARY_OUTPUT)
155    self.assert_('CxxExceptionInSetUpTestCaseTest destructor '
156                 'called as expected.'
157                 in EX_BINARY_OUTPUT)
158    self.assert_('CxxExceptionInSetUpTestCaseTest::SetUp() '
159                 'called as expected.'
160                 in EX_BINARY_OUTPUT)
161    self.assert_('CxxExceptionInSetUpTestCaseTest::TearDown() '
162                 'called as expected.'
163                 in EX_BINARY_OUTPUT)
164    self.assert_('CxxExceptionInSetUpTestCaseTest test body '
165                 'called as expected.'
166                 in EX_BINARY_OUTPUT)
167
168  def testCatchesCxxExceptionsInTearDownTestCase(self):
169    self.assert_('C++ exception with description "Standard C++ exception"'
170                 ' thrown in TearDownTestCase()'
171                 in EX_BINARY_OUTPUT)
172
173  def testCatchesCxxExceptionsInSetUp(self):
174    self.assert_('C++ exception with description "Standard C++ exception"'
175                 ' thrown in SetUp()'
176                 in EX_BINARY_OUTPUT)
177    self.assert_('CxxExceptionInSetUpTest::TearDownTestCase() '
178                 'called as expected.'
179                 in EX_BINARY_OUTPUT)
180    self.assert_('CxxExceptionInSetUpTest destructor '
181                 'called as expected.'
182                 in EX_BINARY_OUTPUT)
183    self.assert_('CxxExceptionInSetUpTest::TearDown() '
184                 'called as expected.'
185                 in EX_BINARY_OUTPUT)
186    self.assert_('unexpected' not in EX_BINARY_OUTPUT,
187                 'This failure belongs in this test only if '
188                 '"CxxExceptionInSetUpTest" (no quotes) '
189                 'appears on the same line as words "called unexpectedly"')
190
191  def testCatchesCxxExceptionsInTearDown(self):
192    self.assert_('C++ exception with description "Standard C++ exception"'
193                 ' thrown in TearDown()'
194                 in EX_BINARY_OUTPUT)
195    self.assert_('CxxExceptionInTearDownTest::TearDownTestCase() '
196                 'called as expected.'
197                 in EX_BINARY_OUTPUT)
198    self.assert_('CxxExceptionInTearDownTest destructor '
199                 'called as expected.'
200                 in EX_BINARY_OUTPUT)
201
202  def testCatchesCxxExceptionsInTestBody(self):
203    self.assert_('C++ exception with description "Standard C++ exception"'
204                 ' thrown in the test body'
205                 in EX_BINARY_OUTPUT)
206    self.assert_('CxxExceptionInTestBodyTest::TearDownTestCase() '
207                 'called as expected.'
208                 in EX_BINARY_OUTPUT)
209    self.assert_('CxxExceptionInTestBodyTest destructor '
210                 'called as expected.'
211                 in EX_BINARY_OUTPUT)
212    self.assert_('CxxExceptionInTestBodyTest::TearDown() '
213                 'called as expected.'
214                 in EX_BINARY_OUTPUT)
215
216  def testCatchesNonStdCxxExceptions(self):
217    self.assert_('Unknown C++ exception thrown in the test body'
218                 in EX_BINARY_OUTPUT)
219
220  def testUnhandledCxxExceptionsAbortTheProgram(self):
221    # Filters out SEH exception tests on Windows. Unhandled SEH exceptions
222    # cause tests to show pop-up windows there.
223    FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*'
224    # By default, Google Test doesn't catch the exceptions.
225    uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess(
226        [EX_EXE_PATH,
227         NO_CATCH_EXCEPTIONS_FLAG,
228         FITLER_OUT_SEH_TESTS_FLAG],
229        env=environ).output
230
231    self.assert_('Unhandled C++ exception terminating the program'
232                 in uncaught_exceptions_ex_binary_output)
233    self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output)
234
235
236if __name__ == '__main__':
237  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_catch_exceptions_test_.cc
r0r249096
1// Copyright 2010, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: vladl@google.com (Vlad Losev)
31//
32// Tests for Google Test itself. Tests in this file throw C++ or SEH
33// exceptions, and the output is verified by gtest_catch_exceptions_test.py.
34
35#include "gtest/gtest.h"
36
37#include <stdio.h>  // NOLINT
38#include <stdlib.h>  // For exit().
39
40#if GTEST_HAS_SEH
41# include <windows.h>
42#endif
43
44#if GTEST_HAS_EXCEPTIONS
45# include <exception>  // For set_terminate().
46# include <stdexcept>
47#endif
48
49using testing::Test;
50
51#if GTEST_HAS_SEH
52
53class SehExceptionInConstructorTest : public Test {
54 public:
55  SehExceptionInConstructorTest() { RaiseException(42, 0, 0, NULL); }
56};
57
58TEST_F(SehExceptionInConstructorTest, ThrowsExceptionInConstructor) {}
59
60class SehExceptionInDestructorTest : public Test {
61 public:
62  ~SehExceptionInDestructorTest() { RaiseException(42, 0, 0, NULL); }
63};
64
65TEST_F(SehExceptionInDestructorTest, ThrowsExceptionInDestructor) {}
66
67class SehExceptionInSetUpTestCaseTest : public Test {
68 public:
69  static void SetUpTestCase() { RaiseException(42, 0, 0, NULL); }
70};
71
72TEST_F(SehExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) {}
73
74class SehExceptionInTearDownTestCaseTest : public Test {
75 public:
76  static void TearDownTestCase() { RaiseException(42, 0, 0, NULL); }
77};
78
79TEST_F(SehExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {}
80
81class SehExceptionInSetUpTest : public Test {
82 protected:
83  virtual void SetUp() { RaiseException(42, 0, 0, NULL); }
84};
85
86TEST_F(SehExceptionInSetUpTest, ThrowsExceptionInSetUp) {}
87
88class SehExceptionInTearDownTest : public Test {
89 protected:
90  virtual void TearDown() { RaiseException(42, 0, 0, NULL); }
91};
92
93TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
94
95TEST(SehExceptionTest, ThrowsSehException) {
96  RaiseException(42, 0, 0, NULL);
97}
98
99#endif  // GTEST_HAS_SEH
100
101#if GTEST_HAS_EXCEPTIONS
102
103class CxxExceptionInConstructorTest : public Test {
104 public:
105  CxxExceptionInConstructorTest() {
106    // Without this macro VC++ complains about unreachable code at the end of
107    // the constructor.
108    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
109        throw std::runtime_error("Standard C++ exception"));
110  }
111
112  static void TearDownTestCase() {
113    printf("%s",
114           "CxxExceptionInConstructorTest::TearDownTestCase() "
115           "called as expected.\n");
116  }
117
118 protected:
119  ~CxxExceptionInConstructorTest() {
120    ADD_FAILURE() << "CxxExceptionInConstructorTest destructor "
121                  << "called unexpectedly.";
122  }
123
124  virtual void SetUp() {
125    ADD_FAILURE() << "CxxExceptionInConstructorTest::SetUp() "
126                  << "called unexpectedly.";
127  }
128
129  virtual void TearDown() {
130    ADD_FAILURE() << "CxxExceptionInConstructorTest::TearDown() "
131                  << "called unexpectedly.";
132  }
133};
134
135TEST_F(CxxExceptionInConstructorTest, ThrowsExceptionInConstructor) {
136  ADD_FAILURE() << "CxxExceptionInConstructorTest test body "
137                << "called unexpectedly.";
138}
139
140// Exceptions in destructors are not supported in C++11.
141#if !defined(__GXX_EXPERIMENTAL_CXX0X__) &&  __cplusplus < 201103L
142class CxxExceptionInDestructorTest : public Test {
143 public:
144  static void TearDownTestCase() {
145    printf("%s",
146           "CxxExceptionInDestructorTest::TearDownTestCase() "
147           "called as expected.\n");
148  }
149
150 protected:
151  ~CxxExceptionInDestructorTest() {
152    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
153        throw std::runtime_error("Standard C++ exception"));
154  }
155};
156
157TEST_F(CxxExceptionInDestructorTest, ThrowsExceptionInDestructor) {}
158#endif  // C++11 mode
159
160class CxxExceptionInSetUpTestCaseTest : public Test {
161 public:
162  CxxExceptionInSetUpTestCaseTest() {
163    printf("%s",
164           "CxxExceptionInSetUpTestCaseTest constructor "
165           "called as expected.\n");
166  }
167
168  static void SetUpTestCase() {
169    throw std::runtime_error("Standard C++ exception");
170  }
171
172  static void TearDownTestCase() {
173    printf("%s",
174           "CxxExceptionInSetUpTestCaseTest::TearDownTestCase() "
175           "called as expected.\n");
176  }
177
178 protected:
179  ~CxxExceptionInSetUpTestCaseTest() {
180    printf("%s",
181           "CxxExceptionInSetUpTestCaseTest destructor "
182           "called as expected.\n");
183  }
184
185  virtual void SetUp() {
186    printf("%s",
187           "CxxExceptionInSetUpTestCaseTest::SetUp() "
188           "called as expected.\n");
189  }
190
191  virtual void TearDown() {
192    printf("%s",
193           "CxxExceptionInSetUpTestCaseTest::TearDown() "
194           "called as expected.\n");
195  }
196};
197
198TEST_F(CxxExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) {
199  printf("%s",
200         "CxxExceptionInSetUpTestCaseTest test body "
201         "called as expected.\n");
202}
203
204class CxxExceptionInTearDownTestCaseTest : public Test {
205 public:
206  static void TearDownTestCase() {
207    throw std::runtime_error("Standard C++ exception");
208  }
209};
210
211TEST_F(CxxExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {}
212
213class CxxExceptionInSetUpTest : public Test {
214 public:
215  static void TearDownTestCase() {
216    printf("%s",
217           "CxxExceptionInSetUpTest::TearDownTestCase() "
218           "called as expected.\n");
219  }
220
221 protected:
222  ~CxxExceptionInSetUpTest() {
223    printf("%s",
224           "CxxExceptionInSetUpTest destructor "
225           "called as expected.\n");
226  }
227
228  virtual void SetUp() { throw std::runtime_error("Standard C++ exception"); }
229
230  virtual void TearDown() {
231    printf("%s",
232           "CxxExceptionInSetUpTest::TearDown() "
233           "called as expected.\n");
234  }
235};
236
237TEST_F(CxxExceptionInSetUpTest, ThrowsExceptionInSetUp) {
238  ADD_FAILURE() << "CxxExceptionInSetUpTest test body "
239                << "called unexpectedly.";
240}
241
242class CxxExceptionInTearDownTest : public Test {
243 public:
244  static void TearDownTestCase() {
245    printf("%s",
246           "CxxExceptionInTearDownTest::TearDownTestCase() "
247           "called as expected.\n");
248  }
249
250 protected:
251  ~CxxExceptionInTearDownTest() {
252    printf("%s",
253           "CxxExceptionInTearDownTest destructor "
254           "called as expected.\n");
255  }
256
257  virtual void TearDown() {
258    throw std::runtime_error("Standard C++ exception");
259  }
260};
261
262TEST_F(CxxExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
263
264class CxxExceptionInTestBodyTest : public Test {
265 public:
266  static void TearDownTestCase() {
267    printf("%s",
268           "CxxExceptionInTestBodyTest::TearDownTestCase() "
269           "called as expected.\n");
270  }
271
272 protected:
273  ~CxxExceptionInTestBodyTest() {
274    printf("%s",
275           "CxxExceptionInTestBodyTest destructor "
276           "called as expected.\n");
277  }
278
279  virtual void TearDown() {
280    printf("%s",
281           "CxxExceptionInTestBodyTest::TearDown() "
282           "called as expected.\n");
283  }
284};
285
286TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
287  throw std::runtime_error("Standard C++ exception");
288}
289
290TEST(CxxExceptionTest, ThrowsNonStdCxxException) {
291  throw "C-string";
292}
293
294// This terminate handler aborts the program using exit() rather than abort().
295// This avoids showing pop-ups on Windows systems and core dumps on Unix-like
296// ones.
297void TerminateHandler() {
298  fprintf(stderr, "%s\n", "Unhandled C++ exception terminating the program.");
299  fflush(NULL);
300  exit(3);
301}
302
303#endif  // GTEST_HAS_EXCEPTIONS
304
305int main(int argc, char** argv) {
306#if GTEST_HAS_EXCEPTIONS
307  std::set_terminate(&TerminateHandler);
308#endif
309  testing::InitGoogleTest(&argc, argv);
310  return RUN_ALL_TESTS();
311}
trunk/3rdparty/googletest/googletest/test/gtest_color_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Verifies that Google Test correctly determines whether to use colors."""
33
34__author__ = 'wan@google.com (Zhanyong Wan)'
35
36import os
37import gtest_test_utils
38
39
40IS_WINDOWS = os.name = 'nt'
41
42COLOR_ENV_VAR = 'GTEST_COLOR'
43COLOR_FLAG = 'gtest_color'
44COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_')
45
46
47def SetEnvVar(env_var, value):
48  """Sets the env variable to 'value'; unsets it when 'value' is None."""
49
50  if value is not None:
51    os.environ[env_var] = value
52  elif env_var in os.environ:
53    del os.environ[env_var]
54
55
56def UsesColor(term, color_env_var, color_flag):
57  """Runs gtest_color_test_ and returns its exit code."""
58
59  SetEnvVar('TERM', term)
60  SetEnvVar(COLOR_ENV_VAR, color_env_var)
61
62  if color_flag is None:
63    args = []
64  else:
65    args = ['--%s=%s' % (COLOR_FLAG, color_flag)]
66  p = gtest_test_utils.Subprocess([COMMAND] + args)
67  return not p.exited or p.exit_code
68
69
70class GTestColorTest(gtest_test_utils.TestCase):
71  def testNoEnvVarNoFlag(self):
72    """Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
73
74    if not IS_WINDOWS:
75      self.assert_(not UsesColor('dumb', None, None))
76      self.assert_(not UsesColor('emacs', None, None))
77      self.assert_(not UsesColor('xterm-mono', None, None))
78      self.assert_(not UsesColor('unknown', None, None))
79      self.assert_(not UsesColor(None, None, None))
80    self.assert_(UsesColor('linux', None, None))
81    self.assert_(UsesColor('cygwin', None, None))
82    self.assert_(UsesColor('xterm', None, None))
83    self.assert_(UsesColor('xterm-color', None, None))
84    self.assert_(UsesColor('xterm-256color', None, None))
85
86  def testFlagOnly(self):
87    """Tests the case when there's --gtest_color but not GTEST_COLOR."""
88
89    self.assert_(not UsesColor('dumb', None, 'no'))
90    self.assert_(not UsesColor('xterm-color', None, 'no'))
91    if not IS_WINDOWS:
92      self.assert_(not UsesColor('emacs', None, 'auto'))
93    self.assert_(UsesColor('xterm', None, 'auto'))
94    self.assert_(UsesColor('dumb', None, 'yes'))
95    self.assert_(UsesColor('xterm', None, 'yes'))
96
97  def testEnvVarOnly(self):
98    """Tests the case when there's GTEST_COLOR but not --gtest_color."""
99
100    self.assert_(not UsesColor('dumb', 'no', None))
101    self.assert_(not UsesColor('xterm-color', 'no', None))
102    if not IS_WINDOWS:
103      self.assert_(not UsesColor('dumb', 'auto', None))
104    self.assert_(UsesColor('xterm-color', 'auto', None))
105    self.assert_(UsesColor('dumb', 'yes', None))
106    self.assert_(UsesColor('xterm-color', 'yes', None))
107
108  def testEnvVarAndFlag(self):
109    """Tests the case when there are both GTEST_COLOR and --gtest_color."""
110
111    self.assert_(not UsesColor('xterm-color', 'no', 'no'))
112    self.assert_(UsesColor('dumb', 'no', 'yes'))
113    self.assert_(UsesColor('xterm-color', 'no', 'auto'))
114
115  def testAliasesOfYesAndNo(self):
116    """Tests using aliases in specifying --gtest_color."""
117
118    self.assert_(UsesColor('dumb', None, 'true'))
119    self.assert_(UsesColor('dumb', None, 'YES'))
120    self.assert_(UsesColor('dumb', None, 'T'))
121    self.assert_(UsesColor('dumb', None, '1'))
122
123    self.assert_(not UsesColor('xterm', None, 'f'))
124    self.assert_(not UsesColor('xterm', None, 'false'))
125    self.assert_(not UsesColor('xterm', None, '0'))
126    self.assert_(not UsesColor('xterm', None, 'unknown'))
127
128
129if __name__ == '__main__':
130  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_color_test_.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// A helper program for testing how Google Test determines whether to use
33// colors in the output.  It prints "YES" and returns 1 if Google Test
34// decides to use colors, and prints "NO" and returns 0 otherwise.
35
36#include <stdio.h>
37
38#include "gtest/gtest.h"
39
40// Indicates that this translation unit is part of Google Test's
41// implementation.  It must come before gtest-internal-inl.h is
42// included, or there will be a compiler error.  This trick is to
43// prevent a user from accidentally including gtest-internal-inl.h in
44// his code.
45#define GTEST_IMPLEMENTATION_ 1
46#include "src/gtest-internal-inl.h"
47#undef GTEST_IMPLEMENTATION_
48
49using testing::internal::ShouldUseColor;
50
51// The purpose of this is to ensure that the UnitTest singleton is
52// created before main() is entered, and thus that ShouldUseColor()
53// works the same way as in a real Google-Test-based test.  We don't actual
54// run the TEST itself.
55TEST(GTestColorTest, Dummy) {
56}
57
58int main(int argc, char** argv) {
59  testing::InitGoogleTest(&argc, argv);
60
61  if (ShouldUseColor(true)) {
62    // Google Test decides to use colors in the output (assuming it
63    // goes to a TTY).
64    printf("YES\n");
65    return 1;
66  } else {
67    // Google Test decides not to use colors in the output.
68    printf("NO\n");
69    return 0;
70  }
71}
trunk/3rdparty/googletest/googletest/test/gtest_env_var_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Verifies that Google Test correctly parses environment variables."""
33
34__author__ = 'wan@google.com (Zhanyong Wan)'
35
36import os
37import gtest_test_utils
38
39
40IS_WINDOWS = os.name == 'nt'
41IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
42
43COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_')
44
45environ = os.environ.copy()
46
47
48def AssertEq(expected, actual):
49  if expected != actual:
50    print 'Expected: %s' % (expected,)
51    print '  Actual: %s' % (actual,)
52    raise AssertionError
53
54
55def SetEnvVar(env_var, value):
56  """Sets the env variable to 'value'; unsets it when 'value' is None."""
57
58  if value is not None:
59    environ[env_var] = value
60  elif env_var in environ:
61    del environ[env_var]
62
63
64def GetFlag(flag):
65  """Runs gtest_env_var_test_ and returns its output."""
66
67  args = [COMMAND]
68  if flag is not None:
69    args += [flag]
70  return gtest_test_utils.Subprocess(args, env=environ).output
71
72
73def TestFlag(flag, test_val, default_val):
74  """Verifies that the given flag is affected by the corresponding env var."""
75
76  env_var = 'GTEST_' + flag.upper()
77  SetEnvVar(env_var, test_val)
78  AssertEq(test_val, GetFlag(flag))
79  SetEnvVar(env_var, None)
80  AssertEq(default_val, GetFlag(flag))
81
82
83class GTestEnvVarTest(gtest_test_utils.TestCase):
84  def testEnvVarAffectsFlag(self):
85    """Tests that environment variable should affect the corresponding flag."""
86
87    TestFlag('break_on_failure', '1', '0')
88    TestFlag('color', 'yes', 'auto')
89    TestFlag('filter', 'FooTest.Bar', '*')
90    TestFlag('output', 'xml:tmp/foo.xml', '')
91    TestFlag('print_time', '0', '1')
92    TestFlag('repeat', '999', '1')
93    TestFlag('throw_on_failure', '1', '0')
94    TestFlag('death_test_style', 'threadsafe', 'fast')
95    TestFlag('catch_exceptions', '0', '1')
96
97    if IS_LINUX:
98      TestFlag('death_test_use_fork', '1', '0')
99      TestFlag('stack_trace_depth', '0', '100')
100
101
102if __name__ == '__main__':
103  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_env_var_test_.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// A helper program for testing that Google Test parses the environment
33// variables correctly.
34
35#include "gtest/gtest.h"
36
37#include <iostream>
38
39#define GTEST_IMPLEMENTATION_ 1
40#include "src/gtest-internal-inl.h"
41#undef GTEST_IMPLEMENTATION_
42
43using ::std::cout;
44
45namespace testing {
46
47// The purpose of this is to make the test more realistic by ensuring
48// that the UnitTest singleton is created before main() is entered.
49// We don't actual run the TEST itself.
50TEST(GTestEnvVarTest, Dummy) {
51}
52
53void PrintFlag(const char* flag) {
54  if (strcmp(flag, "break_on_failure") == 0) {
55    cout << GTEST_FLAG(break_on_failure);
56    return;
57  }
58
59  if (strcmp(flag, "catch_exceptions") == 0) {
60    cout << GTEST_FLAG(catch_exceptions);
61    return;
62  }
63
64  if (strcmp(flag, "color") == 0) {
65    cout << GTEST_FLAG(color);
66    return;
67  }
68
69  if (strcmp(flag, "death_test_style") == 0) {
70    cout << GTEST_FLAG(death_test_style);
71    return;
72  }
73
74  if (strcmp(flag, "death_test_use_fork") == 0) {
75    cout << GTEST_FLAG(death_test_use_fork);
76    return;
77  }
78
79  if (strcmp(flag, "filter") == 0) {
80    cout << GTEST_FLAG(filter);
81    return;
82  }
83
84  if (strcmp(flag, "output") == 0) {
85    cout << GTEST_FLAG(output);
86    return;
87  }
88
89  if (strcmp(flag, "print_time") == 0) {
90    cout << GTEST_FLAG(print_time);
91    return;
92  }
93
94  if (strcmp(flag, "repeat") == 0) {
95    cout << GTEST_FLAG(repeat);
96    return;
97  }
98
99  if (strcmp(flag, "stack_trace_depth") == 0) {
100    cout << GTEST_FLAG(stack_trace_depth);
101    return;
102  }
103
104  if (strcmp(flag, "throw_on_failure") == 0) {
105    cout << GTEST_FLAG(throw_on_failure);
106    return;
107  }
108
109  cout << "Invalid flag name " << flag
110       << ".  Valid names are break_on_failure, color, filter, etc.\n";
111  exit(1);
112}
113
114}  // namespace testing
115
116int main(int argc, char** argv) {
117  testing::InitGoogleTest(&argc, argv);
118
119  if (argc != 2) {
120    cout << "Usage: gtest_env_var_test_ NAME_OF_FLAG\n";
121    return 1;
122  }
123
124  testing::PrintFlag(argv[1]);
125  return 0;
126}
trunk/3rdparty/googletest/googletest/test/gtest_environment_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests using global test environments.
33
34#include <stdlib.h>
35#include <stdio.h>
36#include "gtest/gtest.h"
37
38#define GTEST_IMPLEMENTATION_ 1  // Required for the next #include.
39#include "src/gtest-internal-inl.h"
40#undef GTEST_IMPLEMENTATION_
41
42namespace testing {
43GTEST_DECLARE_string_(filter);
44}
45
46namespace {
47
48enum FailureType {
49  NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE
50};
51
52// For testing using global test environments.
53class MyEnvironment : public testing::Environment {
54 public:
55  MyEnvironment() { Reset(); }
56
57  // Depending on the value of failure_in_set_up_, SetUp() will
58  // generate a non-fatal failure, generate a fatal failure, or
59  // succeed.
60  virtual void SetUp() {
61    set_up_was_run_ = true;
62
63    switch (failure_in_set_up_) {
64      case NON_FATAL_FAILURE:
65        ADD_FAILURE() << "Expected non-fatal failure in global set-up.";
66        break;
67      case FATAL_FAILURE:
68        FAIL() << "Expected fatal failure in global set-up.";
69        break;
70      default:
71        break;
72    }
73  }
74
75  // Generates a non-fatal failure.
76  virtual void TearDown() {
77    tear_down_was_run_ = true;
78    ADD_FAILURE() << "Expected non-fatal failure in global tear-down.";
79  }
80
81  // Resets the state of the environment s.t. it can be reused.
82  void Reset() {
83    failure_in_set_up_ = NO_FAILURE;
84    set_up_was_run_ = false;
85    tear_down_was_run_ = false;
86  }
87
88  // We call this function to set the type of failure SetUp() should
89  // generate.
90  void set_failure_in_set_up(FailureType type) {
91    failure_in_set_up_ = type;
92  }
93
94  // Was SetUp() run?
95  bool set_up_was_run() const { return set_up_was_run_; }
96
97  // Was TearDown() run?
98  bool tear_down_was_run() const { return tear_down_was_run_; }
99
100 private:
101  FailureType failure_in_set_up_;
102  bool set_up_was_run_;
103  bool tear_down_was_run_;
104};
105
106// Was the TEST run?
107bool test_was_run;
108
109// The sole purpose of this TEST is to enable us to check whether it
110// was run.
111TEST(FooTest, Bar) {
112  test_was_run = true;
113}
114
115// Prints the message and aborts the program if condition is false.
116void Check(bool condition, const char* msg) {
117  if (!condition) {
118    printf("FAILED: %s\n", msg);
119    testing::internal::posix::Abort();
120  }
121}
122
123// Runs the tests.  Return true iff successful.
124//
125// The 'failure' parameter specifies the type of failure that should
126// be generated by the global set-up.
127int RunAllTests(MyEnvironment* env, FailureType failure) {
128  env->Reset();
129  env->set_failure_in_set_up(failure);
130  test_was_run = false;
131  testing::internal::GetUnitTestImpl()->ClearAdHocTestResult();
132  return RUN_ALL_TESTS();
133}
134
135}  // namespace
136
137int main(int argc, char **argv) {
138  testing::InitGoogleTest(&argc, argv);
139
140  // Registers a global test environment, and verifies that the
141  // registration function returns its argument.
142  MyEnvironment* const env = new MyEnvironment;
143  Check(testing::AddGlobalTestEnvironment(env) == env,
144        "AddGlobalTestEnvironment() should return its argument.");
145
146  // Verifies that RUN_ALL_TESTS() runs the tests when the global
147  // set-up is successful.
148  Check(RunAllTests(env, NO_FAILURE) != 0,
149        "RUN_ALL_TESTS() should return non-zero, as the global tear-down "
150        "should generate a failure.");
151  Check(test_was_run,
152        "The tests should run, as the global set-up should generate no "
153        "failure");
154  Check(env->tear_down_was_run(),
155        "The global tear-down should run, as the global set-up was run.");
156
157  // Verifies that RUN_ALL_TESTS() runs the tests when the global
158  // set-up generates no fatal failure.
159  Check(RunAllTests(env, NON_FATAL_FAILURE) != 0,
160        "RUN_ALL_TESTS() should return non-zero, as both the global set-up "
161        "and the global tear-down should generate a non-fatal failure.");
162  Check(test_was_run,
163        "The tests should run, as the global set-up should generate no "
164        "fatal failure.");
165  Check(env->tear_down_was_run(),
166        "The global tear-down should run, as the global set-up was run.");
167
168  // Verifies that RUN_ALL_TESTS() runs no test when the global set-up
169  // generates a fatal failure.
170  Check(RunAllTests(env, FATAL_FAILURE) != 0,
171        "RUN_ALL_TESTS() should return non-zero, as the global set-up "
172        "should generate a fatal failure.");
173  Check(!test_was_run,
174        "The tests should not run, as the global set-up should generate "
175        "a fatal failure.");
176  Check(env->tear_down_was_run(),
177        "The global tear-down should run, as the global set-up was run.");
178
179  // Verifies that RUN_ALL_TESTS() doesn't do global set-up or
180  // tear-down when there is no test to run.
181  testing::GTEST_FLAG(filter) = "-*";
182  Check(RunAllTests(env, NO_FAILURE) == 0,
183        "RUN_ALL_TESTS() should return zero, as there is no test to run.");
184  Check(!env->set_up_was_run(),
185        "The global set-up should not run, as there is no test to run.");
186  Check(!env->tear_down_was_run(),
187        "The global tear-down should not run, "
188        "as the global set-up was not run.");
189
190  printf("PASS\n");
191  return 0;
192}
trunk/3rdparty/googletest/googletest/test/gtest_filter_unittest.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2005 Google Inc. All Rights Reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9#     * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11#     * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15#     * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31"""Unit test for Google Test test filters.
32
33A user can specify which test(s) in a Google Test program to run via either
34the GTEST_FILTER environment variable or the --gtest_filter flag.
35This script tests such functionality by invoking
36gtest_filter_unittest_ (a program written with Google Test) with different
37environments and command line flags.
38
39Note that test sharding may also influence which tests are filtered. Therefore,
40we test that here also.
41"""
42
43__author__ = 'wan@google.com (Zhanyong Wan)'
44
45import os
46import re
47import sets
48import sys
49
50import gtest_test_utils
51
52# Constants.
53
54# Checks if this platform can pass empty environment variables to child
55# processes.  We set an env variable to an empty string and invoke a python
56# script in a subprocess to print whether the variable is STILL in
57# os.environ.  We then use 'eval' to parse the child's output so that an
58# exception is thrown if the input is anything other than 'True' nor 'False'.
59os.environ['EMPTY_VAR'] = ''
60child = gtest_test_utils.Subprocess(
61    [sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ'])
62CAN_PASS_EMPTY_ENV = eval(child.output)
63
64
65# Check if this platform can unset environment variables in child processes.
66# We set an env variable to a non-empty string, unset it, and invoke
67# a python script in a subprocess to print whether the variable
68# is NO LONGER in os.environ.
69# We use 'eval' to parse the child's output so that an exception
70# is thrown if the input is neither 'True' nor 'False'.
71os.environ['UNSET_VAR'] = 'X'
72del os.environ['UNSET_VAR']
73child = gtest_test_utils.Subprocess(
74    [sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ'])
75CAN_UNSET_ENV = eval(child.output)
76
77
78# Checks if we should test with an empty filter. This doesn't
79# make sense on platforms that cannot pass empty env variables (Win32)
80# and on platforms that cannot unset variables (since we cannot tell
81# the difference between "" and NULL -- Borland and Solaris < 5.10)
82CAN_TEST_EMPTY_FILTER = (CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV)
83
84
85# The environment variable for specifying the test filters.
86FILTER_ENV_VAR = 'GTEST_FILTER'
87
88# The environment variables for test sharding.
89TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
90SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
91SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'
92
93# The command line flag for specifying the test filters.
94FILTER_FLAG = 'gtest_filter'
95
96# The command line flag for including disabled tests.
97ALSO_RUN_DISABED_TESTS_FLAG = 'gtest_also_run_disabled_tests'
98
99# Command to run the gtest_filter_unittest_ program.
100COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_filter_unittest_')
101
102# Regex for determining whether parameterized tests are enabled in the binary.
103PARAM_TEST_REGEX = re.compile(r'/ParamTest')
104
105# Regex for parsing test case names from Google Test's output.
106TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ tests? from (\w+(/\w+)?)')
107
108# Regex for parsing test names from Google Test's output.
109TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+(/\w+)?)')
110
111# The command line flag to tell Google Test to output the list of tests it
112# will run.
113LIST_TESTS_FLAG = '--gtest_list_tests'
114
115# Indicates whether Google Test supports death tests.
116SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess(
117    [COMMAND, LIST_TESTS_FLAG]).output
118
119# Full names of all tests in gtest_filter_unittests_.
120PARAM_TESTS = [
121    'SeqP/ParamTest.TestX/0',
122    'SeqP/ParamTest.TestX/1',
123    'SeqP/ParamTest.TestY/0',
124    'SeqP/ParamTest.TestY/1',
125    'SeqQ/ParamTest.TestX/0',
126    'SeqQ/ParamTest.TestX/1',
127    'SeqQ/ParamTest.TestY/0',
128    'SeqQ/ParamTest.TestY/1',
129    ]
130
131DISABLED_TESTS = [
132    'BarTest.DISABLED_TestFour',
133    'BarTest.DISABLED_TestFive',
134    'BazTest.DISABLED_TestC',
135    'DISABLED_FoobarTest.Test1',
136    'DISABLED_FoobarTest.DISABLED_Test2',
137    'DISABLED_FoobarbazTest.TestA',
138    ]
139
140if SUPPORTS_DEATH_TESTS:
141  DEATH_TESTS = [
142    'HasDeathTest.Test1',
143    'HasDeathTest.Test2',
144    ]
145else:
146  DEATH_TESTS = []
147
148# All the non-disabled tests.
149ACTIVE_TESTS = [
150    'FooTest.Abc',
151    'FooTest.Xyz',
152
153    'BarTest.TestOne',
154    'BarTest.TestTwo',
155    'BarTest.TestThree',
156
157    'BazTest.TestOne',
158    'BazTest.TestA',
159    'BazTest.TestB',
160    ] + DEATH_TESTS + PARAM_TESTS
161
162param_tests_present = None
163
164# Utilities.
165
166environ = os.environ.copy()
167
168
169def SetEnvVar(env_var, value):
170  """Sets the env variable to 'value'; unsets it when 'value' is None."""
171
172  if value is not None:
173    environ[env_var] = value
174  elif env_var in environ:
175    del environ[env_var]
176
177
178def RunAndReturnOutput(args = None):
179  """Runs the test program and returns its output."""
180
181  return gtest_test_utils.Subprocess([COMMAND] + (args or []),
182                                     env=environ).output
183
184
185def RunAndExtractTestList(args = None):
186  """Runs the test program and returns its exit code and a list of tests run."""
187
188  p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ)
189  tests_run = []
190  test_case = ''
191  test = ''
192  for line in p.output.split('\n'):
193    match = TEST_CASE_REGEX.match(line)
194    if match is not None:
195      test_case = match.group(1)
196    else:
197      match = TEST_REGEX.match(line)
198      if match is not None:
199        test = match.group(1)
200        tests_run.append(test_case + '.' + test)
201  return (tests_run, p.exit_code)
202
203
204def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs):
205  """Runs the given function and arguments in a modified environment."""
206  try:
207    original_env = environ.copy()
208    environ.update(extra_env)
209    return function(*args, **kwargs)
210  finally:
211    environ.clear()
212    environ.update(original_env)
213
214
215def RunWithSharding(total_shards, shard_index, command):
216  """Runs a test program shard and returns exit code and a list of tests run."""
217
218  extra_env = {SHARD_INDEX_ENV_VAR: str(shard_index),
219               TOTAL_SHARDS_ENV_VAR: str(total_shards)}
220  return InvokeWithModifiedEnv(extra_env, RunAndExtractTestList, command)
221
222# The unit test.
223
224
225class GTestFilterUnitTest(gtest_test_utils.TestCase):
226  """Tests the env variable or the command line flag to filter tests."""
227
228  # Utilities.
229
230  def AssertSetEqual(self, lhs, rhs):
231    """Asserts that two sets are equal."""
232
233    for elem in lhs:
234      self.assert_(elem in rhs, '%s in %s' % (elem, rhs))
235
236    for elem in rhs:
237      self.assert_(elem in lhs, '%s in %s' % (elem, lhs))
238
239  def AssertPartitionIsValid(self, set_var, list_of_sets):
240    """Asserts that list_of_sets is a valid partition of set_var."""
241
242    full_partition = []
243    for slice_var in list_of_sets:
244      full_partition.extend(slice_var)
245    self.assertEqual(len(set_var), len(full_partition))
246    self.assertEqual(sets.Set(set_var), sets.Set(full_partition))
247
248  def AdjustForParameterizedTests(self, tests_to_run):
249    """Adjust tests_to_run in case value parameterized tests are disabled."""
250
251    global param_tests_present
252    if not param_tests_present:
253      return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS))
254    else:
255      return tests_to_run
256
257  def RunAndVerify(self, gtest_filter, tests_to_run):
258    """Checks that the binary runs correct set of tests for a given filter."""
259
260    tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
261
262    # First, tests using the environment variable.
263
264    # Windows removes empty variables from the environment when passing it
265    # to a new process.  This means it is impossible to pass an empty filter
266    # into a process using the environment variable.  However, we can still
267    # test the case when the variable is not supplied (i.e., gtest_filter is
268    # None).
269    # pylint: disable-msg=C6403
270    if CAN_TEST_EMPTY_FILTER or gtest_filter != '':
271      SetEnvVar(FILTER_ENV_VAR, gtest_filter)
272      tests_run = RunAndExtractTestList()[0]
273      SetEnvVar(FILTER_ENV_VAR, None)
274      self.AssertSetEqual(tests_run, tests_to_run)
275    # pylint: enable-msg=C6403
276
277    # Next, tests using the command line flag.
278
279    if gtest_filter is None:
280      args = []
281    else:
282      args = ['--%s=%s' % (FILTER_FLAG, gtest_filter)]
283
284    tests_run = RunAndExtractTestList(args)[0]
285    self.AssertSetEqual(tests_run, tests_to_run)
286
287  def RunAndVerifyWithSharding(self, gtest_filter, total_shards, tests_to_run,
288                               args=None, check_exit_0=False):
289    """Checks that binary runs correct tests for the given filter and shard.
290
291    Runs all shards of gtest_filter_unittest_ with the given filter, and
292    verifies that the right set of tests were run. The union of tests run
293    on each shard should be identical to tests_to_run, without duplicates.
294
295    Args:
296      gtest_filter: A filter to apply to the tests.
297      total_shards: A total number of shards to split test run into.
298      tests_to_run: A set of tests expected to run.
299      args   :      Arguments to pass to the to the test binary.
300      check_exit_0: When set to a true value, make sure that all shards
301                    return 0.
302    """
303
304    tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
305
306    # Windows removes empty variables from the environment when passing it
307    # to a new process.  This means it is impossible to pass an empty filter
308    # into a process using the environment variable.  However, we can still
309    # test the case when the variable is not supplied (i.e., gtest_filter is
310    # None).
311    # pylint: disable-msg=C6403
312    if CAN_TEST_EMPTY_FILTER or gtest_filter != '':
313      SetEnvVar(FILTER_ENV_VAR, gtest_filter)
314      partition = []
315      for i in range(0, total_shards):
316        (tests_run, exit_code) = RunWithSharding(total_shards, i, args)
317        if check_exit_0:
318          self.assertEqual(0, exit_code)
319        partition.append(tests_run)
320
321      self.AssertPartitionIsValid(tests_to_run, partition)
322      SetEnvVar(FILTER_ENV_VAR, None)
323    # pylint: enable-msg=C6403
324
325  def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run):
326    """Checks that the binary runs correct set of tests for the given filter.
327
328    Runs gtest_filter_unittest_ with the given filter, and enables
329    disabled tests. Verifies that the right set of tests were run.
330
331    Args:
332      gtest_filter: A filter to apply to the tests.
333      tests_to_run: A set of tests expected to run.
334    """
335
336    tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
337
338    # Construct the command line.
339    args = ['--%s' % ALSO_RUN_DISABED_TESTS_FLAG]
340    if gtest_filter is not None:
341      args.append('--%s=%s' % (FILTER_FLAG, gtest_filter))
342
343    tests_run = RunAndExtractTestList(args)[0]
344    self.AssertSetEqual(tests_run, tests_to_run)
345
346  def setUp(self):
347    """Sets up test case.
348
349    Determines whether value-parameterized tests are enabled in the binary and
350    sets the flags accordingly.
351    """
352
353    global param_tests_present
354    if param_tests_present is None:
355      param_tests_present = PARAM_TEST_REGEX.search(
356          RunAndReturnOutput()) is not None
357
358  def testDefaultBehavior(self):
359    """Tests the behavior of not specifying the filter."""
360
361    self.RunAndVerify(None, ACTIVE_TESTS)
362
363  def testDefaultBehaviorWithShards(self):
364    """Tests the behavior without the filter, with sharding enabled."""
365
366    self.RunAndVerifyWithSharding(None, 1, ACTIVE_TESTS)
367    self.RunAndVerifyWithSharding(None, 2, ACTIVE_TESTS)
368    self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) - 1, ACTIVE_TESTS)
369    self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS), ACTIVE_TESTS)
370    self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) + 1, ACTIVE_TESTS)
371
372  def testEmptyFilter(self):
373    """Tests an empty filter."""
374
375    self.RunAndVerify('', [])
376    self.RunAndVerifyWithSharding('', 1, [])
377    self.RunAndVerifyWithSharding('', 2, [])
378
379  def testBadFilter(self):
380    """Tests a filter that matches nothing."""
381
382    self.RunAndVerify('BadFilter', [])
383    self.RunAndVerifyAllowingDisabled('BadFilter', [])
384
385  def testFullName(self):
386    """Tests filtering by full name."""
387
388    self.RunAndVerify('FooTest.Xyz', ['FooTest.Xyz'])
389    self.RunAndVerifyAllowingDisabled('FooTest.Xyz', ['FooTest.Xyz'])
390    self.RunAndVerifyWithSharding('FooTest.Xyz', 5, ['FooTest.Xyz'])
391
392  def testUniversalFilters(self):
393    """Tests filters that match everything."""
394
395    self.RunAndVerify('*', ACTIVE_TESTS)
396    self.RunAndVerify('*.*', ACTIVE_TESTS)
397    self.RunAndVerifyWithSharding('*.*', len(ACTIVE_TESTS) - 3, ACTIVE_TESTS)
398    self.RunAndVerifyAllowingDisabled('*', ACTIVE_TESTS + DISABLED_TESTS)
399    self.RunAndVerifyAllowingDisabled('*.*', ACTIVE_TESTS + DISABLED_TESTS)
400
401  def testFilterByTestCase(self):
402    """Tests filtering by test case name."""
403
404    self.RunAndVerify('FooTest.*', ['FooTest.Abc', 'FooTest.Xyz'])
405
406    BAZ_TESTS = ['BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB']
407    self.RunAndVerify('BazTest.*', BAZ_TESTS)
408    self.RunAndVerifyAllowingDisabled('BazTest.*',
409                                      BAZ_TESTS + ['BazTest.DISABLED_TestC'])
410
411  def testFilterByTest(self):
412    """Tests filtering by test name."""
413
414    self.RunAndVerify('*.TestOne', ['BarTest.TestOne', 'BazTest.TestOne'])
415
416  def testFilterDisabledTests(self):
417    """Select only the disabled tests to run."""
418
419    self.RunAndVerify('DISABLED_FoobarTest.Test1', [])
420    self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1',
421                                      ['DISABLED_FoobarTest.Test1'])
422
423    self.RunAndVerify('*DISABLED_*', [])
424    self.RunAndVerifyAllowingDisabled('*DISABLED_*', DISABLED_TESTS)
425
426    self.RunAndVerify('*.DISABLED_*', [])
427    self.RunAndVerifyAllowingDisabled('*.DISABLED_*', [
428        'BarTest.DISABLED_TestFour',
429        'BarTest.DISABLED_TestFive',
430        'BazTest.DISABLED_TestC',
431        'DISABLED_FoobarTest.DISABLED_Test2',
432        ])
433
434    self.RunAndVerify('DISABLED_*', [])
435    self.RunAndVerifyAllowingDisabled('DISABLED_*', [
436        'DISABLED_FoobarTest.Test1',
437        'DISABLED_FoobarTest.DISABLED_Test2',
438        'DISABLED_FoobarbazTest.TestA',
439        ])
440
441  def testWildcardInTestCaseName(self):
442    """Tests using wildcard in the test case name."""
443
444    self.RunAndVerify('*a*.*', [
445        'BarTest.TestOne',
446        'BarTest.TestTwo',
447        'BarTest.TestThree',
448
449        'BazTest.TestOne',
450        'BazTest.TestA',
451        'BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS)
452
453  def testWildcardInTestName(self):
454    """Tests using wildcard in the test name."""
455
456    self.RunAndVerify('*.*A*', ['FooTest.Abc', 'BazTest.TestA'])
457
458  def testFilterWithoutDot(self):
459    """Tests a filter that has no '.' in it."""
460
461    self.RunAndVerify('*z*', [
462        'FooTest.Xyz',
463
464        'BazTest.TestOne',
465        'BazTest.TestA',
466        'BazTest.TestB',
467        ])
468
469  def testTwoPatterns(self):
470    """Tests filters that consist of two patterns."""
471
472    self.RunAndVerify('Foo*.*:*A*', [
473        'FooTest.Abc',
474        'FooTest.Xyz',
475
476        'BazTest.TestA',
477        ])
478
479    # An empty pattern + a non-empty one
480    self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA'])
481
482  def testThreePatterns(self):
483    """Tests filters that consist of three patterns."""
484
485    self.RunAndVerify('*oo*:*A*:*One', [
486        'FooTest.Abc',
487        'FooTest.Xyz',
488
489        'BarTest.TestOne',
490
491        'BazTest.TestOne',
492        'BazTest.TestA',
493        ])
494
495    # The 2nd pattern is empty.
496    self.RunAndVerify('*oo*::*One', [
497        'FooTest.Abc',
498        'FooTest.Xyz',
499
500        'BarTest.TestOne',
501
502        'BazTest.TestOne',
503        ])
504
505    # The last 2 patterns are empty.
506    self.RunAndVerify('*oo*::', [
507        'FooTest.Abc',
508        'FooTest.Xyz',
509        ])
510
511  def testNegativeFilters(self):
512    self.RunAndVerify('*-BazTest.TestOne', [
513        'FooTest.Abc',
514        'FooTest.Xyz',
515
516        'BarTest.TestOne',
517        'BarTest.TestTwo',
518        'BarTest.TestThree',
519
520        'BazTest.TestA',
521        'BazTest.TestB',
522        ] + DEATH_TESTS + PARAM_TESTS)
523
524    self.RunAndVerify('*-FooTest.Abc:BazTest.*', [
525        'FooTest.Xyz',
526
527        'BarTest.TestOne',
528        'BarTest.TestTwo',
529        'BarTest.TestThree',
530        ] + DEATH_TESTS + PARAM_TESTS)
531
532    self.RunAndVerify('BarTest.*-BarTest.TestOne', [
533        'BarTest.TestTwo',
534        'BarTest.TestThree',
535        ])
536
537    # Tests without leading '*'.
538    self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:BazTest.*', [
539        'BarTest.TestOne',
540        'BarTest.TestTwo',
541        'BarTest.TestThree',
542        ] + DEATH_TESTS + PARAM_TESTS)
543
544    # Value parameterized tests.
545    self.RunAndVerify('*/*', PARAM_TESTS)
546
547    # Value parameterized tests filtering by the sequence name.
548    self.RunAndVerify('SeqP/*', [
549        'SeqP/ParamTest.TestX/0',
550        'SeqP/ParamTest.TestX/1',
551        'SeqP/ParamTest.TestY/0',
552        'SeqP/ParamTest.TestY/1',
553        ])
554
555    # Value parameterized tests filtering by the test name.
556    self.RunAndVerify('*/0', [
557        'SeqP/ParamTest.TestX/0',
558        'SeqP/ParamTest.TestY/0',
559        'SeqQ/ParamTest.TestX/0',
560        'SeqQ/ParamTest.TestY/0',
561        ])
562
563  def testFlagOverridesEnvVar(self):
564    """Tests that the filter flag overrides the filtering env. variable."""
565
566    SetEnvVar(FILTER_ENV_VAR, 'Foo*')
567    args = ['--%s=%s' % (FILTER_FLAG, '*One')]
568    tests_run = RunAndExtractTestList(args)[0]
569    SetEnvVar(FILTER_ENV_VAR, None)
570
571    self.AssertSetEqual(tests_run, ['BarTest.TestOne', 'BazTest.TestOne'])
572
573  def testShardStatusFileIsCreated(self):
574    """Tests that the shard file is created if specified in the environment."""
575
576    shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),
577                                     'shard_status_file')
578    self.assert_(not os.path.exists(shard_status_file))
579
580    extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}
581    try:
582      InvokeWithModifiedEnv(extra_env, RunAndReturnOutput)
583    finally:
584      self.assert_(os.path.exists(shard_status_file))
585      os.remove(shard_status_file)
586
587  def testShardStatusFileIsCreatedWithListTests(self):
588    """Tests that the shard file is created with the "list_tests" flag."""
589
590    shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),
591                                     'shard_status_file2')
592    self.assert_(not os.path.exists(shard_status_file))
593
594    extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}
595    try:
596      output = InvokeWithModifiedEnv(extra_env,
597                                     RunAndReturnOutput,
598                                     [LIST_TESTS_FLAG])
599    finally:
600      # This assertion ensures that Google Test enumerated the tests as
601      # opposed to running them.
602      self.assert_('[==========]' not in output,
603                   'Unexpected output during test enumeration.\n'
604                   'Please ensure that LIST_TESTS_FLAG is assigned the\n'
605                   'correct flag value for listing Google Test tests.')
606
607      self.assert_(os.path.exists(shard_status_file))
608      os.remove(shard_status_file)
609
610  if SUPPORTS_DEATH_TESTS:
611    def testShardingWorksWithDeathTests(self):
612      """Tests integration with death tests and sharding."""
613
614      gtest_filter = 'HasDeathTest.*:SeqP/*'
615      expected_tests = [
616          'HasDeathTest.Test1',
617          'HasDeathTest.Test2',
618
619          'SeqP/ParamTest.TestX/0',
620          'SeqP/ParamTest.TestX/1',
621          'SeqP/ParamTest.TestY/0',
622          'SeqP/ParamTest.TestY/1',
623          ]
624
625      for flag in ['--gtest_death_test_style=threadsafe',
626                   '--gtest_death_test_style=fast']:
627        self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests,
628                                      check_exit_0=True, args=[flag])
629        self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests,
630                                      check_exit_0=True, args=[flag])
631
632if __name__ == '__main__':
633  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_filter_unittest_.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Unit test for Google Test test filters.
33//
34// A user can specify which test(s) in a Google Test program to run via
35// either the GTEST_FILTER environment variable or the --gtest_filter
36// flag.  This is used for testing such functionality.
37//
38// The program will be invoked from a Python unit test.  Don't run it
39// directly.
40
41#include "gtest/gtest.h"
42
43namespace {
44
45// Test case FooTest.
46
47class FooTest : public testing::Test {
48};
49
50TEST_F(FooTest, Abc) {
51}
52
53TEST_F(FooTest, Xyz) {
54  FAIL() << "Expected failure.";
55}
56
57// Test case BarTest.
58
59TEST(BarTest, TestOne) {
60}
61
62TEST(BarTest, TestTwo) {
63}
64
65TEST(BarTest, TestThree) {
66}
67
68TEST(BarTest, DISABLED_TestFour) {
69  FAIL() << "Expected failure.";
70}
71
72TEST(BarTest, DISABLED_TestFive) {
73  FAIL() << "Expected failure.";
74}
75
76// Test case BazTest.
77
78TEST(BazTest, TestOne) {
79  FAIL() << "Expected failure.";
80}
81
82TEST(BazTest, TestA) {
83}
84
85TEST(BazTest, TestB) {
86}
87
88TEST(BazTest, DISABLED_TestC) {
89  FAIL() << "Expected failure.";
90}
91
92// Test case HasDeathTest
93
94TEST(HasDeathTest, Test1) {
95  EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
96}
97
98// We need at least two death tests to make sure that the all death tests
99// aren't on the first shard.
100TEST(HasDeathTest, Test2) {
101  EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
102}
103
104// Test case FoobarTest
105
106TEST(DISABLED_FoobarTest, Test1) {
107  FAIL() << "Expected failure.";
108}
109
110TEST(DISABLED_FoobarTest, DISABLED_Test2) {
111  FAIL() << "Expected failure.";
112}
113
114// Test case FoobarbazTest
115
116TEST(DISABLED_FoobarbazTest, TestA) {
117  FAIL() << "Expected failure.";
118}
119
120#if GTEST_HAS_PARAM_TEST
121class ParamTest : public testing::TestWithParam<int> {
122};
123
124TEST_P(ParamTest, TestX) {
125}
126
127TEST_P(ParamTest, TestY) {
128}
129
130INSTANTIATE_TEST_CASE_P(SeqP, ParamTest, testing::Values(1, 2));
131INSTANTIATE_TEST_CASE_P(SeqQ, ParamTest, testing::Values(5, 6));
132#endif  // GTEST_HAS_PARAM_TEST
133
134}  // namespace
135
136int main(int argc, char **argv) {
137  ::testing::InitGoogleTest(&argc, argv);
138
139  return RUN_ALL_TESTS();
140}
trunk/3rdparty/googletest/googletest/test/gtest_help_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Tests the --help flag of Google C++ Testing Framework.
33
34SYNOPSIS
35       gtest_help_test.py --build_dir=BUILD/DIR
36         # where BUILD/DIR contains the built gtest_help_test_ file.
37       gtest_help_test.py
38"""
39
40__author__ = 'wan@google.com (Zhanyong Wan)'
41
42import os
43import re
44import gtest_test_utils
45
46
47IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
48IS_WINDOWS = os.name == 'nt'
49
50PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
51FLAG_PREFIX = '--gtest_'
52DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style'
53STREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to'
54UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing'
55LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
56INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG),
57                           re.sub('^--', '/', LIST_TESTS_FLAG),
58                           re.sub('_', '-', LIST_TESTS_FLAG)]
59INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing'
60
61SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess(
62    [PROGRAM_PATH, LIST_TESTS_FLAG]).output
63
64# The help message must match this regex.
65HELP_REGEX = re.compile(
66    FLAG_PREFIX + r'list_tests.*' +
67    FLAG_PREFIX + r'filter=.*' +
68    FLAG_PREFIX + r'also_run_disabled_tests.*' +
69    FLAG_PREFIX + r'repeat=.*' +
70    FLAG_PREFIX + r'shuffle.*' +
71    FLAG_PREFIX + r'random_seed=.*' +
72    FLAG_PREFIX + r'color=.*' +
73    FLAG_PREFIX + r'print_time.*' +
74    FLAG_PREFIX + r'output=.*' +
75    FLAG_PREFIX + r'break_on_failure.*' +
76    FLAG_PREFIX + r'throw_on_failure.*' +
77    FLAG_PREFIX + r'catch_exceptions=0.*',
78    re.DOTALL)
79
80
81def RunWithFlag(flag):
82  """Runs gtest_help_test_ with the given flag.
83
84  Returns:
85    the exit code and the text output as a tuple.
86  Args:
87    flag: the command-line flag to pass to gtest_help_test_, or None.
88  """
89
90  if flag is None:
91    command = [PROGRAM_PATH]
92  else:
93    command = [PROGRAM_PATH, flag]
94  child = gtest_test_utils.Subprocess(command)
95  return child.exit_code, child.output
96
97
98class GTestHelpTest(gtest_test_utils.TestCase):
99  """Tests the --help flag and its equivalent forms."""
100
101  def TestHelpFlag(self, flag):
102    """Verifies correct behavior when help flag is specified.
103
104    The right message must be printed and the tests must
105    skipped when the given flag is specified.
106
107    Args:
108      flag:  A flag to pass to the binary or None.
109    """
110
111    exit_code, output = RunWithFlag(flag)
112    self.assertEquals(0, exit_code)
113    self.assert_(HELP_REGEX.search(output), output)
114
115    if IS_LINUX:
116      self.assert_(STREAM_RESULT_TO_FLAG in output, output)
117    else:
118      self.assert_(STREAM_RESULT_TO_FLAG not in output, output)
119
120    if SUPPORTS_DEATH_TESTS and not IS_WINDOWS:
121      self.assert_(DEATH_TEST_STYLE_FLAG in output, output)
122    else:
123      self.assert_(DEATH_TEST_STYLE_FLAG not in output, output)
124
125  def TestNonHelpFlag(self, flag):
126    """Verifies correct behavior when no help flag is specified.
127
128    Verifies that when no help flag is specified, the tests are run
129    and the help message is not printed.
130
131    Args:
132      flag:  A flag to pass to the binary or None.
133    """
134
135    exit_code, output = RunWithFlag(flag)
136    self.assert_(exit_code != 0)
137    self.assert_(not HELP_REGEX.search(output), output)
138
139  def testPrintsHelpWithFullFlag(self):
140    self.TestHelpFlag('--help')
141
142  def testPrintsHelpWithShortFlag(self):
143    self.TestHelpFlag('-h')
144
145  def testPrintsHelpWithQuestionFlag(self):
146    self.TestHelpFlag('-?')
147
148  def testPrintsHelpWithWindowsStyleQuestionFlag(self):
149    self.TestHelpFlag('/?')
150
151  def testPrintsHelpWithUnrecognizedGoogleTestFlag(self):
152    self.TestHelpFlag(UNKNOWN_FLAG)
153
154  def testPrintsHelpWithIncorrectFlagStyle(self):
155    for incorrect_flag in INCORRECT_FLAG_VARIANTS:
156      self.TestHelpFlag(incorrect_flag)
157
158  def testRunsTestsWithoutHelpFlag(self):
159    """Verifies that when no help flag is specified, the tests are run
160    and the help message is not printed."""
161
162    self.TestNonHelpFlag(None)
163
164  def testRunsTestsWithGtestInternalFlag(self):
165    """Verifies that the tests are run and no help message is printed when
166    a flag starting with Google Test prefix and 'internal_' is supplied."""
167
168    self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING)
169
170
171if __name__ == '__main__':
172  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_help_test_.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// This program is meant to be run by gtest_help_test.py.  Do not run
33// it directly.
34
35#include "gtest/gtest.h"
36
37// When a help flag is specified, this program should skip the tests
38// and exit with 0; otherwise the following test will be executed,
39// causing this program to exit with a non-zero code.
40TEST(HelpFlagTest, ShouldNotBeRun) {
41  ASSERT_TRUE(false) << "Tests shouldn't be run when --help is specified.";
42}
43
44#if GTEST_HAS_DEATH_TEST
45TEST(DeathTest, UsedByPythonScriptToDetectSupportForDeathTestsInThisBinary) {}
46#endif
trunk/3rdparty/googletest/googletest/test/gtest_list_tests_unittest.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2006, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Unit test for Google Test's --gtest_list_tests flag.
33
34A user can ask Google Test to list all tests by specifying the
35--gtest_list_tests flag.  This script tests such functionality
36by invoking gtest_list_tests_unittest_ (a program written with
37Google Test) the command line flags.
38"""
39
40__author__ = 'phanna@google.com (Patrick Hanna)'
41
42import gtest_test_utils
43import re
44
45
46# Constants.
47
48# The command line flag for enabling/disabling listing all tests.
49LIST_TESTS_FLAG = 'gtest_list_tests'
50
51# Path to the gtest_list_tests_unittest_ program.
52EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_list_tests_unittest_')
53
54# The expected output when running gtest_list_tests_unittest_ with
55# --gtest_list_tests
56EXPECTED_OUTPUT_NO_FILTER_RE = re.compile(r"""FooDeathTest\.
57  Test1
58Foo\.
59  Bar1
60  Bar2
61  DISABLED_Bar3
62Abc\.
63  Xyz
64  Def
65FooBar\.
66  Baz
67FooTest\.
68  Test1
69  DISABLED_Test2
70  Test3
71TypedTest/0\.  # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\.
72  TestA
73  TestB
74TypedTest/1\.  # TypeParam = int\s*\*
75  TestA
76  TestB
77TypedTest/2\.  # TypeParam = .*MyArray<bool,\s*42>
78  TestA
79  TestB
80My/TypeParamTest/0\.  # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\.
81  TestA
82  TestB
83My/TypeParamTest/1\.  # TypeParam = int\s*\*
84  TestA
85  TestB
86My/TypeParamTest/2\.  # TypeParam = .*MyArray<bool,\s*42>
87  TestA
88  TestB
89MyInstantiation/ValueParamTest\.
90  TestA/0  # GetParam\(\) = one line
91  TestA/1  # GetParam\(\) = two\\nlines
92  TestA/2  # GetParam\(\) = a very\\nlo{241}\.\.\.
93  TestB/0  # GetParam\(\) = one line
94  TestB/1  # GetParam\(\) = two\\nlines
95  TestB/2  # GetParam\(\) = a very\\nlo{241}\.\.\.
96""")
97
98# The expected output when running gtest_list_tests_unittest_ with
99# --gtest_list_tests and --gtest_filter=Foo*.
100EXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(r"""FooDeathTest\.
101  Test1
102Foo\.
103  Bar1
104  Bar2
105  DISABLED_Bar3
106FooBar\.
107  Baz
108FooTest\.
109  Test1
110  DISABLED_Test2
111  Test3
112""")
113
114# Utilities.
115
116
117def Run(args):
118  """Runs gtest_list_tests_unittest_ and returns the list of tests printed."""
119
120  return gtest_test_utils.Subprocess([EXE_PATH] + args,
121                                     capture_stderr=False).output
122
123
124# The unit test.
125
126class GTestListTestsUnitTest(gtest_test_utils.TestCase):
127  """Tests using the --gtest_list_tests flag to list all tests."""
128
129  def RunAndVerify(self, flag_value, expected_output_re, other_flag):
130    """Runs gtest_list_tests_unittest_ and verifies that it prints
131    the correct tests.
132
133    Args:
134      flag_value:         value of the --gtest_list_tests flag;
135                          None if the flag should not be present.
136      expected_output_re: regular expression that matches the expected
137                          output after running command;
138      other_flag:         a different flag to be passed to command
139                          along with gtest_list_tests;
140                          None if the flag should not be present.
141    """
142
143    if flag_value is None:
144      flag = ''
145      flag_expression = 'not set'
146    elif flag_value == '0':
147      flag = '--%s=0' % LIST_TESTS_FLAG
148      flag_expression = '0'
149    else:
150      flag = '--%s' % LIST_TESTS_FLAG
151      flag_expression = '1'
152
153    args = [flag]
154
155    if other_flag is not None:
156      args += [other_flag]
157
158    output = Run(args)
159
160    if expected_output_re:
161      self.assert_(
162          expected_output_re.match(output),
163          ('when %s is %s, the output of "%s" is "%s",\n'
164           'which does not match regex "%s"' %
165           (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output,
166            expected_output_re.pattern)))
167    else:
168      self.assert_(
169          not EXPECTED_OUTPUT_NO_FILTER_RE.match(output),
170          ('when %s is %s, the output of "%s" is "%s"'%
171           (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output)))
172
173  def testDefaultBehavior(self):
174    """Tests the behavior of the default mode."""
175
176    self.RunAndVerify(flag_value=None,
177                      expected_output_re=None,
178                      other_flag=None)
179
180  def testFlag(self):
181    """Tests using the --gtest_list_tests flag."""
182
183    self.RunAndVerify(flag_value='0',
184                      expected_output_re=None,
185                      other_flag=None)
186    self.RunAndVerify(flag_value='1',
187                      expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,
188                      other_flag=None)
189
190  def testOverrideNonFilterFlags(self):
191    """Tests that --gtest_list_tests overrides the non-filter flags."""
192
193    self.RunAndVerify(flag_value='1',
194                      expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,
195                      other_flag='--gtest_break_on_failure')
196
197  def testWithFilterFlags(self):
198    """Tests that --gtest_list_tests takes into account the
199    --gtest_filter flag."""
200
201    self.RunAndVerify(flag_value='1',
202                      expected_output_re=EXPECTED_OUTPUT_FILTER_FOO_RE,
203                      other_flag='--gtest_filter=Foo*')
204
205
206if __name__ == '__main__':
207  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_list_tests_unittest_.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: phanna@google.com (Patrick Hanna)
31
32// Unit test for Google Test's --gtest_list_tests flag.
33//
34// A user can ask Google Test to list all tests that will run
35// so that when using a filter, a user will know what
36// tests to look for. The tests will not be run after listing.
37//
38// This program will be invoked from a Python unit test.
39// Don't run it directly.
40
41#include "gtest/gtest.h"
42
43// Several different test cases and tests that will be listed.
44TEST(Foo, Bar1) {
45}
46
47TEST(Foo, Bar2) {
48}
49
50TEST(Foo, DISABLED_Bar3) {
51}
52
53TEST(Abc, Xyz) {
54}
55
56TEST(Abc, Def) {
57}
58
59TEST(FooBar, Baz) {
60}
61
62class FooTest : public testing::Test {
63};
64
65TEST_F(FooTest, Test1) {
66}
67
68TEST_F(FooTest, DISABLED_Test2) {
69}
70
71TEST_F(FooTest, Test3) {
72}
73
74TEST(FooDeathTest, Test1) {
75}
76
77// A group of value-parameterized tests.
78
79class MyType {
80 public:
81  explicit MyType(const std::string& a_value) : value_(a_value) {}
82
83  const std::string& value() const { return value_; }
84
85 private:
86  std::string value_;
87};
88
89// Teaches Google Test how to print a MyType.
90void PrintTo(const MyType& x, std::ostream* os) {
91  *os << x.value();
92}
93
94class ValueParamTest : public testing::TestWithParam<MyType> {
95};
96
97TEST_P(ValueParamTest, TestA) {
98}
99
100TEST_P(ValueParamTest, TestB) {
101}
102
103INSTANTIATE_TEST_CASE_P(
104    MyInstantiation, ValueParamTest,
105    testing::Values(MyType("one line"),
106                    MyType("two\nlines"),
107                    MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line")));  // NOLINT
108
109// A group of typed tests.
110
111// A deliberately long type name for testing the line-truncating
112// behavior when printing a type parameter.
113class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName {  // NOLINT
114};
115
116template <typename T>
117class TypedTest : public testing::Test {
118};
119
120template <typename T, int kSize>
121class MyArray {
122};
123
124typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName,  // NOLINT
125                       int*, MyArray<bool, 42> > MyTypes;
126
127TYPED_TEST_CASE(TypedTest, MyTypes);
128
129TYPED_TEST(TypedTest, TestA) {
130}
131
132TYPED_TEST(TypedTest, TestB) {
133}
134
135// A group of type-parameterized tests.
136
137template <typename T>
138class TypeParamTest : public testing::Test {
139};
140
141TYPED_TEST_CASE_P(TypeParamTest);
142
143TYPED_TEST_P(TypeParamTest, TestA) {
144}
145
146TYPED_TEST_P(TypeParamTest, TestB) {
147}
148
149REGISTER_TYPED_TEST_CASE_P(TypeParamTest, TestA, TestB);
150
151INSTANTIATE_TYPED_TEST_CASE_P(My, TypeParamTest, MyTypes);
152
153int main(int argc, char **argv) {
154  ::testing::InitGoogleTest(&argc, argv);
155
156  return RUN_ALL_TESTS();
157}
trunk/3rdparty/googletest/googletest/test/gtest_main_unittest.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gtest/gtest.h"
33
34// Tests that we don't have to define main() when we link to
35// gtest_main instead of gtest.
36
37namespace {
38
39TEST(GTestMainTest, ShouldSucceed) {
40}
41
42}  // namespace
43
44// We are using the main() function defined in src/gtest_main.cc, so
45// we don't define it here.
trunk/3rdparty/googletest/googletest/test/gtest_no_test_unittest.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// Tests that a Google Test program that has no test defined can run
31// successfully.
32//
33// Author: wan@google.com (Zhanyong Wan)
34
35#include "gtest/gtest.h"
36
37int main(int argc, char **argv) {
38  testing::InitGoogleTest(&argc, argv);
39
40  // An ad-hoc assertion outside of all tests.
41  //
42  // This serves three purposes:
43  //
44  // 1. It verifies that an ad-hoc assertion can be executed even if
45  //    no test is defined.
46  // 2. It verifies that a failed ad-hoc assertion causes the test
47  //    program to fail.
48  // 3. We had a bug where the XML output won't be generated if an
49  //    assertion is executed before RUN_ALL_TESTS() is called, even
50  //    though --gtest_output=xml is specified.  This makes sure the
51  //    bug is fixed and doesn't regress.
52  EXPECT_EQ(1, 2);
53
54  // The above EXPECT_EQ() should cause RUN_ALL_TESTS() to return non-zero.
55  return RUN_ALL_TESTS() ? 0 : 1;
56}
trunk/3rdparty/googletest/googletest/test/gtest_output_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Tests the text output of Google C++ Testing Framework.
33
34SYNOPSIS
35       gtest_output_test.py --build_dir=BUILD/DIR --gengolden
36         # where BUILD/DIR contains the built gtest_output_test_ file.
37       gtest_output_test.py --gengolden
38       gtest_output_test.py
39"""
40
41__author__ = 'wan@google.com (Zhanyong Wan)'
42
43import difflib
44import os
45import re
46import sys
47import gtest_test_utils
48
49
50# The flag for generating the golden file
51GENGOLDEN_FLAG = '--gengolden'
52CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS'
53
54IS_WINDOWS = os.name == 'nt'
55
56# TODO(vladl@google.com): remove the _lin suffix.
57GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
58
59PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
60
61# At least one command we exercise must not have the
62# 'internal_skip_environment_and_ad_hoc_tests' argument.
63COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
64COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
65COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
66                          '--gtest_print_time',
67                          'internal_skip_environment_and_ad_hoc_tests',
68                          '--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
69COMMAND_WITH_DISABLED = (
70    {}, [PROGRAM_PATH,
71         '--gtest_also_run_disabled_tests',
72         'internal_skip_environment_and_ad_hoc_tests',
73         '--gtest_filter=*DISABLED_*'])
74COMMAND_WITH_SHARDING = (
75    {'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
76    [PROGRAM_PATH,
77     'internal_skip_environment_and_ad_hoc_tests',
78     '--gtest_filter=PassingTest.*'])
79
80GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
81
82
83def ToUnixLineEnding(s):
84  """Changes all Windows/Mac line endings in s to UNIX line endings."""
85
86  return s.replace('\r\n', '\n').replace('\r', '\n')
87
88
89def RemoveLocations(test_output):
90  """Removes all file location info from a Google Test program's output.
91
92  Args:
93       test_output:  the output of a Google Test program.
94
95  Returns:
96       output with all file location info (in the form of
97       'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
98       'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
99       'FILE_NAME:#: '.
100  """
101
102  return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
103
104
105def RemoveStackTraceDetails(output):
106  """Removes all stack traces from a Google Test program's output."""
107
108  # *? means "find the shortest string that matches".
109  return re.sub(r'Stack trace:(.|\n)*?\n\n',
110                'Stack trace: (omitted)\n\n', output)
111
112
113def RemoveStackTraces(output):
114  """Removes all traces of stack traces from a Google Test program's output."""
115
116  # *? means "find the shortest string that matches".
117  return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)
118
119
120def RemoveTime(output):
121  """Removes all time information from a Google Test program's output."""
122
123  return re.sub(r'\(\d+ ms', '(? ms', output)
124
125
126def RemoveTypeInfoDetails(test_output):
127  """Removes compiler-specific type info from Google Test program's output.
128
129  Args:
130       test_output:  the output of a Google Test program.
131
132  Returns:
133       output with type information normalized to canonical form.
134  """
135
136  # some compilers output the name of type 'unsigned int' as 'unsigned'
137  return re.sub(r'unsigned int', 'unsigned', test_output)
138
139
140def NormalizeToCurrentPlatform(test_output):
141  """Normalizes platform specific output details for easier comparison."""
142
143  if IS_WINDOWS:
144    # Removes the color information that is not present on Windows.
145    test_output = re.sub('\x1b\\[(0;3\d)?m', '', test_output)
146    # Changes failure message headers into the Windows format.
147    test_output = re.sub(r': Failure\n', r': error: ', test_output)
148    # Changes file(line_number) to file:line_number.
149    test_output = re.sub(r'((\w|\.)+)\((\d+)\):', r'\1:\3:', test_output)
150
151  return test_output
152
153
154def RemoveTestCounts(output):
155  """Removes test counts from a Google Test program's output."""
156
157  output = re.sub(r'\d+ tests?, listed below',
158                  '? tests, listed below', output)
159  output = re.sub(r'\d+ FAILED TESTS',
160                  '? FAILED TESTS', output)
161  output = re.sub(r'\d+ tests? from \d+ test cases?',
162                  '? tests from ? test cases', output)
163  output = re.sub(r'\d+ tests? from ([a-zA-Z_])',
164                  r'? tests from \1', output)
165  return re.sub(r'\d+ tests?\.', '? tests.', output)
166
167
168def RemoveMatchingTests(test_output, pattern):
169  """Removes output of specified tests from a Google Test program's output.
170
171  This function strips not only the beginning and the end of a test but also
172  all output in between.
173
174  Args:
175    test_output:       A string containing the test output.
176    pattern:           A regex string that matches names of test cases or
177                       tests to remove.
178
179  Returns:
180    Contents of test_output with tests whose names match pattern removed.
181  """
182
183  test_output = re.sub(
184      r'.*\[ RUN      \] .*%s(.|\n)*?\[(  FAILED  |       OK )\] .*%s.*\n' % (
185          pattern, pattern),
186      '',
187      test_output)
188  return re.sub(r'.*%s.*\n' % pattern, '', test_output)
189
190
191def NormalizeOutput(output):
192  """Normalizes output (the output of gtest_output_test_.exe)."""
193
194  output = ToUnixLineEnding(output)
195  output = RemoveLocations(output)
196  output = RemoveStackTraceDetails(output)
197  output = RemoveTime(output)
198  return output
199
200
201def GetShellCommandOutput(env_cmd):
202  """Runs a command in a sub-process, and returns its output in a string.
203
204  Args:
205    env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
206             environment variables to set, and element 1 is a string with
207             the command and any flags.
208
209  Returns:
210    A string with the command's combined standard and diagnostic output.
211  """
212
213  # Spawns cmd in a sub-process, and gets its standard I/O file objects.
214  # Set and save the environment properly.
215  environ = os.environ.copy()
216  environ.update(env_cmd[0])
217  p = gtest_test_utils.Subprocess(env_cmd[1], env=environ)
218
219  return p.output
220
221
222def GetCommandOutput(env_cmd):
223  """Runs a command and returns its output with all file location
224  info stripped off.
225
226  Args:
227    env_cmd:  The shell command. A 2-tuple where element 0 is a dict of extra
228              environment variables to set, and element 1 is a string with
229              the command and any flags.
230  """
231
232  # Disables exception pop-ups on Windows.
233  environ, cmdline = env_cmd
234  environ = dict(environ)  # Ensures we are modifying a copy.
235  environ[CATCH_EXCEPTIONS_ENV_VAR_NAME] = '1'
236  return NormalizeOutput(GetShellCommandOutput((environ, cmdline)))
237
238
239def GetOutputOfAllCommands():
240  """Returns concatenated output from several representative commands."""
241
242  return (GetCommandOutput(COMMAND_WITH_COLOR) +
243          GetCommandOutput(COMMAND_WITH_TIME) +
244          GetCommandOutput(COMMAND_WITH_DISABLED) +
245          GetCommandOutput(COMMAND_WITH_SHARDING))
246
247
248test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
249SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
250SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
251SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
252SUPPORTS_STACK_TRACES = False
253
254CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and
255                            SUPPORTS_TYPED_TESTS and
256                            SUPPORTS_THREADS and
257                            not IS_WINDOWS)
258
259class GTestOutputTest(gtest_test_utils.TestCase):
260  def RemoveUnsupportedTests(self, test_output):
261    if not SUPPORTS_DEATH_TESTS:
262      test_output = RemoveMatchingTests(test_output, 'DeathTest')
263    if not SUPPORTS_TYPED_TESTS:
264      test_output = RemoveMatchingTests(test_output, 'TypedTest')
265      test_output = RemoveMatchingTests(test_output, 'TypedDeathTest')
266      test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest')
267    if not SUPPORTS_THREADS:
268      test_output = RemoveMatchingTests(test_output,
269                                        'ExpectFailureWithThreadsTest')
270      test_output = RemoveMatchingTests(test_output,
271                                        'ScopedFakeTestPartResultReporterTest')
272      test_output = RemoveMatchingTests(test_output,
273                                        'WorksConcurrently')
274    if not SUPPORTS_STACK_TRACES:
275      test_output = RemoveStackTraces(test_output)
276
277    return test_output
278
279  def testOutput(self):
280    output = GetOutputOfAllCommands()
281
282    golden_file = open(GOLDEN_PATH, 'rb')
283    # A mis-configured source control system can cause \r appear in EOL
284    # sequences when we read the golden file irrespective of an operating
285    # system used. Therefore, we need to strip those \r's from newlines
286    # unconditionally.
287    golden = ToUnixLineEnding(golden_file.read())
288    golden_file.close()
289
290    # We want the test to pass regardless of certain features being
291    # supported or not.
292
293    # We still have to remove type name specifics in all cases.
294    normalized_actual = RemoveTypeInfoDetails(output)
295    normalized_golden = RemoveTypeInfoDetails(golden)
296
297    if CAN_GENERATE_GOLDEN_FILE:
298      self.assertEqual(normalized_golden, normalized_actual,
299                       '\n'.join(difflib.unified_diff(
300                           normalized_golden.split('\n'),
301                           normalized_actual.split('\n'),
302                           'golden', 'actual')))
303    else:
304      normalized_actual = NormalizeToCurrentPlatform(
305          RemoveTestCounts(normalized_actual))
306      normalized_golden = NormalizeToCurrentPlatform(
307          RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden)))
308
309      # This code is very handy when debugging golden file differences:
310      if os.getenv('DEBUG_GTEST_OUTPUT_TEST'):
311        open(os.path.join(
312            gtest_test_utils.GetSourceDir(),
313            '_gtest_output_test_normalized_actual.txt'), 'wb').write(
314                normalized_actual)
315        open(os.path.join(
316            gtest_test_utils.GetSourceDir(),
317            '_gtest_output_test_normalized_golden.txt'), 'wb').write(
318                normalized_golden)
319
320      self.assertEqual(normalized_golden, normalized_actual)
321
322
323if __name__ == '__main__':
324  if sys.argv[1:] == [GENGOLDEN_FLAG]:
325    if CAN_GENERATE_GOLDEN_FILE:
326      output = GetOutputOfAllCommands()
327      golden_file = open(GOLDEN_PATH, 'wb')
328      golden_file.write(output)
329      golden_file.close()
330    else:
331      message = (
332          """Unable to write a golden file when compiled in an environment
333that does not support all the required features (death tests, typed tests,
334and multiple threads).  Please generate the golden file using a binary built
335with those features enabled.""")
336
337      sys.stderr.write(message)
338      sys.exit(1)
339  else:
340    gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_output_test_.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// The purpose of this file is to generate Google Test output under
31// various conditions.  The output will then be verified by
32// gtest_output_test.py to ensure that Google Test generates the
33// desired messages.  Therefore, most tests in this file are MEANT TO
34// FAIL.
35//
36// Author: wan@google.com (Zhanyong Wan)
37
38#include "gtest/gtest-spi.h"
39#include "gtest/gtest.h"
40
41// Indicates that this translation unit is part of Google Test's
42// implementation.  It must come before gtest-internal-inl.h is
43// included, or there will be a compiler error.  This trick is to
44// prevent a user from accidentally including gtest-internal-inl.h in
45// his code.
46#define GTEST_IMPLEMENTATION_ 1
47#include "src/gtest-internal-inl.h"
48#undef GTEST_IMPLEMENTATION_
49
50#include <stdlib.h>
51
52#if GTEST_IS_THREADSAFE
53using testing::ScopedFakeTestPartResultReporter;
54using testing::TestPartResultArray;
55
56using testing::internal::Notification;
57using testing::internal::ThreadWithParam;
58#endif
59
60namespace posix = ::testing::internal::posix;
61
62// Tests catching fatal failures.
63
64// A subroutine used by the following test.
65void TestEq1(int x) {
66  ASSERT_EQ(1, x);
67}
68
69// This function calls a test subroutine, catches the fatal failure it
70// generates, and then returns early.
71void TryTestSubroutine() {
72  // Calls a subrountine that yields a fatal failure.
73  TestEq1(2);
74
75  // Catches the fatal failure and aborts the test.
76  //
77  // The testing::Test:: prefix is necessary when calling
78  // HasFatalFailure() outside of a TEST, TEST_F, or test fixture.
79  if (testing::Test::HasFatalFailure()) return;
80
81  // If we get here, something is wrong.
82  FAIL() << "This should never be reached.";
83}
84
85TEST(PassingTest, PassingTest1) {
86}
87
88TEST(PassingTest, PassingTest2) {
89}
90
91// Tests that parameters of failing parameterized tests are printed in the
92// failing test summary.
93class FailingParamTest : public testing::TestWithParam<int> {};
94
95TEST_P(FailingParamTest, Fails) {
96  EXPECT_EQ(1, GetParam());
97}
98
99// This generates a test which will fail. Google Test is expected to print
100// its parameter when it outputs the list of all failed tests.
101INSTANTIATE_TEST_CASE_P(PrintingFailingParams,
102                        FailingParamTest,
103                        testing::Values(2));
104
105static const char kGoldenString[] = "\"Line\0 1\"\nLine 2";
106
107TEST(NonfatalFailureTest, EscapesStringOperands) {
108  std::string actual = "actual \"string\"";
109  EXPECT_EQ(kGoldenString, actual);
110
111  const char* golden = kGoldenString;
112  EXPECT_EQ(golden, actual);
113}
114
115TEST(NonfatalFailureTest, DiffForLongStrings) {
116  std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1);
117  EXPECT_EQ(golden_str, "Line 2");
118}
119
120// Tests catching a fatal failure in a subroutine.
121TEST(FatalFailureTest, FatalFailureInSubroutine) {
122  printf("(expecting a failure that x should be 1)\n");
123
124  TryTestSubroutine();
125}
126
127// Tests catching a fatal failure in a nested subroutine.
128TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
129  printf("(expecting a failure that x should be 1)\n");
130
131  // Calls a subrountine that yields a fatal failure.
132  TryTestSubroutine();
133
134  // Catches the fatal failure and aborts the test.
135  //
136  // When calling HasFatalFailure() inside a TEST, TEST_F, or test
137  // fixture, the testing::Test:: prefix is not needed.
138  if (HasFatalFailure()) return;
139
140  // If we get here, something is wrong.
141  FAIL() << "This should never be reached.";
142}
143
144// Tests HasFatalFailure() after a failed EXPECT check.
145TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
146  printf("(expecting a failure on false)\n");
147  EXPECT_TRUE(false);  // Generates a nonfatal failure
148  ASSERT_FALSE(HasFatalFailure());  // This should succeed.
149}
150
151// Tests interleaving user logging and Google Test assertions.
152TEST(LoggingTest, InterleavingLoggingAndAssertions) {
153  static const int a[4] = {
154    3, 9, 2, 6
155  };
156
157  printf("(expecting 2 failures on (3) >= (a[i]))\n");
158  for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) {
159    printf("i == %d\n", i);
160    EXPECT_GE(3, a[i]);
161  }
162}
163
164// Tests the SCOPED_TRACE macro.
165
166// A helper function for testing SCOPED_TRACE.
167void SubWithoutTrace(int n) {
168  EXPECT_EQ(1, n);
169  ASSERT_EQ(2, n);
170}
171
172// Another helper function for testing SCOPED_TRACE.
173void SubWithTrace(int n) {
174  SCOPED_TRACE(testing::Message() << "n = " << n);
175
176  SubWithoutTrace(n);
177}
178
179// Tests that SCOPED_TRACE() obeys lexical scopes.
180TEST(SCOPED_TRACETest, ObeysScopes) {
181  printf("(expected to fail)\n");
182
183  // There should be no trace before SCOPED_TRACE() is invoked.
184  ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
185
186  {
187    SCOPED_TRACE("Expected trace");
188    // After SCOPED_TRACE(), a failure in the current scope should contain
189    // the trace.
190    ADD_FAILURE() << "This failure is expected, and should have a trace.";
191  }
192
193  // Once the control leaves the scope of the SCOPED_TRACE(), there
194  // should be no trace again.
195  ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
196}
197
198// Tests that SCOPED_TRACE works inside a loop.
199TEST(SCOPED_TRACETest, WorksInLoop) {
200  printf("(expected to fail)\n");
201
202  for (int i = 1; i <= 2; i++) {
203    SCOPED_TRACE(testing::Message() << "i = " << i);
204
205    SubWithoutTrace(i);
206  }
207}
208
209// Tests that SCOPED_TRACE works in a subroutine.
210TEST(SCOPED_TRACETest, WorksInSubroutine) {
211  printf("(expected to fail)\n");
212
213  SubWithTrace(1);
214  SubWithTrace(2);
215}
216
217// Tests that SCOPED_TRACE can be nested.
218TEST(SCOPED_TRACETest, CanBeNested) {
219  printf("(expected to fail)\n");
220
221  SCOPED_TRACE("");  // A trace without a message.
222
223  SubWithTrace(2);
224}
225
226// Tests that multiple SCOPED_TRACEs can be used in the same scope.
227TEST(SCOPED_TRACETest, CanBeRepeated) {
228  printf("(expected to fail)\n");
229
230  SCOPED_TRACE("A");
231  ADD_FAILURE()
232      << "This failure is expected, and should contain trace point A.";
233
234  SCOPED_TRACE("B");
235  ADD_FAILURE()
236      << "This failure is expected, and should contain trace point A and B.";
237
238  {
239    SCOPED_TRACE("C");
240    ADD_FAILURE() << "This failure is expected, and should "
241                  << "contain trace point A, B, and C.";
242  }
243
244  SCOPED_TRACE("D");
245  ADD_FAILURE() << "This failure is expected, and should "
246                << "contain trace point A, B, and D.";
247}
248
249#if GTEST_IS_THREADSAFE
250// Tests that SCOPED_TRACE()s can be used concurrently from multiple
251// threads.  Namely, an assertion should be affected by
252// SCOPED_TRACE()s in its own thread only.
253
254// Here's the sequence of actions that happen in the test:
255//
256//   Thread A (main)                | Thread B (spawned)
257//   ===============================|================================
258//   spawns thread B                |
259//   -------------------------------+--------------------------------
260//   waits for n1                   | SCOPED_TRACE("Trace B");
261//                                  | generates failure #1
262//                                  | notifies n1
263//   -------------------------------+--------------------------------
264//   SCOPED_TRACE("Trace A");       | waits for n2
265//   generates failure #2           |
266//   notifies n2                    |
267//   -------------------------------|--------------------------------
268//   waits for n3                   | generates failure #3
269//                                  | trace B dies
270//                                  | generates failure #4
271//                                  | notifies n3
272//   -------------------------------|--------------------------------
273//   generates failure #5           | finishes
274//   trace A dies                   |
275//   generates failure #6           |
276//   -------------------------------|--------------------------------
277//   waits for thread B to finish   |
278
279struct CheckPoints {
280  Notification n1;
281  Notification n2;
282  Notification n3;
283};
284
285static void ThreadWithScopedTrace(CheckPoints* check_points) {
286  {
287    SCOPED_TRACE("Trace B");
288    ADD_FAILURE()
289        << "Expected failure #1 (in thread B, only trace B alive).";
290    check_points->n1.Notify();
291    check_points->n2.WaitForNotification();
292
293    ADD_FAILURE()
294        << "Expected failure #3 (in thread B, trace A & B both alive).";
295  }  // Trace B dies here.
296  ADD_FAILURE()
297      << "Expected failure #4 (in thread B, only trace A alive).";
298  check_points->n3.Notify();
299}
300
301TEST(SCOPED_TRACETest, WorksConcurrently) {
302  printf("(expecting 6 failures)\n");
303
304  CheckPoints check_points;
305  ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace,
306                                       &check_points,
307                                       NULL);
308  check_points.n1.WaitForNotification();
309
310  {
311    SCOPED_TRACE("Trace A");
312    ADD_FAILURE()
313        << "Expected failure #2 (in thread A, trace A & B both alive).";
314    check_points.n2.Notify();
315    check_points.n3.WaitForNotification();
316
317    ADD_FAILURE()
318        << "Expected failure #5 (in thread A, only trace A alive).";
319  }  // Trace A dies here.
320  ADD_FAILURE()
321      << "Expected failure #6 (in thread A, no trace alive).";
322  thread.Join();
323}
324#endif  // GTEST_IS_THREADSAFE
325
326TEST(DisabledTestsWarningTest,
327     DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {
328  // This test body is intentionally empty.  Its sole purpose is for
329  // verifying that the --gtest_also_run_disabled_tests flag
330  // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of
331  // the test output.
332}
333
334// Tests using assertions outside of TEST and TEST_F.
335//
336// This function creates two failures intentionally.
337void AdHocTest() {
338  printf("The non-test part of the code is expected to have 2 failures.\n\n");
339  EXPECT_TRUE(false);
340  EXPECT_EQ(2, 3);
341}
342
343// Runs all TESTs, all TEST_Fs, and the ad hoc test.
344int RunAllTests() {
345  AdHocTest();
346  return RUN_ALL_TESTS();
347}
348
349// Tests non-fatal failures in the fixture constructor.
350class NonFatalFailureInFixtureConstructorTest : public testing::Test {
351 protected:
352  NonFatalFailureInFixtureConstructorTest() {
353    printf("(expecting 5 failures)\n");
354    ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
355  }
356
357  ~NonFatalFailureInFixtureConstructorTest() {
358    ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
359  }
360
361  virtual void SetUp() {
362    ADD_FAILURE() << "Expected failure #2, in SetUp().";
363  }
364
365  virtual void TearDown() {
366    ADD_FAILURE() << "Expected failure #4, in TearDown.";
367  }
368};
369
370TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
371  ADD_FAILURE() << "Expected failure #3, in the test body.";
372}
373
374// Tests fatal failures in the fixture constructor.
375class FatalFailureInFixtureConstructorTest : public testing::Test {
376 protected:
377  FatalFailureInFixtureConstructorTest() {
378    printf("(expecting 2 failures)\n");
379    Init();
380  }
381
382  ~FatalFailureInFixtureConstructorTest() {
383    ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
384  }
385
386  virtual void SetUp() {
387    ADD_FAILURE() << "UNEXPECTED failure in SetUp().  "
388                  << "We should never get here, as the test fixture c'tor "
389                  << "had a fatal failure.";
390  }
391
392  virtual void TearDown() {
393    ADD_FAILURE() << "UNEXPECTED failure in TearDown().  "
394                  << "We should never get here, as the test fixture c'tor "
395                  << "had a fatal failure.";
396  }
397
398 private:
399  void Init() {
400    FAIL() << "Expected failure #1, in the test fixture c'tor.";
401  }
402};
403
404TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
405  ADD_FAILURE() << "UNEXPECTED failure in the test body.  "
406                << "We should never get here, as the test fixture c'tor "
407                << "had a fatal failure.";
408}
409
410// Tests non-fatal failures in SetUp().
411class NonFatalFailureInSetUpTest : public testing::Test {
412 protected:
413  virtual ~NonFatalFailureInSetUpTest() {
414    Deinit();
415  }
416
417  virtual void SetUp() {
418    printf("(expecting 4 failures)\n");
419    ADD_FAILURE() << "Expected failure #1, in SetUp().";
420  }
421
422  virtual void TearDown() {
423    FAIL() << "Expected failure #3, in TearDown().";
424  }
425 private:
426  void Deinit() {
427    FAIL() << "Expected failure #4, in the test fixture d'tor.";
428  }
429};
430
431TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
432  FAIL() << "Expected failure #2, in the test function.";
433}
434
435// Tests fatal failures in SetUp().
436class FatalFailureInSetUpTest : public testing::Test {
437 protected:
438  virtual ~FatalFailureInSetUpTest() {
439    Deinit();
440  }
441
442  virtual void SetUp() {
443    printf("(expecting 3 failures)\n");
444    FAIL() << "Expected failure #1, in SetUp().";
445  }
446
447  virtual void TearDown() {
448    FAIL() << "Expected failure #2, in TearDown().";
449  }
450 private:
451  void Deinit() {
452    FAIL() << "Expected failure #3, in the test fixture d'tor.";
453  }
454};
455
456TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
457  FAIL() << "UNEXPECTED failure in the test function.  "
458         << "We should never get here, as SetUp() failed.";
459}
460
461TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {
462  ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc";
463}
464
465#if GTEST_IS_THREADSAFE
466
467// A unary function that may die.
468void DieIf(bool should_die) {
469  GTEST_CHECK_(!should_die) << " - death inside DieIf().";
470}
471
472// Tests running death tests in a multi-threaded context.
473
474// Used for coordination between the main and the spawn thread.
475struct SpawnThreadNotifications {
476  SpawnThreadNotifications() {}
477
478  Notification spawn_thread_started;
479  Notification spawn_thread_ok_to_terminate;
480
481 private:
482  GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
483};
484
485// The function to be executed in the thread spawn by the
486// MultipleThreads test (below).
487static void ThreadRoutine(SpawnThreadNotifications* notifications) {
488  // Signals the main thread that this thread has started.
489  notifications->spawn_thread_started.Notify();
490
491  // Waits for permission to finish from the main thread.
492  notifications->spawn_thread_ok_to_terminate.WaitForNotification();
493}
494
495// This is a death-test test, but it's not named with a DeathTest
496// suffix.  It starts threads which might interfere with later
497// death tests, so it must run after all other death tests.
498class DeathTestAndMultiThreadsTest : public testing::Test {
499 protected:
500  // Starts a thread and waits for it to begin.
501  virtual void SetUp() {
502    thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
503        &ThreadRoutine, &notifications_, NULL));
504    notifications_.spawn_thread_started.WaitForNotification();
505  }
506  // Tells the thread to finish, and reaps it.
507  // Depending on the version of the thread library in use,
508  // a manager thread might still be left running that will interfere
509  // with later death tests.  This is unfortunate, but this class
510  // cleans up after itself as best it can.
511  virtual void TearDown() {
512    notifications_.spawn_thread_ok_to_terminate.Notify();
513  }
514
515 private:
516  SpawnThreadNotifications notifications_;
517  testing::internal::scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> >
518      thread_;
519};
520
521#endif  // GTEST_IS_THREADSAFE
522
523// The MixedUpTestCaseTest test case verifies that Google Test will fail a
524// test if it uses a different fixture class than what other tests in
525// the same test case use.  It deliberately contains two fixture
526// classes with the same name but defined in different namespaces.
527
528// The MixedUpTestCaseWithSameTestNameTest test case verifies that
529// when the user defines two tests with the same test case name AND
530// same test name (but in different namespaces), the second test will
531// fail.
532
533namespace foo {
534
535class MixedUpTestCaseTest : public testing::Test {
536};
537
538TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {}
539TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {}
540
541class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
542};
543
544TEST_F(MixedUpTestCaseWithSameTestNameTest,
545       TheSecondTestWithThisNameShouldFail) {}
546
547}  // namespace foo
548
549namespace bar {
550
551class MixedUpTestCaseTest : public testing::Test {
552};
553
554// The following two tests are expected to fail.  We rely on the
555// golden file to check that Google Test generates the right error message.
556TEST_F(MixedUpTestCaseTest, ThisShouldFail) {}
557TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {}
558
559class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
560};
561
562// Expected to fail.  We rely on the golden file to check that Google Test
563// generates the right error message.
564TEST_F(MixedUpTestCaseWithSameTestNameTest,
565       TheSecondTestWithThisNameShouldFail) {}
566
567}  // namespace bar
568
569// The following two test cases verify that Google Test catches the user
570// error of mixing TEST and TEST_F in the same test case.  The first
571// test case checks the scenario where TEST_F appears before TEST, and
572// the second one checks where TEST appears before TEST_F.
573
574class TEST_F_before_TEST_in_same_test_case : public testing::Test {
575};
576
577TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
578
579// Expected to fail.  We rely on the golden file to check that Google Test
580// generates the right error message.
581TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
582
583class TEST_before_TEST_F_in_same_test_case : public testing::Test {
584};
585
586TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
587
588// Expected to fail.  We rely on the golden file to check that Google Test
589// generates the right error message.
590TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {
591}
592
593// Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
594int global_integer = 0;
595
596// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
597TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
598  global_integer = 0;
599  EXPECT_NONFATAL_FAILURE({
600    EXPECT_EQ(1, global_integer) << "Expected non-fatal failure.";
601  }, "Expected non-fatal failure.");
602}
603
604// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
605// (static or not).
606TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
607  int m = 0;
608  static int n;
609  n = 1;
610  EXPECT_NONFATAL_FAILURE({
611    EXPECT_EQ(m, n) << "Expected non-fatal failure.";
612  }, "Expected non-fatal failure.");
613}
614
615// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
616// one non-fatal failure and no fatal failure.
617TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
618  EXPECT_NONFATAL_FAILURE({
619    ADD_FAILURE() << "Expected non-fatal failure.";
620  }, "Expected non-fatal failure.");
621}
622
623// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
624// non-fatal failure.
625TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
626  printf("(expecting a failure)\n");
627  EXPECT_NONFATAL_FAILURE({
628  }, "");
629}
630
631// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
632// non-fatal failures.
633TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
634  printf("(expecting a failure)\n");
635  EXPECT_NONFATAL_FAILURE({
636    ADD_FAILURE() << "Expected non-fatal failure 1.";
637    ADD_FAILURE() << "Expected non-fatal failure 2.";
638  }, "");
639}
640
641// Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
642// failure.
643TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
644  printf("(expecting a failure)\n");
645  EXPECT_NONFATAL_FAILURE({
646    FAIL() << "Expected fatal failure.";
647  }, "");
648}
649
650// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
651// tested returns.
652TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
653  printf("(expecting a failure)\n");
654  EXPECT_NONFATAL_FAILURE({
655    return;
656  }, "");
657}
658
659#if GTEST_HAS_EXCEPTIONS
660
661// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
662// tested throws.
663TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
664  printf("(expecting a failure)\n");
665  try {
666    EXPECT_NONFATAL_FAILURE({
667      throw 0;
668    }, "");
669  } catch(int) {  // NOLINT
670  }
671}
672
673#endif  // GTEST_HAS_EXCEPTIONS
674
675// Tests that EXPECT_FATAL_FAILURE() can reference global variables.
676TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
677  global_integer = 0;
678  EXPECT_FATAL_FAILURE({
679    ASSERT_EQ(1, global_integer) << "Expected fatal failure.";
680  }, "Expected fatal failure.");
681}
682
683// Tests that EXPECT_FATAL_FAILURE() can reference local static
684// variables.
685TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
686  static int n;
687  n = 1;
688  EXPECT_FATAL_FAILURE({
689    ASSERT_EQ(0, n) << "Expected fatal failure.";
690  }, "Expected fatal failure.");
691}
692
693// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
694// one fatal failure and no non-fatal failure.
695TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
696  EXPECT_FATAL_FAILURE({
697    FAIL() << "Expected fatal failure.";
698  }, "Expected fatal failure.");
699}
700
701// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
702// failure.
703TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
704  printf("(expecting a failure)\n");
705  EXPECT_FATAL_FAILURE({
706  }, "");
707}
708
709// A helper for generating a fatal failure.
710void FatalFailure() {
711  FAIL() << "Expected fatal failure.";
712}
713
714// Tests that EXPECT_FATAL_FAILURE() fails when there are two
715// fatal failures.
716TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
717  printf("(expecting a failure)\n");
718  EXPECT_FATAL_FAILURE({
719    FatalFailure();
720    FatalFailure();
721  }, "");
722}
723
724// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
725// failure.
726TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
727  printf("(expecting a failure)\n");
728  EXPECT_FATAL_FAILURE({
729    ADD_FAILURE() << "Expected non-fatal failure.";
730  }, "");
731}
732
733// Tests that EXPECT_FATAL_FAILURE() fails when the statement being
734// tested returns.
735TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
736  printf("(expecting a failure)\n");
737  EXPECT_FATAL_FAILURE({
738    return;
739  }, "");
740}
741
742#if GTEST_HAS_EXCEPTIONS
743
744// Tests that EXPECT_FATAL_FAILURE() fails when the statement being
745// tested throws.
746TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
747  printf("(expecting a failure)\n");
748  try {
749    EXPECT_FATAL_FAILURE({
750      throw 0;
751    }, "");
752  } catch(int) {  // NOLINT
753  }
754}
755
756#endif  // GTEST_HAS_EXCEPTIONS
757
758// This #ifdef block tests the output of value-parameterized tests.
759
760#if GTEST_HAS_PARAM_TEST
761
762std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
763  return info.param;
764}
765
766class ParamTest : public testing::TestWithParam<std::string> {
767};
768
769TEST_P(ParamTest, Success) {
770  EXPECT_EQ("a", GetParam());
771}
772
773TEST_P(ParamTest, Failure) {
774  EXPECT_EQ("b", GetParam()) << "Expected failure";
775}
776
777INSTANTIATE_TEST_CASE_P(PrintingStrings,
778                        ParamTest,
779                        testing::Values(std::string("a")),
780                        ParamNameFunc);
781
782#endif  // GTEST_HAS_PARAM_TEST
783
784// This #ifdef block tests the output of typed tests.
785#if GTEST_HAS_TYPED_TEST
786
787template <typename T>
788class TypedTest : public testing::Test {
789};
790
791TYPED_TEST_CASE(TypedTest, testing::Types<int>);
792
793TYPED_TEST(TypedTest, Success) {
794  EXPECT_EQ(0, TypeParam());
795}
796
797TYPED_TEST(TypedTest, Failure) {
798  EXPECT_EQ(1, TypeParam()) << "Expected failure";
799}
800
801#endif  // GTEST_HAS_TYPED_TEST
802
803// This #ifdef block tests the output of type-parameterized tests.
804#if GTEST_HAS_TYPED_TEST_P
805
806template <typename T>
807class TypedTestP : public testing::Test {
808};
809
810TYPED_TEST_CASE_P(TypedTestP);
811
812TYPED_TEST_P(TypedTestP, Success) {
813  EXPECT_EQ(0U, TypeParam());
814}
815
816TYPED_TEST_P(TypedTestP, Failure) {
817  EXPECT_EQ(1U, TypeParam()) << "Expected failure";
818}
819
820REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure);
821
822typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
823INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes);
824
825#endif  // GTEST_HAS_TYPED_TEST_P
826
827#if GTEST_HAS_DEATH_TEST
828
829// We rely on the golden file to verify that tests whose test case
830// name ends with DeathTest are run first.
831
832TEST(ADeathTest, ShouldRunFirst) {
833}
834
835# if GTEST_HAS_TYPED_TEST
836
837// We rely on the golden file to verify that typed tests whose test
838// case name ends with DeathTest are run first.
839
840template <typename T>
841class ATypedDeathTest : public testing::Test {
842};
843
844typedef testing::Types<int, double> NumericTypes;
845TYPED_TEST_CASE(ATypedDeathTest, NumericTypes);
846
847TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {
848}
849
850# endif  // GTEST_HAS_TYPED_TEST
851
852# if GTEST_HAS_TYPED_TEST_P
853
854
855// We rely on the golden file to verify that type-parameterized tests
856// whose test case name ends with DeathTest are run first.
857
858template <typename T>
859class ATypeParamDeathTest : public testing::Test {
860};
861
862TYPED_TEST_CASE_P(ATypeParamDeathTest);
863
864TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {
865}
866
867REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst);
868
869INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes);
870
871# endif  // GTEST_HAS_TYPED_TEST_P
872
873#endif  // GTEST_HAS_DEATH_TEST
874
875// Tests various failure conditions of
876// EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
877class ExpectFailureTest : public testing::Test {
878 public:  // Must be public and not protected due to a bug in g++ 3.4.2.
879  enum FailureMode {
880    FATAL_FAILURE,
881    NONFATAL_FAILURE
882  };
883  static void AddFailure(FailureMode failure) {
884    if (failure == FATAL_FAILURE) {
885      FAIL() << "Expected fatal failure.";
886    } else {
887      ADD_FAILURE() << "Expected non-fatal failure.";
888    }
889  }
890};
891
892TEST_F(ExpectFailureTest, ExpectFatalFailure) {
893  // Expected fatal failure, but succeeds.
894  printf("(expecting 1 failure)\n");
895  EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
896  // Expected fatal failure, but got a non-fatal failure.
897  printf("(expecting 1 failure)\n");
898  EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal "
899                       "failure.");
900  // Wrong message.
901  printf("(expecting 1 failure)\n");
902  EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure "
903                       "expected.");
904}
905
906TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
907  // Expected non-fatal failure, but succeeds.
908  printf("(expecting 1 failure)\n");
909  EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
910  // Expected non-fatal failure, but got a fatal failure.
911  printf("(expecting 1 failure)\n");
912  EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
913  // Wrong message.
914  printf("(expecting 1 failure)\n");
915  EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal "
916                          "failure.");
917}
918
919#if GTEST_IS_THREADSAFE
920
921class ExpectFailureWithThreadsTest : public ExpectFailureTest {
922 protected:
923  static void AddFailureInOtherThread(FailureMode failure) {
924    ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
925    thread.Join();
926  }
927};
928
929TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {
930  // We only intercept the current thread.
931  printf("(expecting 2 failures)\n");
932  EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),
933                       "Expected fatal failure.");
934}
935
936TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {
937  // We only intercept the current thread.
938  printf("(expecting 2 failures)\n");
939  EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),
940                          "Expected non-fatal failure.");
941}
942
943typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
944
945// Tests that the ScopedFakeTestPartResultReporter only catches failures from
946// the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
947TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {
948  printf("(expecting 2 failures)\n");
949  TestPartResultArray results;
950  {
951    ScopedFakeTestPartResultReporter reporter(
952        ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
953        &results);
954    AddFailureInOtherThread(FATAL_FAILURE);
955    AddFailureInOtherThread(NONFATAL_FAILURE);
956  }
957  // The two failures should not have been intercepted.
958  EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
959}
960
961#endif  // GTEST_IS_THREADSAFE
962
963TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
964  // Expected fatal failure, but succeeds.
965  printf("(expecting 1 failure)\n");
966  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
967  // Expected fatal failure, but got a non-fatal failure.
968  printf("(expecting 1 failure)\n");
969  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
970                                      "Expected non-fatal failure.");
971  // Wrong message.
972  printf("(expecting 1 failure)\n");
973  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
974                                      "Some other fatal failure expected.");
975}
976
977TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
978  // Expected non-fatal failure, but succeeds.
979  printf("(expecting 1 failure)\n");
980  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal "
981                                         "failure.");
982  // Expected non-fatal failure, but got a fatal failure.
983  printf("(expecting 1 failure)\n");
984  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
985                                         "Expected fatal failure.");
986  // Wrong message.
987  printf("(expecting 1 failure)\n");
988  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
989                                         "Some other non-fatal failure.");
990}
991
992
993// Two test environments for testing testing::AddGlobalTestEnvironment().
994
995class FooEnvironment : public testing::Environment {
996 public:
997  virtual void SetUp() {
998    printf("%s", "FooEnvironment::SetUp() called.\n");
999  }
1000
1001  virtual void TearDown() {
1002    printf("%s", "FooEnvironment::TearDown() called.\n");
1003    FAIL() << "Expected fatal failure.";
1004  }
1005};
1006
1007class BarEnvironment : public testing::Environment {
1008 public:
1009  virtual void SetUp() {
1010    printf("%s", "BarEnvironment::SetUp() called.\n");
1011  }
1012
1013  virtual void TearDown() {
1014    printf("%s", "BarEnvironment::TearDown() called.\n");
1015    ADD_FAILURE() << "Expected non-fatal failure.";
1016  }
1017};
1018
1019// The main function.
1020//
1021// The idea is to use Google Test to run all the tests we have defined (some
1022// of them are intended to fail), and then compare the test results
1023// with the "golden" file.
1024int main(int argc, char **argv) {
1025  testing::GTEST_FLAG(print_time) = false;
1026
1027  // We just run the tests, knowing some of them are intended to fail.
1028  // We will use a separate Python script to compare the output of
1029  // this program with the golden file.
1030
1031  // It's hard to test InitGoogleTest() directly, as it has many
1032  // global side effects.  The following line serves as a sanity test
1033  // for it.
1034  testing::InitGoogleTest(&argc, argv);
1035  bool internal_skip_environment_and_ad_hoc_tests =
1036      std::count(argv, argv + argc,
1037                 std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
1038
1039#if GTEST_HAS_DEATH_TEST
1040  if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
1041    // Skip the usual output capturing if we're running as the child
1042    // process of an threadsafe-style death test.
1043# if GTEST_OS_WINDOWS
1044    posix::FReopen("nul:", "w", stdout);
1045# else
1046    posix::FReopen("/dev/null", "w", stdout);
1047# endif  // GTEST_OS_WINDOWS
1048    return RUN_ALL_TESTS();
1049  }
1050#endif  // GTEST_HAS_DEATH_TEST
1051
1052  if (internal_skip_environment_and_ad_hoc_tests)
1053    return RUN_ALL_TESTS();
1054
1055  // Registers two global test environments.
1056  // The golden file verifies that they are set up in the order they
1057  // are registered, and torn down in the reverse order.
1058  testing::AddGlobalTestEnvironment(new FooEnvironment);
1059  testing::AddGlobalTestEnvironment(new BarEnvironment);
1060
1061  return RunAllTests();
1062}
trunk/3rdparty/googletest/googletest/test/gtest_output_test_golden_lin.txt
r0r249096
1The non-test part of the code is expected to have 2 failures.
2
3gtest_output_test_.cc:#: Failure
4Value of: false
5  Actual: false
6Expected: true
7gtest_output_test_.cc:#: Failure
8Value of: 3
9Expected: 2
10[==========] Running 66 tests from 29 test cases.
11[----------] Global test environment set-up.
12FooEnvironment::SetUp() called.
13BarEnvironment::SetUp() called.
14[----------] 1 test from ADeathTest
15[ RUN      ] ADeathTest.ShouldRunFirst
16[       OK ] ADeathTest.ShouldRunFirst
17[----------] 1 test from ATypedDeathTest/0, where TypeParam = int
18[ RUN      ] ATypedDeathTest/0.ShouldRunFirst
19[       OK ] ATypedDeathTest/0.ShouldRunFirst
20[----------] 1 test from ATypedDeathTest/1, where TypeParam = double
21[ RUN      ] ATypedDeathTest/1.ShouldRunFirst
22[       OK ] ATypedDeathTest/1.ShouldRunFirst
23[----------] 1 test from My/ATypeParamDeathTest/0, where TypeParam = int
24[ RUN      ] My/ATypeParamDeathTest/0.ShouldRunFirst
25[       OK ] My/ATypeParamDeathTest/0.ShouldRunFirst
26[----------] 1 test from My/ATypeParamDeathTest/1, where TypeParam = double
27[ RUN      ] My/ATypeParamDeathTest/1.ShouldRunFirst
28[       OK ] My/ATypeParamDeathTest/1.ShouldRunFirst
29[----------] 2 tests from PassingTest
30[ RUN      ] PassingTest.PassingTest1
31[       OK ] PassingTest.PassingTest1
32[ RUN      ] PassingTest.PassingTest2
33[       OK ] PassingTest.PassingTest2
34[----------] 2 tests from NonfatalFailureTest
35[ RUN      ] NonfatalFailureTest.EscapesStringOperands
36gtest_output_test_.cc:#: Failure
37Value of: actual
38  Actual: "actual \"string\""
39Expected: kGoldenString
40Which is: "\"Line"
41gtest_output_test_.cc:#: Failure
42Value of: actual
43  Actual: "actual \"string\""
44Expected: golden
45Which is: "\"Line"
46[  FAILED  ] NonfatalFailureTest.EscapesStringOperands
47[ RUN      ] NonfatalFailureTest.DiffForLongStrings
48gtest_output_test_.cc:#: Failure
49Value of: "Line 2"
50Expected: golden_str
51Which is: "\"Line\0 1\"\nLine 2"
52With diff:
53@@ -1,2 @@
54-\"Line\0 1\"
55 Line 2
56
57[  FAILED  ] NonfatalFailureTest.DiffForLongStrings
58[----------] 3 tests from FatalFailureTest
59[ RUN      ] FatalFailureTest.FatalFailureInSubroutine
60(expecting a failure that x should be 1)
61gtest_output_test_.cc:#: Failure
62Value of: x
63  Actual: 2
64Expected: 1
65[  FAILED  ] FatalFailureTest.FatalFailureInSubroutine
66[ RUN      ] FatalFailureTest.FatalFailureInNestedSubroutine
67(expecting a failure that x should be 1)
68gtest_output_test_.cc:#: Failure
69Value of: x
70  Actual: 2
71Expected: 1
72[  FAILED  ] FatalFailureTest.FatalFailureInNestedSubroutine
73[ RUN      ] FatalFailureTest.NonfatalFailureInSubroutine
74(expecting a failure on false)
75gtest_output_test_.cc:#: Failure
76Value of: false
77  Actual: false
78Expected: true
79[  FAILED  ] FatalFailureTest.NonfatalFailureInSubroutine
80[----------] 1 test from LoggingTest
81[ RUN      ] LoggingTest.InterleavingLoggingAndAssertions
82(expecting 2 failures on (3) >= (a[i]))
83i == 0
84i == 1
85gtest_output_test_.cc:#: Failure
86Expected: (3) >= (a[i]), actual: 3 vs 9
87i == 2
88i == 3
89gtest_output_test_.cc:#: Failure
90Expected: (3) >= (a[i]), actual: 3 vs 6
91[  FAILED  ] LoggingTest.InterleavingLoggingAndAssertions
92[----------] 6 tests from SCOPED_TRACETest
93[ RUN      ] SCOPED_TRACETest.ObeysScopes
94(expected to fail)
95gtest_output_test_.cc:#: Failure
96Failed
97This failure is expected, and shouldn't have a trace.
98gtest_output_test_.cc:#: Failure
99Failed
100This failure is expected, and should have a trace.
101Google Test trace:
102gtest_output_test_.cc:#: Expected trace
103gtest_output_test_.cc:#: Failure
104Failed
105This failure is expected, and shouldn't have a trace.
106[  FAILED  ] SCOPED_TRACETest.ObeysScopes
107[ RUN      ] SCOPED_TRACETest.WorksInLoop
108(expected to fail)
109gtest_output_test_.cc:#: Failure
110Value of: n
111  Actual: 1
112Expected: 2
113Google Test trace:
114gtest_output_test_.cc:#: i = 1
115gtest_output_test_.cc:#: Failure
116Value of: n
117  Actual: 2
118Expected: 1
119Google Test trace:
120gtest_output_test_.cc:#: i = 2
121[  FAILED  ] SCOPED_TRACETest.WorksInLoop
122[ RUN      ] SCOPED_TRACETest.WorksInSubroutine
123(expected to fail)
124gtest_output_test_.cc:#: Failure
125Value of: n
126  Actual: 1
127Expected: 2
128Google Test trace:
129gtest_output_test_.cc:#: n = 1
130gtest_output_test_.cc:#: Failure
131Value of: n
132  Actual: 2
133Expected: 1
134Google Test trace:
135gtest_output_test_.cc:#: n = 2
136[  FAILED  ] SCOPED_TRACETest.WorksInSubroutine
137[ RUN      ] SCOPED_TRACETest.CanBeNested
138(expected to fail)
139gtest_output_test_.cc:#: Failure
140Value of: n
141  Actual: 2
142Expected: 1
143Google Test trace:
144gtest_output_test_.cc:#: n = 2
145gtest_output_test_.cc:#:
146[  FAILED  ] SCOPED_TRACETest.CanBeNested
147[ RUN      ] SCOPED_TRACETest.CanBeRepeated
148(expected to fail)
149gtest_output_test_.cc:#: Failure
150Failed
151This failure is expected, and should contain trace point A.
152Google Test trace:
153gtest_output_test_.cc:#: A
154gtest_output_test_.cc:#: Failure
155Failed
156This failure is expected, and should contain trace point A and B.
157Google Test trace:
158gtest_output_test_.cc:#: B
159gtest_output_test_.cc:#: A
160gtest_output_test_.cc:#: Failure
161Failed
162This failure is expected, and should contain trace point A, B, and C.
163Google Test trace:
164gtest_output_test_.cc:#: C
165gtest_output_test_.cc:#: B
166gtest_output_test_.cc:#: A
167gtest_output_test_.cc:#: Failure
168Failed
169This failure is expected, and should contain trace point A, B, and D.
170Google Test trace:
171gtest_output_test_.cc:#: D
172gtest_output_test_.cc:#: B
173gtest_output_test_.cc:#: A
174[  FAILED  ] SCOPED_TRACETest.CanBeRepeated
175[ RUN      ] SCOPED_TRACETest.WorksConcurrently
176(expecting 6 failures)
177gtest_output_test_.cc:#: Failure
178Failed
179Expected failure #1 (in thread B, only trace B alive).
180Google Test trace:
181gtest_output_test_.cc:#: Trace B
182gtest_output_test_.cc:#: Failure
183Failed
184Expected failure #2 (in thread A, trace A & B both alive).
185Google Test trace:
186gtest_output_test_.cc:#: Trace A
187gtest_output_test_.cc:#: Failure
188Failed
189Expected failure #3 (in thread B, trace A & B both alive).
190Google Test trace:
191gtest_output_test_.cc:#: Trace B
192gtest_output_test_.cc:#: Failure
193Failed
194Expected failure #4 (in thread B, only trace A alive).
195gtest_output_test_.cc:#: Failure
196Failed
197Expected failure #5 (in thread A, only trace A alive).
198Google Test trace:
199gtest_output_test_.cc:#: Trace A
200gtest_output_test_.cc:#: Failure
201Failed
202Expected failure #6 (in thread A, no trace alive).
203[  FAILED  ] SCOPED_TRACETest.WorksConcurrently
204[----------] 1 test from NonFatalFailureInFixtureConstructorTest
205[ RUN      ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
206(expecting 5 failures)
207gtest_output_test_.cc:#: Failure
208Failed
209Expected failure #1, in the test fixture c'tor.
210gtest_output_test_.cc:#: Failure
211Failed
212Expected failure #2, in SetUp().
213gtest_output_test_.cc:#: Failure
214Failed
215Expected failure #3, in the test body.
216gtest_output_test_.cc:#: Failure
217Failed
218Expected failure #4, in TearDown.
219gtest_output_test_.cc:#: Failure
220Failed
221Expected failure #5, in the test fixture d'tor.
222[  FAILED  ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
223[----------] 1 test from FatalFailureInFixtureConstructorTest
224[ RUN      ] FatalFailureInFixtureConstructorTest.FailureInConstructor
225(expecting 2 failures)
226gtest_output_test_.cc:#: Failure
227Failed
228Expected failure #1, in the test fixture c'tor.
229gtest_output_test_.cc:#: Failure
230Failed
231Expected failure #2, in the test fixture d'tor.
232[  FAILED  ] FatalFailureInFixtureConstructorTest.FailureInConstructor
233[----------] 1 test from NonFatalFailureInSetUpTest
234[ RUN      ] NonFatalFailureInSetUpTest.FailureInSetUp
235(expecting 4 failures)
236gtest_output_test_.cc:#: Failure
237Failed
238Expected failure #1, in SetUp().
239gtest_output_test_.cc:#: Failure
240Failed
241Expected failure #2, in the test function.
242gtest_output_test_.cc:#: Failure
243Failed
244Expected failure #3, in TearDown().
245gtest_output_test_.cc:#: Failure
246Failed
247Expected failure #4, in the test fixture d'tor.
248[  FAILED  ] NonFatalFailureInSetUpTest.FailureInSetUp
249[----------] 1 test from FatalFailureInSetUpTest
250[ RUN      ] FatalFailureInSetUpTest.FailureInSetUp
251(expecting 3 failures)
252gtest_output_test_.cc:#: Failure
253Failed
254Expected failure #1, in SetUp().
255gtest_output_test_.cc:#: Failure
256Failed
257Expected failure #2, in TearDown().
258gtest_output_test_.cc:#: Failure
259Failed
260Expected failure #3, in the test fixture d'tor.
261[  FAILED  ] FatalFailureInSetUpTest.FailureInSetUp
262[----------] 1 test from AddFailureAtTest
263[ RUN      ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber
264foo.cc:42: Failure
265Failed
266Expected failure in foo.cc
267[  FAILED  ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber
268[----------] 4 tests from MixedUpTestCaseTest
269[ RUN      ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo
270[       OK ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo
271[ RUN      ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo
272[       OK ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo
273[ RUN      ] MixedUpTestCaseTest.ThisShouldFail
274gtest.cc:#: Failure
275Failed
276All tests in the same test case must use the same test fixture
277class.  However, in test case MixedUpTestCaseTest,
278you defined test FirstTestFromNamespaceFoo and test ThisShouldFail
279using two different test fixture classes.  This can happen if
280the two classes are from different namespaces or translation
281units and have the same name.  You should probably rename one
282of the classes to put the tests into different test cases.
283[  FAILED  ] MixedUpTestCaseTest.ThisShouldFail
284[ RUN      ] MixedUpTestCaseTest.ThisShouldFailToo
285gtest.cc:#: Failure
286Failed
287All tests in the same test case must use the same test fixture
288class.  However, in test case MixedUpTestCaseTest,
289you defined test FirstTestFromNamespaceFoo and test ThisShouldFailToo
290using two different test fixture classes.  This can happen if
291the two classes are from different namespaces or translation
292units and have the same name.  You should probably rename one
293of the classes to put the tests into different test cases.
294[  FAILED  ] MixedUpTestCaseTest.ThisShouldFailToo
295[----------] 2 tests from MixedUpTestCaseWithSameTestNameTest
296[ RUN      ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
297[       OK ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
298[ RUN      ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
299gtest.cc:#: Failure
300Failed
301All tests in the same test case must use the same test fixture
302class.  However, in test case MixedUpTestCaseWithSameTestNameTest,
303you defined test TheSecondTestWithThisNameShouldFail and test TheSecondTestWithThisNameShouldFail
304using two different test fixture classes.  This can happen if
305the two classes are from different namespaces or translation
306units and have the same name.  You should probably rename one
307of the classes to put the tests into different test cases.
308[  FAILED  ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
309[----------] 2 tests from TEST_F_before_TEST_in_same_test_case
310[ RUN      ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F
311[       OK ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F
312[ RUN      ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
313gtest.cc:#: Failure
314Failed
315All tests in the same test case must use the same test fixture
316class, so mixing TEST_F and TEST in the same test case is
317illegal.  In test case TEST_F_before_TEST_in_same_test_case,
318test DefinedUsingTEST_F is defined using TEST_F but
319test DefinedUsingTESTAndShouldFail is defined using TEST.  You probably
320want to change the TEST to TEST_F or move it to another test
321case.
322[  FAILED  ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
323[----------] 2 tests from TEST_before_TEST_F_in_same_test_case
324[ RUN      ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST
325[       OK ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST
326[ RUN      ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
327gtest.cc:#: Failure
328Failed
329All tests in the same test case must use the same test fixture
330class, so mixing TEST_F and TEST in the same test case is
331illegal.  In test case TEST_before_TEST_F_in_same_test_case,
332test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but
333test DefinedUsingTEST is defined using TEST.  You probably
334want to change the TEST to TEST_F or move it to another test
335case.
336[  FAILED  ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
337[----------] 8 tests from ExpectNonfatalFailureTest
338[ RUN      ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables
339[       OK ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables
340[ RUN      ] ExpectNonfatalFailureTest.CanReferenceLocalVariables
341[       OK ] ExpectNonfatalFailureTest.CanReferenceLocalVariables
342[ RUN      ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure
343[       OK ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure
344[ RUN      ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
345(expecting a failure)
346gtest.cc:#: Failure
347Expected: 1 non-fatal failure
348  Actual: 0 failures
349[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
350[ RUN      ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
351(expecting a failure)
352gtest.cc:#: Failure
353Expected: 1 non-fatal failure
354  Actual: 2 failures
355gtest_output_test_.cc:#: Non-fatal failure:
356Failed
357Expected non-fatal failure 1.
358
359gtest_output_test_.cc:#: Non-fatal failure:
360Failed
361Expected non-fatal failure 2.
362
363[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
364[ RUN      ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
365(expecting a failure)
366gtest.cc:#: Failure
367Expected: 1 non-fatal failure
368  Actual:
369gtest_output_test_.cc:#: Fatal failure:
370Failed
371Expected fatal failure.
372
373[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
374[ RUN      ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
375(expecting a failure)
376gtest.cc:#: Failure
377Expected: 1 non-fatal failure
378  Actual: 0 failures
379[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
380[ RUN      ] ExpectNonfatalFailureTest.FailsWhenStatementThrows
381(expecting a failure)
382gtest.cc:#: Failure
383Expected: 1 non-fatal failure
384  Actual: 0 failures
385[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenStatementThrows
386[----------] 8 tests from ExpectFatalFailureTest
387[ RUN      ] ExpectFatalFailureTest.CanReferenceGlobalVariables
388[       OK ] ExpectFatalFailureTest.CanReferenceGlobalVariables
389[ RUN      ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables
390[       OK ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables
391[ RUN      ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure
392[       OK ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure
393[ RUN      ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
394(expecting a failure)
395gtest.cc:#: Failure
396Expected: 1 fatal failure
397  Actual: 0 failures
398[  FAILED  ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
399[ RUN      ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
400(expecting a failure)
401gtest.cc:#: Failure
402Expected: 1 fatal failure
403  Actual: 2 failures
404gtest_output_test_.cc:#: Fatal failure:
405Failed
406Expected fatal failure.
407
408gtest_output_test_.cc:#: Fatal failure:
409Failed
410Expected fatal failure.
411
412[  FAILED  ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
413[ RUN      ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
414(expecting a failure)
415gtest.cc:#: Failure
416Expected: 1 fatal failure
417  Actual:
418gtest_output_test_.cc:#: Non-fatal failure:
419Failed
420Expected non-fatal failure.
421
422[  FAILED  ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
423[ RUN      ] ExpectFatalFailureTest.FailsWhenStatementReturns
424(expecting a failure)
425gtest.cc:#: Failure
426Expected: 1 fatal failure
427  Actual: 0 failures
428[  FAILED  ] ExpectFatalFailureTest.FailsWhenStatementReturns
429[ RUN      ] ExpectFatalFailureTest.FailsWhenStatementThrows
430(expecting a failure)
431gtest.cc:#: Failure
432Expected: 1 fatal failure
433  Actual: 0 failures
434[  FAILED  ] ExpectFatalFailureTest.FailsWhenStatementThrows
435[----------] 2 tests from TypedTest/0, where TypeParam = int
436[ RUN      ] TypedTest/0.Success
437[       OK ] TypedTest/0.Success
438[ RUN      ] TypedTest/0.Failure
439gtest_output_test_.cc:#: Failure
440Value of: TypeParam()
441  Actual: 0
442Expected: 1
443Expected failure
444[  FAILED  ] TypedTest/0.Failure, where TypeParam = int
445[----------] 2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char
446[ RUN      ] Unsigned/TypedTestP/0.Success
447[       OK ] Unsigned/TypedTestP/0.Success
448[ RUN      ] Unsigned/TypedTestP/0.Failure
449gtest_output_test_.cc:#: Failure
450Value of: TypeParam()
451  Actual: '\0'
452Expected: 1U
453Which is: 1
454Expected failure
455[  FAILED  ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char
456[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int
457[ RUN      ] Unsigned/TypedTestP/1.Success
458[       OK ] Unsigned/TypedTestP/1.Success
459[ RUN      ] Unsigned/TypedTestP/1.Failure
460gtest_output_test_.cc:#: Failure
461Value of: TypeParam()
462  Actual: 0
463Expected: 1U
464Which is: 1
465Expected failure
466[  FAILED  ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int
467[----------] 4 tests from ExpectFailureTest
468[ RUN      ] ExpectFailureTest.ExpectFatalFailure
469(expecting 1 failure)
470gtest.cc:#: Failure
471Expected: 1 fatal failure
472  Actual:
473gtest_output_test_.cc:#: Success:
474Succeeded
475
476(expecting 1 failure)
477gtest.cc:#: Failure
478Expected: 1 fatal failure
479  Actual:
480gtest_output_test_.cc:#: Non-fatal failure:
481Failed
482Expected non-fatal failure.
483
484(expecting 1 failure)
485gtest.cc:#: Failure
486Expected: 1 fatal failure containing "Some other fatal failure expected."
487  Actual:
488gtest_output_test_.cc:#: Fatal failure:
489Failed
490Expected fatal failure.
491
492[  FAILED  ] ExpectFailureTest.ExpectFatalFailure
493[ RUN      ] ExpectFailureTest.ExpectNonFatalFailure
494(expecting 1 failure)
495gtest.cc:#: Failure
496Expected: 1 non-fatal failure
497  Actual:
498gtest_output_test_.cc:#: Success:
499Succeeded
500
501(expecting 1 failure)
502gtest.cc:#: Failure
503Expected: 1 non-fatal failure
504  Actual:
505gtest_output_test_.cc:#: Fatal failure:
506Failed
507Expected fatal failure.
508
509(expecting 1 failure)
510gtest.cc:#: Failure
511Expected: 1 non-fatal failure containing "Some other non-fatal failure."
512  Actual:
513gtest_output_test_.cc:#: Non-fatal failure:
514Failed
515Expected non-fatal failure.
516
517[  FAILED  ] ExpectFailureTest.ExpectNonFatalFailure
518[ RUN      ] ExpectFailureTest.ExpectFatalFailureOnAllThreads
519(expecting 1 failure)
520gtest.cc:#: Failure
521Expected: 1 fatal failure
522  Actual:
523gtest_output_test_.cc:#: Success:
524Succeeded
525
526(expecting 1 failure)
527gtest.cc:#: Failure
528Expected: 1 fatal failure
529  Actual:
530gtest_output_test_.cc:#: Non-fatal failure:
531Failed
532Expected non-fatal failure.
533
534(expecting 1 failure)
535gtest.cc:#: Failure
536Expected: 1 fatal failure containing "Some other fatal failure expected."
537  Actual:
538gtest_output_test_.cc:#: Fatal failure:
539Failed
540Expected fatal failure.
541
542[  FAILED  ] ExpectFailureTest.ExpectFatalFailureOnAllThreads
543[ RUN      ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads
544(expecting 1 failure)
545gtest.cc:#: Failure
546Expected: 1 non-fatal failure
547  Actual:
548gtest_output_test_.cc:#: Success:
549Succeeded
550
551(expecting 1 failure)
552gtest.cc:#: Failure
553Expected: 1 non-fatal failure
554  Actual:
555gtest_output_test_.cc:#: Fatal failure:
556Failed
557Expected fatal failure.
558
559(expecting 1 failure)
560gtest.cc:#: Failure
561Expected: 1 non-fatal failure containing "Some other non-fatal failure."
562  Actual:
563gtest_output_test_.cc:#: Non-fatal failure:
564Failed
565Expected non-fatal failure.
566
567[  FAILED  ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads
568[----------] 2 tests from ExpectFailureWithThreadsTest
569[ RUN      ] ExpectFailureWithThreadsTest.ExpectFatalFailure
570(expecting 2 failures)
571gtest_output_test_.cc:#: Failure
572Failed
573Expected fatal failure.
574gtest.cc:#: Failure
575Expected: 1 fatal failure
576  Actual: 0 failures
577[  FAILED  ] ExpectFailureWithThreadsTest.ExpectFatalFailure
578[ RUN      ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure
579(expecting 2 failures)
580gtest_output_test_.cc:#: Failure
581Failed
582Expected non-fatal failure.
583gtest.cc:#: Failure
584Expected: 1 non-fatal failure
585  Actual: 0 failures
586[  FAILED  ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure
587[----------] 1 test from ScopedFakeTestPartResultReporterTest
588[ RUN      ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread
589(expecting 2 failures)
590gtest_output_test_.cc:#: Failure
591Failed
592Expected fatal failure.
593gtest_output_test_.cc:#: Failure
594Failed
595Expected non-fatal failure.
596[  FAILED  ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread
597[----------] 1 test from PrintingFailingParams/FailingParamTest
598[ RUN      ] PrintingFailingParams/FailingParamTest.Fails/0
599gtest_output_test_.cc:#: Failure
600Value of: GetParam()
601  Actual: 2
602Expected: 1
603[  FAILED  ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
604[----------] 2 tests from PrintingStrings/ParamTest
605[ RUN      ] PrintingStrings/ParamTest.Success/a
606[       OK ] PrintingStrings/ParamTest.Success/a
607[ RUN      ] PrintingStrings/ParamTest.Failure/a
608gtest_output_test_.cc:#: Failure
609Value of: GetParam()
610  Actual: "a"
611Expected: "b"
612Expected failure
613[  FAILED  ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
614[----------] Global test environment tear-down
615BarEnvironment::TearDown() called.
616gtest_output_test_.cc:#: Failure
617Failed
618Expected non-fatal failure.
619FooEnvironment::TearDown() called.
620gtest_output_test_.cc:#: Failure
621Failed
622Expected fatal failure.
623[==========] 66 tests from 29 test cases ran.
624[  PASSED  ] 22 tests.
625[  FAILED  ] 44 tests, listed below:
626[  FAILED  ] NonfatalFailureTest.EscapesStringOperands
627[  FAILED  ] NonfatalFailureTest.DiffForLongStrings
628[  FAILED  ] FatalFailureTest.FatalFailureInSubroutine
629[  FAILED  ] FatalFailureTest.FatalFailureInNestedSubroutine
630[  FAILED  ] FatalFailureTest.NonfatalFailureInSubroutine
631[  FAILED  ] LoggingTest.InterleavingLoggingAndAssertions
632[  FAILED  ] SCOPED_TRACETest.ObeysScopes
633[  FAILED  ] SCOPED_TRACETest.WorksInLoop
634[  FAILED  ] SCOPED_TRACETest.WorksInSubroutine
635[  FAILED  ] SCOPED_TRACETest.CanBeNested
636[  FAILED  ] SCOPED_TRACETest.CanBeRepeated
637[  FAILED  ] SCOPED_TRACETest.WorksConcurrently
638[  FAILED  ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
639[  FAILED  ] FatalFailureInFixtureConstructorTest.FailureInConstructor
640[  FAILED  ] NonFatalFailureInSetUpTest.FailureInSetUp
641[  FAILED  ] FatalFailureInSetUpTest.FailureInSetUp
642[  FAILED  ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber
643[  FAILED  ] MixedUpTestCaseTest.ThisShouldFail
644[  FAILED  ] MixedUpTestCaseTest.ThisShouldFailToo
645[  FAILED  ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
646[  FAILED  ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
647[  FAILED  ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
648[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
649[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
650[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
651[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
652[  FAILED  ] ExpectNonfatalFailureTest.FailsWhenStatementThrows
653[  FAILED  ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
654[  FAILED  ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
655[  FAILED  ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
656[  FAILED  ] ExpectFatalFailureTest.FailsWhenStatementReturns
657[  FAILED  ] ExpectFatalFailureTest.FailsWhenStatementThrows
658[  FAILED  ] TypedTest/0.Failure, where TypeParam = int
659[  FAILED  ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char
660[  FAILED  ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int
661[  FAILED  ] ExpectFailureTest.ExpectFatalFailure
662[  FAILED  ] ExpectFailureTest.ExpectNonFatalFailure
663[  FAILED  ] ExpectFailureTest.ExpectFatalFailureOnAllThreads
664[  FAILED  ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads
665[  FAILED  ] ExpectFailureWithThreadsTest.ExpectFatalFailure
666[  FAILED  ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure
667[  FAILED  ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread
668[  FAILED  ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
669[  FAILED  ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
670
67144 FAILED TESTS
672  YOU HAVE 1 DISABLED TEST
673
674Note: Google Test filter = FatalFailureTest.*:LoggingTest.*
675[==========] Running 4 tests from 2 test cases.
676[----------] Global test environment set-up.
677[----------] 3 tests from FatalFailureTest
678[ RUN      ] FatalFailureTest.FatalFailureInSubroutine
679(expecting a failure that x should be 1)
680gtest_output_test_.cc:#: Failure
681Value of: x
682  Actual: 2
683Expected: 1
684[  FAILED  ] FatalFailureTest.FatalFailureInSubroutine (? ms)
685[ RUN      ] FatalFailureTest.FatalFailureInNestedSubroutine
686(expecting a failure that x should be 1)
687gtest_output_test_.cc:#: Failure
688Value of: x
689  Actual: 2
690Expected: 1
691[  FAILED  ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms)
692[ RUN      ] FatalFailureTest.NonfatalFailureInSubroutine
693(expecting a failure on false)
694gtest_output_test_.cc:#: Failure
695Value of: false
696  Actual: false
697Expected: true
698[  FAILED  ] FatalFailureTest.NonfatalFailureInSubroutine (? ms)
699[----------] 3 tests from FatalFailureTest (? ms total)
700
701[----------] 1 test from LoggingTest
702[ RUN      ] LoggingTest.InterleavingLoggingAndAssertions
703(expecting 2 failures on (3) >= (a[i]))
704i == 0
705i == 1
706gtest_output_test_.cc:#: Failure
707Expected: (3) >= (a[i]), actual: 3 vs 9
708i == 2
709i == 3
710gtest_output_test_.cc:#: Failure
711Expected: (3) >= (a[i]), actual: 3 vs 6
712[  FAILED  ] LoggingTest.InterleavingLoggingAndAssertions (? ms)
713[----------] 1 test from LoggingTest (? ms total)
714
715[----------] Global test environment tear-down
716[==========] 4 tests from 2 test cases ran. (? ms total)
717[  PASSED  ] 0 tests.
718[  FAILED  ] 4 tests, listed below:
719[  FAILED  ] FatalFailureTest.FatalFailureInSubroutine
720[  FAILED  ] FatalFailureTest.FatalFailureInNestedSubroutine
721[  FAILED  ] FatalFailureTest.NonfatalFailureInSubroutine
722[  FAILED  ] LoggingTest.InterleavingLoggingAndAssertions
723
724 4 FAILED TESTS
725Note: Google Test filter = *DISABLED_*
726[==========] Running 1 test from 1 test case.
727[----------] Global test environment set-up.
728[----------] 1 test from DisabledTestsWarningTest
729[ RUN      ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning
730[       OK ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning
731[----------] Global test environment tear-down
732[==========] 1 test from 1 test case ran.
733[  PASSED  ] 1 test.
734Note: Google Test filter = PassingTest.*
735Note: This is test shard 2 of 2.
736[==========] Running 1 test from 1 test case.
737[----------] Global test environment set-up.
738[----------] 1 test from PassingTest
739[ RUN      ] PassingTest.PassingTest2
740[       OK ] PassingTest.PassingTest2
741[----------] Global test environment tear-down
742[==========] 1 test from 1 test case ran.
743[  PASSED  ] 1 test.
trunk/3rdparty/googletest/googletest/test/gtest_pred_impl_unittest.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command
31// 'gen_gtest_pred_impl.py 5'.  DO NOT EDIT BY HAND!
32
33// Regression test for gtest_pred_impl.h
34//
35// This file is generated by a script and quite long.  If you intend to
36// learn how Google Test works by reading its unit tests, read
37// gtest_unittest.cc instead.
38//
39// This is intended as a regression test for the Google Test predicate
40// assertions.  We compile it as part of the gtest_unittest target
41// only to keep the implementation tidy and compact, as it is quite
42// involved to set up the stage for testing Google Test using Google
43// Test itself.
44//
45// Currently, gtest_unittest takes ~11 seconds to run in the testing
46// daemon.  In the future, if it grows too large and needs much more
47// time to finish, we should consider separating this file into a
48// stand-alone regression test.
49
50#include <iostream>
51
52#include "gtest/gtest.h"
53#include "gtest/gtest-spi.h"
54
55// A user-defined data type.
56struct Bool {
57  explicit Bool(int val) : value(val != 0) {}
58
59  bool operator>(int n) const { return value > Bool(n).value; }
60
61  Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
62
63  bool operator==(const Bool& rhs) const { return value == rhs.value; }
64
65  bool value;
66};
67
68// Enables Bool to be used in assertions.
69std::ostream& operator<<(std::ostream& os, const Bool& x) {
70  return os << (x.value ? "true" : "false");
71}
72
73// Sample functions/functors for testing unary predicate assertions.
74
75// A unary predicate function.
76template <typename T1>
77bool PredFunction1(T1 v1) {
78  return v1 > 0;
79}
80
81// The following two functions are needed to circumvent a bug in
82// gcc 2.95.3, which sometimes has problem with the above template
83// function.
84bool PredFunction1Int(int v1) {
85  return v1 > 0;
86}
87bool PredFunction1Bool(Bool v1) {
88  return v1 > 0;
89}
90
91// A unary predicate functor.
92struct PredFunctor1 {
93  template <typename T1>
94  bool operator()(const T1& v1) {
95    return v1 > 0;
96  }
97};
98
99// A unary predicate-formatter function.
100template <typename T1>
101testing::AssertionResult PredFormatFunction1(const char* e1,
102                                             const T1& v1) {
103  if (PredFunction1(v1))
104    return testing::AssertionSuccess();
105
106  return testing::AssertionFailure()
107      << e1
108      << " is expected to be positive, but evaluates to "
109      << v1 << ".";
110}
111
112// A unary predicate-formatter functor.
113struct PredFormatFunctor1 {
114  template <typename T1>
115  testing::AssertionResult operator()(const char* e1,
116                                      const T1& v1) const {
117    return PredFormatFunction1(e1, v1);
118  }
119};
120
121// Tests for {EXPECT|ASSERT}_PRED_FORMAT1.
122
123class Predicate1Test : public testing::Test {
124 protected:
125  virtual void SetUp() {
126    expected_to_finish_ = true;
127    finished_ = false;
128    n1_ = 0;
129  }
130
131  virtual void TearDown() {
132    // Verifies that each of the predicate's arguments was evaluated
133    // exactly once.
134    EXPECT_EQ(1, n1_) <<
135        "The predicate assertion didn't evaluate argument 2 "
136        "exactly once.";
137
138    // Verifies that the control flow in the test function is expected.
139    if (expected_to_finish_ && !finished_) {
140      FAIL() << "The predicate assertion unexpactedly aborted the test.";
141    } else if (!expected_to_finish_ && finished_) {
142      FAIL() << "The failed predicate assertion didn't abort the test "
143                "as expected.";
144    }
145  }
146
147  // true iff the test function is expected to run to finish.
148  static bool expected_to_finish_;
149
150  // true iff the test function did run to finish.
151  static bool finished_;
152
153  static int n1_;
154};
155
156bool Predicate1Test::expected_to_finish_;
157bool Predicate1Test::finished_;
158int Predicate1Test::n1_;
159
160typedef Predicate1Test EXPECT_PRED_FORMAT1Test;
161typedef Predicate1Test ASSERT_PRED_FORMAT1Test;
162typedef Predicate1Test EXPECT_PRED1Test;
163typedef Predicate1Test ASSERT_PRED1Test;
164
165// Tests a successful EXPECT_PRED1 where the
166// predicate-formatter is a function on a built-in type (int).
167TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeSuccess) {
168  EXPECT_PRED1(PredFunction1Int,
169               ++n1_);
170  finished_ = true;
171}
172
173// Tests a successful EXPECT_PRED1 where the
174// predicate-formatter is a function on a user-defined type (Bool).
175TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeSuccess) {
176  EXPECT_PRED1(PredFunction1Bool,
177               Bool(++n1_));
178  finished_ = true;
179}
180
181// Tests a successful EXPECT_PRED1 where the
182// predicate-formatter is a functor on a built-in type (int).
183TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeSuccess) {
184  EXPECT_PRED1(PredFunctor1(),
185               ++n1_);
186  finished_ = true;
187}
188
189// Tests a successful EXPECT_PRED1 where the
190// predicate-formatter is a functor on a user-defined type (Bool).
191TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeSuccess) {
192  EXPECT_PRED1(PredFunctor1(),
193               Bool(++n1_));
194  finished_ = true;
195}
196
197// Tests a failed EXPECT_PRED1 where the
198// predicate-formatter is a function on a built-in type (int).
199TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeFailure) {
200  EXPECT_NONFATAL_FAILURE({  // NOLINT
201    EXPECT_PRED1(PredFunction1Int,
202                 n1_++);
203    finished_ = true;
204  }, "");
205}
206
207// Tests a failed EXPECT_PRED1 where the
208// predicate-formatter is a function on a user-defined type (Bool).
209TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeFailure) {
210  EXPECT_NONFATAL_FAILURE({  // NOLINT
211    EXPECT_PRED1(PredFunction1Bool,
212                 Bool(n1_++));
213    finished_ = true;
214  }, "");
215}
216
217// Tests a failed EXPECT_PRED1 where the
218// predicate-formatter is a functor on a built-in type (int).
219TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeFailure) {
220  EXPECT_NONFATAL_FAILURE({  // NOLINT
221    EXPECT_PRED1(PredFunctor1(),
222                 n1_++);
223    finished_ = true;
224  }, "");
225}
226
227// Tests a failed EXPECT_PRED1 where the
228// predicate-formatter is a functor on a user-defined type (Bool).
229TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeFailure) {
230  EXPECT_NONFATAL_FAILURE({  // NOLINT
231    EXPECT_PRED1(PredFunctor1(),
232                 Bool(n1_++));
233    finished_ = true;
234  }, "");
235}
236
237// Tests a successful ASSERT_PRED1 where the
238// predicate-formatter is a function on a built-in type (int).
239TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeSuccess) {
240  ASSERT_PRED1(PredFunction1Int,
241               ++n1_);
242  finished_ = true;
243}
244
245// Tests a successful ASSERT_PRED1 where the
246// predicate-formatter is a function on a user-defined type (Bool).
247TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeSuccess) {
248  ASSERT_PRED1(PredFunction1Bool,
249               Bool(++n1_));
250  finished_ = true;
251}
252
253// Tests a successful ASSERT_PRED1 where the
254// predicate-formatter is a functor on a built-in type (int).
255TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeSuccess) {
256  ASSERT_PRED1(PredFunctor1(),
257               ++n1_);
258  finished_ = true;
259}
260
261// Tests a successful ASSERT_PRED1 where the
262// predicate-formatter is a functor on a user-defined type (Bool).
263TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) {
264  ASSERT_PRED1(PredFunctor1(),
265               Bool(++n1_));
266  finished_ = true;
267}
268
269// Tests a failed ASSERT_PRED1 where the
270// predicate-formatter is a function on a built-in type (int).
271TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeFailure) {
272  expected_to_finish_ = false;
273  EXPECT_FATAL_FAILURE({  // NOLINT
274    ASSERT_PRED1(PredFunction1Int,
275                 n1_++);
276    finished_ = true;
277  }, "");
278}
279
280// Tests a failed ASSERT_PRED1 where the
281// predicate-formatter is a function on a user-defined type (Bool).
282TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeFailure) {
283  expected_to_finish_ = false;
284  EXPECT_FATAL_FAILURE({  // NOLINT
285    ASSERT_PRED1(PredFunction1Bool,
286                 Bool(n1_++));
287    finished_ = true;
288  }, "");
289}
290
291// Tests a failed ASSERT_PRED1 where the
292// predicate-formatter is a functor on a built-in type (int).
293TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeFailure) {
294  expected_to_finish_ = false;
295  EXPECT_FATAL_FAILURE({  // NOLINT
296    ASSERT_PRED1(PredFunctor1(),
297                 n1_++);
298    finished_ = true;
299  }, "");
300}
301
302// Tests a failed ASSERT_PRED1 where the
303// predicate-formatter is a functor on a user-defined type (Bool).
304TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeFailure) {
305  expected_to_finish_ = false;
306  EXPECT_FATAL_FAILURE({  // NOLINT
307    ASSERT_PRED1(PredFunctor1(),
308                 Bool(n1_++));
309    finished_ = true;
310  }, "");
311}
312
313// Tests a successful EXPECT_PRED_FORMAT1 where the
314// predicate-formatter is a function on a built-in type (int).
315TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) {
316  EXPECT_PRED_FORMAT1(PredFormatFunction1,
317                      ++n1_);
318  finished_ = true;
319}
320
321// Tests a successful EXPECT_PRED_FORMAT1 where the
322// predicate-formatter is a function on a user-defined type (Bool).
323TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) {
324  EXPECT_PRED_FORMAT1(PredFormatFunction1,
325                      Bool(++n1_));
326  finished_ = true;
327}
328
329// Tests a successful EXPECT_PRED_FORMAT1 where the
330// predicate-formatter is a functor on a built-in type (int).
331TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) {
332  EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
333                      ++n1_);
334  finished_ = true;
335}
336
337// Tests a successful EXPECT_PRED_FORMAT1 where the
338// predicate-formatter is a functor on a user-defined type (Bool).
339TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) {
340  EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
341                      Bool(++n1_));
342  finished_ = true;
343}
344
345// Tests a failed EXPECT_PRED_FORMAT1 where the
346// predicate-formatter is a function on a built-in type (int).
347TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) {
348  EXPECT_NONFATAL_FAILURE({  // NOLINT
349    EXPECT_PRED_FORMAT1(PredFormatFunction1,
350                        n1_++);
351    finished_ = true;
352  }, "");
353}
354
355// Tests a failed EXPECT_PRED_FORMAT1 where the
356// predicate-formatter is a function on a user-defined type (Bool).
357TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) {
358  EXPECT_NONFATAL_FAILURE({  // NOLINT
359    EXPECT_PRED_FORMAT1(PredFormatFunction1,
360                        Bool(n1_++));
361    finished_ = true;
362  }, "");
363}
364
365// Tests a failed EXPECT_PRED_FORMAT1 where the
366// predicate-formatter is a functor on a built-in type (int).
367TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) {
368  EXPECT_NONFATAL_FAILURE({  // NOLINT
369    EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
370                        n1_++);
371    finished_ = true;
372  }, "");
373}
374
375// Tests a failed EXPECT_PRED_FORMAT1 where the
376// predicate-formatter is a functor on a user-defined type (Bool).
377TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) {
378  EXPECT_NONFATAL_FAILURE({  // NOLINT
379    EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
380                        Bool(n1_++));
381    finished_ = true;
382  }, "");
383}
384
385// Tests a successful ASSERT_PRED_FORMAT1 where the
386// predicate-formatter is a function on a built-in type (int).
387TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) {
388  ASSERT_PRED_FORMAT1(PredFormatFunction1,
389                      ++n1_);
390  finished_ = true;
391}
392
393// Tests a successful ASSERT_PRED_FORMAT1 where the
394// predicate-formatter is a function on a user-defined type (Bool).
395TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) {
396  ASSERT_PRED_FORMAT1(PredFormatFunction1,
397                      Bool(++n1_));
398  finished_ = true;
399}
400
401// Tests a successful ASSERT_PRED_FORMAT1 where the
402// predicate-formatter is a functor on a built-in type (int).
403TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) {
404  ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
405                      ++n1_);
406  finished_ = true;
407}
408
409// Tests a successful ASSERT_PRED_FORMAT1 where the
410// predicate-formatter is a functor on a user-defined type (Bool).
411TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) {
412  ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
413                      Bool(++n1_));
414  finished_ = true;
415}
416
417// Tests a failed ASSERT_PRED_FORMAT1 where the
418// predicate-formatter is a function on a built-in type (int).
419TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) {
420  expected_to_finish_ = false;
421  EXPECT_FATAL_FAILURE({  // NOLINT
422    ASSERT_PRED_FORMAT1(PredFormatFunction1,
423                        n1_++);
424    finished_ = true;
425  }, "");
426}
427
428// Tests a failed ASSERT_PRED_FORMAT1 where the
429// predicate-formatter is a function on a user-defined type (Bool).
430TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) {
431  expected_to_finish_ = false;
432  EXPECT_FATAL_FAILURE({  // NOLINT
433    ASSERT_PRED_FORMAT1(PredFormatFunction1,
434                        Bool(n1_++));
435    finished_ = true;
436  }, "");
437}
438
439// Tests a failed ASSERT_PRED_FORMAT1 where the
440// predicate-formatter is a functor on a built-in type (int).
441TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) {
442  expected_to_finish_ = false;
443  EXPECT_FATAL_FAILURE({  // NOLINT
444    ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
445                        n1_++);
446    finished_ = true;
447  }, "");
448}
449
450// Tests a failed ASSERT_PRED_FORMAT1 where the
451// predicate-formatter is a functor on a user-defined type (Bool).
452TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) {
453  expected_to_finish_ = false;
454  EXPECT_FATAL_FAILURE({  // NOLINT
455    ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
456                        Bool(n1_++));
457    finished_ = true;
458  }, "");
459}
460// Sample functions/functors for testing binary predicate assertions.
461
462// A binary predicate function.
463template <typename T1, typename T2>
464bool PredFunction2(T1 v1, T2 v2) {
465  return v1 + v2 > 0;
466}
467
468// The following two functions are needed to circumvent a bug in
469// gcc 2.95.3, which sometimes has problem with the above template
470// function.
471bool PredFunction2Int(int v1, int v2) {
472  return v1 + v2 > 0;
473}
474bool PredFunction2Bool(Bool v1, Bool v2) {
475  return v1 + v2 > 0;
476}
477
478// A binary predicate functor.
479struct PredFunctor2 {
480  template <typename T1, typename T2>
481  bool operator()(const T1& v1,
482                  const T2& v2) {
483    return v1 + v2 > 0;
484  }
485};
486
487// A binary predicate-formatter function.
488template <typename T1, typename T2>
489testing::AssertionResult PredFormatFunction2(const char* e1,
490                                             const char* e2,
491                                             const T1& v1,
492                                             const T2& v2) {
493  if (PredFunction2(v1, v2))
494    return testing::AssertionSuccess();
495
496  return testing::AssertionFailure()
497      << e1 << " + " << e2
498      << " is expected to be positive, but evaluates to "
499      << v1 + v2 << ".";
500}
501
502// A binary predicate-formatter functor.
503struct PredFormatFunctor2 {
504  template <typename T1, typename T2>
505  testing::AssertionResult operator()(const char* e1,
506                                      const char* e2,
507                                      const T1& v1,
508                                      const T2& v2) const {
509    return PredFormatFunction2(e1, e2, v1, v2);
510  }
511};
512
513// Tests for {EXPECT|ASSERT}_PRED_FORMAT2.
514
515class Predicate2Test : public testing::Test {
516 protected:
517  virtual void SetUp() {
518    expected_to_finish_ = true;
519    finished_ = false;
520    n1_ = n2_ = 0;
521  }
522
523  virtual void TearDown() {
524    // Verifies that each of the predicate's arguments was evaluated
525    // exactly once.
526    EXPECT_EQ(1, n1_) <<
527        "The predicate assertion didn't evaluate argument 2 "
528        "exactly once.";
529    EXPECT_EQ(1, n2_) <<
530        "The predicate assertion didn't evaluate argument 3 "
531        "exactly once.";
532
533    // Verifies that the control flow in the test function is expected.
534    if (expected_to_finish_ && !finished_) {
535      FAIL() << "The predicate assertion unexpactedly aborted the test.";
536    } else if (!expected_to_finish_ && finished_) {
537      FAIL() << "The failed predicate assertion didn't abort the test "
538                "as expected.";
539    }
540  }
541
542  // true iff the test function is expected to run to finish.
543  static bool expected_to_finish_;
544
545  // true iff the test function did run to finish.
546  static bool finished_;
547
548  static int n1_;
549  static int n2_;
550};
551
552bool Predicate2Test::expected_to_finish_;
553bool Predicate2Test::finished_;
554int Predicate2Test::n1_;
555int Predicate2Test::n2_;
556
557typedef Predicate2Test EXPECT_PRED_FORMAT2Test;
558typedef Predicate2Test ASSERT_PRED_FORMAT2Test;
559typedef Predicate2Test EXPECT_PRED2Test;
560typedef Predicate2Test ASSERT_PRED2Test;
561
562// Tests a successful EXPECT_PRED2 where the
563// predicate-formatter is a function on a built-in type (int).
564TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeSuccess) {
565  EXPECT_PRED2(PredFunction2Int,
566               ++n1_,
567               ++n2_);
568  finished_ = true;
569}
570
571// Tests a successful EXPECT_PRED2 where the
572// predicate-formatter is a function on a user-defined type (Bool).
573TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeSuccess) {
574  EXPECT_PRED2(PredFunction2Bool,
575               Bool(++n1_),
576               Bool(++n2_));
577  finished_ = true;
578}
579
580// Tests a successful EXPECT_PRED2 where the
581// predicate-formatter is a functor on a built-in type (int).
582TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeSuccess) {
583  EXPECT_PRED2(PredFunctor2(),
584               ++n1_,
585               ++n2_);
586  finished_ = true;
587}
588
589// Tests a successful EXPECT_PRED2 where the
590// predicate-formatter is a functor on a user-defined type (Bool).
591TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeSuccess) {
592  EXPECT_PRED2(PredFunctor2(),
593               Bool(++n1_),
594               Bool(++n2_));
595  finished_ = true;
596}
597
598// Tests a failed EXPECT_PRED2 where the
599// predicate-formatter is a function on a built-in type (int).
600TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeFailure) {
601  EXPECT_NONFATAL_FAILURE({  // NOLINT
602    EXPECT_PRED2(PredFunction2Int,
603                 n1_++,
604                 n2_++);
605    finished_ = true;
606  }, "");
607}
608
609// Tests a failed EXPECT_PRED2 where the
610// predicate-formatter is a function on a user-defined type (Bool).
611TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeFailure) {
612  EXPECT_NONFATAL_FAILURE({  // NOLINT
613    EXPECT_PRED2(PredFunction2Bool,
614                 Bool(n1_++),
615                 Bool(n2_++));
616    finished_ = true;
617  }, "");
618}
619
620// Tests a failed EXPECT_PRED2 where the
621// predicate-formatter is a functor on a built-in type (int).
622TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeFailure) {
623  EXPECT_NONFATAL_FAILURE({  // NOLINT
624    EXPECT_PRED2(PredFunctor2(),
625                 n1_++,
626                 n2_++);
627    finished_ = true;
628  }, "");
629}
630
631// Tests a failed EXPECT_PRED2 where the
632// predicate-formatter is a functor on a user-defined type (Bool).
633TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeFailure) {
634  EXPECT_NONFATAL_FAILURE({  // NOLINT
635    EXPECT_PRED2(PredFunctor2(),
636                 Bool(n1_++),
637                 Bool(n2_++));
638    finished_ = true;
639  }, "");
640}
641
642// Tests a successful ASSERT_PRED2 where the
643// predicate-formatter is a function on a built-in type (int).
644TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeSuccess) {
645  ASSERT_PRED2(PredFunction2Int,
646               ++n1_,
647               ++n2_);
648  finished_ = true;
649}
650
651// Tests a successful ASSERT_PRED2 where the
652// predicate-formatter is a function on a user-defined type (Bool).
653TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeSuccess) {
654  ASSERT_PRED2(PredFunction2Bool,
655               Bool(++n1_),
656               Bool(++n2_));
657  finished_ = true;
658}
659
660// Tests a successful ASSERT_PRED2 where the
661// predicate-formatter is a functor on a built-in type (int).
662TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeSuccess) {
663  ASSERT_PRED2(PredFunctor2(),
664               ++n1_,
665               ++n2_);
666  finished_ = true;
667}
668
669// Tests a successful ASSERT_PRED2 where the
670// predicate-formatter is a functor on a user-defined type (Bool).
671TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) {
672  ASSERT_PRED2(PredFunctor2(),
673               Bool(++n1_),
674               Bool(++n2_));
675  finished_ = true;
676}
677
678// Tests a failed ASSERT_PRED2 where the
679// predicate-formatter is a function on a built-in type (int).
680TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeFailure) {
681  expected_to_finish_ = false;
682  EXPECT_FATAL_FAILURE({  // NOLINT
683    ASSERT_PRED2(PredFunction2Int,
684                 n1_++,
685                 n2_++);
686    finished_ = true;
687  }, "");
688}
689
690// Tests a failed ASSERT_PRED2 where the
691// predicate-formatter is a function on a user-defined type (Bool).
692TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeFailure) {
693  expected_to_finish_ = false;
694  EXPECT_FATAL_FAILURE({  // NOLINT
695    ASSERT_PRED2(PredFunction2Bool,
696                 Bool(n1_++),
697                 Bool(n2_++));
698    finished_ = true;
699  }, "");
700}
701
702// Tests a failed ASSERT_PRED2 where the
703// predicate-formatter is a functor on a built-in type (int).
704TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeFailure) {
705  expected_to_finish_ = false;
706  EXPECT_FATAL_FAILURE({  // NOLINT
707    ASSERT_PRED2(PredFunctor2(),
708                 n1_++,
709                 n2_++);
710    finished_ = true;
711  }, "");
712}
713
714// Tests a failed ASSERT_PRED2 where the
715// predicate-formatter is a functor on a user-defined type (Bool).
716TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeFailure) {
717  expected_to_finish_ = false;
718  EXPECT_FATAL_FAILURE({  // NOLINT
719    ASSERT_PRED2(PredFunctor2(),
720                 Bool(n1_++),
721                 Bool(n2_++));
722    finished_ = true;
723  }, "");
724}
725
726// Tests a successful EXPECT_PRED_FORMAT2 where the
727// predicate-formatter is a function on a built-in type (int).
728TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) {
729  EXPECT_PRED_FORMAT2(PredFormatFunction2,
730                      ++n1_,
731                      ++n2_);
732  finished_ = true;
733}
734
735// Tests a successful EXPECT_PRED_FORMAT2 where the
736// predicate-formatter is a function on a user-defined type (Bool).
737TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) {
738  EXPECT_PRED_FORMAT2(PredFormatFunction2,
739                      Bool(++n1_),
740                      Bool(++n2_));
741  finished_ = true;
742}
743
744// Tests a successful EXPECT_PRED_FORMAT2 where the
745// predicate-formatter is a functor on a built-in type (int).
746TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) {
747  EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
748                      ++n1_,
749                      ++n2_);
750  finished_ = true;
751}
752
753// Tests a successful EXPECT_PRED_FORMAT2 where the
754// predicate-formatter is a functor on a user-defined type (Bool).
755TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) {
756  EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
757                      Bool(++n1_),
758                      Bool(++n2_));
759  finished_ = true;
760}
761
762// Tests a failed EXPECT_PRED_FORMAT2 where the
763// predicate-formatter is a function on a built-in type (int).
764TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) {
765  EXPECT_NONFATAL_FAILURE({  // NOLINT
766    EXPECT_PRED_FORMAT2(PredFormatFunction2,
767                        n1_++,
768                        n2_++);
769    finished_ = true;
770  }, "");
771}
772
773// Tests a failed EXPECT_PRED_FORMAT2 where the
774// predicate-formatter is a function on a user-defined type (Bool).
775TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) {
776  EXPECT_NONFATAL_FAILURE({  // NOLINT
777    EXPECT_PRED_FORMAT2(PredFormatFunction2,
778                        Bool(n1_++),
779                        Bool(n2_++));
780    finished_ = true;
781  }, "");
782}
783
784// Tests a failed EXPECT_PRED_FORMAT2 where the
785// predicate-formatter is a functor on a built-in type (int).
786TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) {
787  EXPECT_NONFATAL_FAILURE({  // NOLINT
788    EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
789                        n1_++,
790                        n2_++);
791    finished_ = true;
792  }, "");
793}
794
795// Tests a failed EXPECT_PRED_FORMAT2 where the
796// predicate-formatter is a functor on a user-defined type (Bool).
797TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) {
798  EXPECT_NONFATAL_FAILURE({  // NOLINT
799    EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
800                        Bool(n1_++),
801                        Bool(n2_++));
802    finished_ = true;
803  }, "");
804}
805
806// Tests a successful ASSERT_PRED_FORMAT2 where the
807// predicate-formatter is a function on a built-in type (int).
808TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) {
809  ASSERT_PRED_FORMAT2(PredFormatFunction2,
810                      ++n1_,
811                      ++n2_);
812  finished_ = true;
813}
814
815// Tests a successful ASSERT_PRED_FORMAT2 where the
816// predicate-formatter is a function on a user-defined type (Bool).
817TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) {
818  ASSERT_PRED_FORMAT2(PredFormatFunction2,
819                      Bool(++n1_),
820                      Bool(++n2_));
821  finished_ = true;
822}
823
824// Tests a successful ASSERT_PRED_FORMAT2 where the
825// predicate-formatter is a functor on a built-in type (int).
826TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) {
827  ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
828                      ++n1_,
829                      ++n2_);
830  finished_ = true;
831}
832
833// Tests a successful ASSERT_PRED_FORMAT2 where the
834// predicate-formatter is a functor on a user-defined type (Bool).
835TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) {
836  ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
837                      Bool(++n1_),
838                      Bool(++n2_));
839  finished_ = true;
840}
841
842// Tests a failed ASSERT_PRED_FORMAT2 where the
843// predicate-formatter is a function on a built-in type (int).
844TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) {
845  expected_to_finish_ = false;
846  EXPECT_FATAL_FAILURE({  // NOLINT
847    ASSERT_PRED_FORMAT2(PredFormatFunction2,
848                        n1_++,
849                        n2_++);
850    finished_ = true;
851  }, "");
852}
853
854// Tests a failed ASSERT_PRED_FORMAT2 where the
855// predicate-formatter is a function on a user-defined type (Bool).
856TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) {
857  expected_to_finish_ = false;
858  EXPECT_FATAL_FAILURE({  // NOLINT
859    ASSERT_PRED_FORMAT2(PredFormatFunction2,
860                        Bool(n1_++),
861                        Bool(n2_++));
862    finished_ = true;
863  }, "");
864}
865
866// Tests a failed ASSERT_PRED_FORMAT2 where the
867// predicate-formatter is a functor on a built-in type (int).
868TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) {
869  expected_to_finish_ = false;
870  EXPECT_FATAL_FAILURE({  // NOLINT
871    ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
872                        n1_++,
873                        n2_++);
874    finished_ = true;
875  }, "");
876}
877
878// Tests a failed ASSERT_PRED_FORMAT2 where the
879// predicate-formatter is a functor on a user-defined type (Bool).
880TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) {
881  expected_to_finish_ = false;
882  EXPECT_FATAL_FAILURE({  // NOLINT
883    ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
884                        Bool(n1_++),
885                        Bool(n2_++));
886    finished_ = true;
887  }, "");
888}
889// Sample functions/functors for testing ternary predicate assertions.
890
891// A ternary predicate function.
892template <typename T1, typename T2, typename T3>
893bool PredFunction3(T1 v1, T2 v2, T3 v3) {
894  return v1 + v2 + v3 > 0;
895}
896
897// The following two functions are needed to circumvent a bug in
898// gcc 2.95.3, which sometimes has problem with the above template
899// function.
900bool PredFunction3Int(int v1, int v2, int v3) {
901  return v1 + v2 + v3 > 0;
902}
903bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) {
904  return v1 + v2 + v3 > 0;
905}
906
907// A ternary predicate functor.
908struct PredFunctor3 {
909  template <typename T1, typename T2, typename T3>
910  bool operator()(const T1& v1,
911                  const T2& v2,
912                  const T3& v3) {
913    return v1 + v2 + v3 > 0;
914  }
915};
916
917// A ternary predicate-formatter function.
918template <typename T1, typename T2, typename T3>
919testing::AssertionResult PredFormatFunction3(const char* e1,
920                                             const char* e2,
921                                             const char* e3,
922                                             const T1& v1,
923                                             const T2& v2,
924                                             const T3& v3) {
925  if (PredFunction3(v1, v2, v3))
926    return testing::AssertionSuccess();
927
928  return testing::AssertionFailure()
929      << e1 << " + " << e2 << " + " << e3
930      << " is expected to be positive, but evaluates to "
931      << v1 + v2 + v3 << ".";
932}
933
934// A ternary predicate-formatter functor.
935struct PredFormatFunctor3 {
936  template <typename T1, typename T2, typename T3>
937  testing::AssertionResult operator()(const char* e1,
938                                      const char* e2,
939                                      const char* e3,
940                                      const T1& v1,
941                                      const T2& v2,
942                                      const T3& v3) const {
943    return PredFormatFunction3(e1, e2, e3, v1, v2, v3);
944  }
945};
946
947// Tests for {EXPECT|ASSERT}_PRED_FORMAT3.
948
949class Predicate3Test : public testing::Test {
950 protected:
951  virtual void SetUp() {
952    expected_to_finish_ = true;
953    finished_ = false;
954    n1_ = n2_ = n3_ = 0;
955  }
956
957  virtual void TearDown() {
958    // Verifies that each of the predicate's arguments was evaluated
959    // exactly once.
960    EXPECT_EQ(1, n1_) <<
961        "The predicate assertion didn't evaluate argument 2 "
962        "exactly once.";
963    EXPECT_EQ(1, n2_) <<
964        "The predicate assertion didn't evaluate argument 3 "
965        "exactly once.";
966    EXPECT_EQ(1, n3_) <<
967        "The predicate assertion didn't evaluate argument 4 "
968        "exactly once.";
969
970    // Verifies that the control flow in the test function is expected.
971    if (expected_to_finish_ && !finished_) {
972      FAIL() << "The predicate assertion unexpactedly aborted the test.";
973    } else if (!expected_to_finish_ && finished_) {
974      FAIL() << "The failed predicate assertion didn't abort the test "
975                "as expected.";
976    }
977  }
978
979  // true iff the test function is expected to run to finish.
980  static bool expected_to_finish_;
981
982  // true iff the test function did run to finish.
983  static bool finished_;
984
985  static int n1_;
986  static int n2_;
987  static int n3_;
988};
989
990bool Predicate3Test::expected_to_finish_;
991bool Predicate3Test::finished_;
992int Predicate3Test::n1_;
993int Predicate3Test::n2_;
994int Predicate3Test::n3_;
995
996typedef Predicate3Test EXPECT_PRED_FORMAT3Test;
997typedef Predicate3Test ASSERT_PRED_FORMAT3Test;
998typedef Predicate3Test EXPECT_PRED3Test;
999typedef Predicate3Test ASSERT_PRED3Test;
1000
1001// Tests a successful EXPECT_PRED3 where the
1002// predicate-formatter is a function on a built-in type (int).
1003TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeSuccess) {
1004  EXPECT_PRED3(PredFunction3Int,
1005               ++n1_,
1006               ++n2_,
1007               ++n3_);
1008  finished_ = true;
1009}
1010
1011// Tests a successful EXPECT_PRED3 where the
1012// predicate-formatter is a function on a user-defined type (Bool).
1013TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeSuccess) {
1014  EXPECT_PRED3(PredFunction3Bool,
1015               Bool(++n1_),
1016               Bool(++n2_),
1017               Bool(++n3_));
1018  finished_ = true;
1019}
1020
1021// Tests a successful EXPECT_PRED3 where the
1022// predicate-formatter is a functor on a built-in type (int).
1023TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeSuccess) {
1024  EXPECT_PRED3(PredFunctor3(),
1025               ++n1_,
1026               ++n2_,
1027               ++n3_);
1028  finished_ = true;
1029}
1030
1031// Tests a successful EXPECT_PRED3 where the
1032// predicate-formatter is a functor on a user-defined type (Bool).
1033TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeSuccess) {
1034  EXPECT_PRED3(PredFunctor3(),
1035               Bool(++n1_),
1036               Bool(++n2_),
1037               Bool(++n3_));
1038  finished_ = true;
1039}
1040
1041// Tests a failed EXPECT_PRED3 where the
1042// predicate-formatter is a function on a built-in type (int).
1043TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeFailure) {
1044  EXPECT_NONFATAL_FAILURE({  // NOLINT
1045    EXPECT_PRED3(PredFunction3Int,
1046                 n1_++,
1047                 n2_++,
1048                 n3_++);
1049    finished_ = true;
1050  }, "");
1051}
1052
1053// Tests a failed EXPECT_PRED3 where the
1054// predicate-formatter is a function on a user-defined type (Bool).
1055TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeFailure) {
1056  EXPECT_NONFATAL_FAILURE({  // NOLINT
1057    EXPECT_PRED3(PredFunction3Bool,
1058                 Bool(n1_++),
1059                 Bool(n2_++),
1060                 Bool(n3_++));
1061    finished_ = true;
1062  }, "");
1063}
1064
1065// Tests a failed EXPECT_PRED3 where the
1066// predicate-formatter is a functor on a built-in type (int).
1067TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeFailure) {
1068  EXPECT_NONFATAL_FAILURE({  // NOLINT
1069    EXPECT_PRED3(PredFunctor3(),
1070                 n1_++,
1071                 n2_++,
1072                 n3_++);
1073    finished_ = true;
1074  }, "");
1075}
1076
1077// Tests a failed EXPECT_PRED3 where the
1078// predicate-formatter is a functor on a user-defined type (Bool).
1079TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeFailure) {
1080  EXPECT_NONFATAL_FAILURE({  // NOLINT
1081    EXPECT_PRED3(PredFunctor3(),
1082                 Bool(n1_++),
1083                 Bool(n2_++),
1084                 Bool(n3_++));
1085    finished_ = true;
1086  }, "");
1087}
1088
1089// Tests a successful ASSERT_PRED3 where the
1090// predicate-formatter is a function on a built-in type (int).
1091TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeSuccess) {
1092  ASSERT_PRED3(PredFunction3Int,
1093               ++n1_,
1094               ++n2_,
1095               ++n3_);
1096  finished_ = true;
1097}
1098
1099// Tests a successful ASSERT_PRED3 where the
1100// predicate-formatter is a function on a user-defined type (Bool).
1101TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeSuccess) {
1102  ASSERT_PRED3(PredFunction3Bool,
1103               Bool(++n1_),
1104               Bool(++n2_),
1105               Bool(++n3_));
1106  finished_ = true;
1107}
1108
1109// Tests a successful ASSERT_PRED3 where the
1110// predicate-formatter is a functor on a built-in type (int).
1111TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeSuccess) {
1112  ASSERT_PRED3(PredFunctor3(),
1113               ++n1_,
1114               ++n2_,
1115               ++n3_);
1116  finished_ = true;
1117}
1118
1119// Tests a successful ASSERT_PRED3 where the
1120// predicate-formatter is a functor on a user-defined type (Bool).
1121TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) {
1122  ASSERT_PRED3(PredFunctor3(),
1123               Bool(++n1_),
1124               Bool(++n2_),
1125               Bool(++n3_));
1126  finished_ = true;
1127}
1128
1129// Tests a failed ASSERT_PRED3 where the
1130// predicate-formatter is a function on a built-in type (int).
1131TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeFailure) {
1132  expected_to_finish_ = false;
1133  EXPECT_FATAL_FAILURE({  // NOLINT
1134    ASSERT_PRED3(PredFunction3Int,
1135                 n1_++,
1136                 n2_++,
1137                 n3_++);
1138    finished_ = true;
1139  }, "");
1140}
1141
1142// Tests a failed ASSERT_PRED3 where the
1143// predicate-formatter is a function on a user-defined type (Bool).
1144TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeFailure) {
1145  expected_to_finish_ = false;
1146  EXPECT_FATAL_FAILURE({  // NOLINT
1147    ASSERT_PRED3(PredFunction3Bool,
1148                 Bool(n1_++),
1149                 Bool(n2_++),
1150                 Bool(n3_++));
1151    finished_ = true;
1152  }, "");
1153}
1154
1155// Tests a failed ASSERT_PRED3 where the
1156// predicate-formatter is a functor on a built-in type (int).
1157TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeFailure) {
1158  expected_to_finish_ = false;
1159  EXPECT_FATAL_FAILURE({  // NOLINT
1160    ASSERT_PRED3(PredFunctor3(),
1161                 n1_++,
1162                 n2_++,
1163                 n3_++);
1164    finished_ = true;
1165  }, "");
1166}
1167
1168// Tests a failed ASSERT_PRED3 where the
1169// predicate-formatter is a functor on a user-defined type (Bool).
1170TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeFailure) {
1171  expected_to_finish_ = false;
1172  EXPECT_FATAL_FAILURE({  // NOLINT
1173    ASSERT_PRED3(PredFunctor3(),
1174                 Bool(n1_++),
1175                 Bool(n2_++),
1176                 Bool(n3_++));
1177    finished_ = true;
1178  }, "");
1179}
1180
1181// Tests a successful EXPECT_PRED_FORMAT3 where the
1182// predicate-formatter is a function on a built-in type (int).
1183TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) {
1184  EXPECT_PRED_FORMAT3(PredFormatFunction3,
1185                      ++n1_,
1186                      ++n2_,
1187                      ++n3_);
1188  finished_ = true;
1189}
1190
1191// Tests a successful EXPECT_PRED_FORMAT3 where the
1192// predicate-formatter is a function on a user-defined type (Bool).
1193TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {
1194  EXPECT_PRED_FORMAT3(PredFormatFunction3,
1195                      Bool(++n1_),
1196                      Bool(++n2_),
1197                      Bool(++n3_));
1198  finished_ = true;
1199}
1200
1201// Tests a successful EXPECT_PRED_FORMAT3 where the
1202// predicate-formatter is a functor on a built-in type (int).
1203TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) {
1204  EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
1205                      ++n1_,
1206                      ++n2_,
1207                      ++n3_);
1208  finished_ = true;
1209}
1210
1211// Tests a successful EXPECT_PRED_FORMAT3 where the
1212// predicate-formatter is a functor on a user-defined type (Bool).
1213TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {
1214  EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
1215                      Bool(++n1_),
1216                      Bool(++n2_),
1217                      Bool(++n3_));
1218  finished_ = true;
1219}
1220
1221// Tests a failed EXPECT_PRED_FORMAT3 where the
1222// predicate-formatter is a function on a built-in type (int).
1223TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) {
1224  EXPECT_NONFATAL_FAILURE({  // NOLINT
1225    EXPECT_PRED_FORMAT3(PredFormatFunction3,
1226                        n1_++,
1227                        n2_++,
1228                        n3_++);
1229    finished_ = true;
1230  }, "");
1231}
1232
1233// Tests a failed EXPECT_PRED_FORMAT3 where the
1234// predicate-formatter is a function on a user-defined type (Bool).
1235TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) {
1236  EXPECT_NONFATAL_FAILURE({  // NOLINT
1237    EXPECT_PRED_FORMAT3(PredFormatFunction3,
1238                        Bool(n1_++),
1239                        Bool(n2_++),
1240                        Bool(n3_++));
1241    finished_ = true;
1242  }, "");
1243}
1244
1245// Tests a failed EXPECT_PRED_FORMAT3 where the
1246// predicate-formatter is a functor on a built-in type (int).
1247TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) {
1248  EXPECT_NONFATAL_FAILURE({  // NOLINT
1249    EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
1250                        n1_++,
1251                        n2_++,
1252                        n3_++);
1253    finished_ = true;
1254  }, "");
1255}
1256
1257// Tests a failed EXPECT_PRED_FORMAT3 where the
1258// predicate-formatter is a functor on a user-defined type (Bool).
1259TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) {
1260  EXPECT_NONFATAL_FAILURE({  // NOLINT
1261    EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
1262                        Bool(n1_++),
1263                        Bool(n2_++),
1264                        Bool(n3_++));
1265    finished_ = true;
1266  }, "");
1267}
1268
1269// Tests a successful ASSERT_PRED_FORMAT3 where the
1270// predicate-formatter is a function on a built-in type (int).
1271TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) {
1272  ASSERT_PRED_FORMAT3(PredFormatFunction3,
1273                      ++n1_,
1274                      ++n2_,
1275                      ++n3_);
1276  finished_ = true;
1277}
1278
1279// Tests a successful ASSERT_PRED_FORMAT3 where the
1280// predicate-formatter is a function on a user-defined type (Bool).
1281TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {
1282  ASSERT_PRED_FORMAT3(PredFormatFunction3,
1283                      Bool(++n1_),
1284                      Bool(++n2_),
1285                      Bool(++n3_));
1286  finished_ = true;
1287}
1288
1289// Tests a successful ASSERT_PRED_FORMAT3 where the
1290// predicate-formatter is a functor on a built-in type (int).
1291TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) {
1292  ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
1293                      ++n1_,
1294                      ++n2_,
1295                      ++n3_);
1296  finished_ = true;
1297}
1298
1299// Tests a successful ASSERT_PRED_FORMAT3 where the
1300// predicate-formatter is a functor on a user-defined type (Bool).
1301TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {
1302  ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
1303                      Bool(++n1_),
1304                      Bool(++n2_),
1305                      Bool(++n3_));
1306  finished_ = true;
1307}
1308
1309// Tests a failed ASSERT_PRED_FORMAT3 where the
1310// predicate-formatter is a function on a built-in type (int).
1311TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) {
1312  expected_to_finish_ = false;
1313  EXPECT_FATAL_FAILURE({  // NOLINT
1314    ASSERT_PRED_FORMAT3(PredFormatFunction3,
1315                        n1_++,
1316                        n2_++,
1317                        n3_++);
1318    finished_ = true;
1319  }, "");
1320}
1321
1322// Tests a failed ASSERT_PRED_FORMAT3 where the
1323// predicate-formatter is a function on a user-defined type (Bool).
1324TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) {
1325  expected_to_finish_ = false;
1326  EXPECT_FATAL_FAILURE({  // NOLINT
1327    ASSERT_PRED_FORMAT3(PredFormatFunction3,
1328                        Bool(n1_++),
1329                        Bool(n2_++),
1330                        Bool(n3_++));
1331    finished_ = true;
1332  }, "");
1333}
1334
1335// Tests a failed ASSERT_PRED_FORMAT3 where the
1336// predicate-formatter is a functor on a built-in type (int).
1337TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) {
1338  expected_to_finish_ = false;
1339  EXPECT_FATAL_FAILURE({  // NOLINT
1340    ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
1341                        n1_++,
1342                        n2_++,
1343                        n3_++);
1344    finished_ = true;
1345  }, "");
1346}
1347
1348// Tests a failed ASSERT_PRED_FORMAT3 where the
1349// predicate-formatter is a functor on a user-defined type (Bool).
1350TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) {
1351  expected_to_finish_ = false;
1352  EXPECT_FATAL_FAILURE({  // NOLINT
1353    ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
1354                        Bool(n1_++),
1355                        Bool(n2_++),
1356                        Bool(n3_++));
1357    finished_ = true;
1358  }, "");
1359}
1360// Sample functions/functors for testing 4-ary predicate assertions.
1361
1362// A 4-ary predicate function.
1363template <typename T1, typename T2, typename T3, typename T4>
1364bool PredFunction4(T1 v1, T2 v2, T3 v3, T4 v4) {
1365  return v1 + v2 + v3 + v4 > 0;
1366}
1367
1368// The following two functions are needed to circumvent a bug in
1369// gcc 2.95.3, which sometimes has problem with the above template
1370// function.
1371bool PredFunction4Int(int v1, int v2, int v3, int v4) {
1372  return v1 + v2 + v3 + v4 > 0;
1373}
1374bool PredFunction4Bool(Bool v1, Bool v2, Bool v3, Bool v4) {
1375  return v1 + v2 + v3 + v4 > 0;
1376}
1377
1378// A 4-ary predicate functor.
1379struct PredFunctor4 {
1380  template <typename T1, typename T2, typename T3, typename T4>
1381  bool operator()(const T1& v1,
1382                  const T2& v2,
1383                  const T3& v3,
1384                  const T4& v4) {
1385    return v1 + v2 + v3 + v4 > 0;
1386  }
1387};
1388
1389// A 4-ary predicate-formatter function.
1390template <typename T1, typename T2, typename T3, typename T4>
1391testing::AssertionResult PredFormatFunction4(const char* e1,
1392                                             const char* e2,
1393                                             const char* e3,
1394                                             const char* e4,
1395                                             const T1& v1,
1396                                             const T2& v2,
1397                                             const T3& v3,
1398                                             const T4& v4) {
1399  if (PredFunction4(v1, v2, v3, v4))
1400    return testing::AssertionSuccess();
1401
1402  return testing::AssertionFailure()
1403      << e1 << " + " << e2 << " + " << e3 << " + " << e4
1404      << " is expected to be positive, but evaluates to "
1405      << v1 + v2 + v3 + v4 << ".";
1406}
1407
1408// A 4-ary predicate-formatter functor.
1409struct PredFormatFunctor4 {
1410  template <typename T1, typename T2, typename T3, typename T4>
1411  testing::AssertionResult operator()(const char* e1,
1412                                      const char* e2,
1413                                      const char* e3,
1414                                      const char* e4,
1415                                      const T1& v1,
1416                                      const T2& v2,
1417                                      const T3& v3,
1418                                      const T4& v4) const {
1419    return PredFormatFunction4(e1, e2, e3, e4, v1, v2, v3, v4);
1420  }
1421};
1422
1423// Tests for {EXPECT|ASSERT}_PRED_FORMAT4.
1424
1425class Predicate4Test : public testing::Test {
1426 protected:
1427  virtual void SetUp() {
1428    expected_to_finish_ = true;
1429    finished_ = false;
1430    n1_ = n2_ = n3_ = n4_ = 0;
1431  }
1432
1433  virtual void TearDown() {
1434    // Verifies that each of the predicate's arguments was evaluated
1435    // exactly once.
1436    EXPECT_EQ(1, n1_) <<
1437        "The predicate assertion didn't evaluate argument 2 "
1438        "exactly once.";
1439    EXPECT_EQ(1, n2_) <<
1440        "The predicate assertion didn't evaluate argument 3 "
1441        "exactly once.";
1442    EXPECT_EQ(1, n3_) <<
1443        "The predicate assertion didn't evaluate argument 4 "
1444        "exactly once.";
1445    EXPECT_EQ(1, n4_) <<
1446        "The predicate assertion didn't evaluate argument 5 "
1447        "exactly once.";
1448
1449    // Verifies that the control flow in the test function is expected.
1450    if (expected_to_finish_ && !finished_) {
1451      FAIL() << "The predicate assertion unexpactedly aborted the test.";
1452    } else if (!expected_to_finish_ && finished_) {
1453      FAIL() << "The failed predicate assertion didn't abort the test "
1454                "as expected.";
1455    }
1456  }
1457
1458  // true iff the test function is expected to run to finish.
1459  static bool expected_to_finish_;
1460
1461  // true iff the test function did run to finish.
1462  static bool finished_;
1463
1464  static int n1_;
1465  static int n2_;
1466  static int n3_;
1467  static int n4_;
1468};
1469
1470bool Predicate4Test::expected_to_finish_;
1471bool Predicate4Test::finished_;
1472int Predicate4Test::n1_;
1473int Predicate4Test::n2_;
1474int Predicate4Test::n3_;
1475int Predicate4Test::n4_;
1476
1477typedef Predicate4Test EXPECT_PRED_FORMAT4Test;
1478typedef Predicate4Test ASSERT_PRED_FORMAT4Test;
1479typedef Predicate4Test EXPECT_PRED4Test;
1480typedef Predicate4Test ASSERT_PRED4Test;
1481
1482// Tests a successful EXPECT_PRED4 where the
1483// predicate-formatter is a function on a built-in type (int).
1484TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeSuccess) {
1485  EXPECT_PRED4(PredFunction4Int,
1486               ++n1_,
1487               ++n2_,
1488               ++n3_,
1489               ++n4_);
1490  finished_ = true;
1491}
1492
1493// Tests a successful EXPECT_PRED4 where the
1494// predicate-formatter is a function on a user-defined type (Bool).
1495TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) {
1496  EXPECT_PRED4(PredFunction4Bool,
1497               Bool(++n1_),
1498               Bool(++n2_),
1499               Bool(++n3_),
1500               Bool(++n4_));
1501  finished_ = true;
1502}
1503
1504// Tests a successful EXPECT_PRED4 where the
1505// predicate-formatter is a functor on a built-in type (int).
1506TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeSuccess) {
1507  EXPECT_PRED4(PredFunctor4(),
1508               ++n1_,
1509               ++n2_,
1510               ++n3_,
1511               ++n4_);
1512  finished_ = true;
1513}
1514
1515// Tests a successful EXPECT_PRED4 where the
1516// predicate-formatter is a functor on a user-defined type (Bool).
1517TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) {
1518  EXPECT_PRED4(PredFunctor4(),
1519               Bool(++n1_),
1520               Bool(++n2_),
1521               Bool(++n3_),
1522               Bool(++n4_));
1523  finished_ = true;
1524}
1525
1526// Tests a failed EXPECT_PRED4 where the
1527// predicate-formatter is a function on a built-in type (int).
1528TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeFailure) {
1529  EXPECT_NONFATAL_FAILURE({  // NOLINT
1530    EXPECT_PRED4(PredFunction4Int,
1531                 n1_++,
1532                 n2_++,
1533                 n3_++,
1534                 n4_++);
1535    finished_ = true;
1536  }, "");
1537}
1538
1539// Tests a failed EXPECT_PRED4 where the
1540// predicate-formatter is a function on a user-defined type (Bool).
1541TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeFailure) {
1542  EXPECT_NONFATAL_FAILURE({  // NOLINT
1543    EXPECT_PRED4(PredFunction4Bool,
1544                 Bool(n1_++),
1545                 Bool(n2_++),
1546                 Bool(n3_++),
1547                 Bool(n4_++));
1548    finished_ = true;
1549  }, "");
1550}
1551
1552// Tests a failed EXPECT_PRED4 where the
1553// predicate-formatter is a functor on a built-in type (int).
1554TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeFailure) {
1555  EXPECT_NONFATAL_FAILURE({  // NOLINT
1556    EXPECT_PRED4(PredFunctor4(),
1557                 n1_++,
1558                 n2_++,
1559                 n3_++,
1560                 n4_++);
1561    finished_ = true;
1562  }, "");
1563}
1564
1565// Tests a failed EXPECT_PRED4 where the
1566// predicate-formatter is a functor on a user-defined type (Bool).
1567TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeFailure) {
1568  EXPECT_NONFATAL_FAILURE({  // NOLINT
1569    EXPECT_PRED4(PredFunctor4(),
1570                 Bool(n1_++),
1571                 Bool(n2_++),
1572                 Bool(n3_++),
1573                 Bool(n4_++));
1574    finished_ = true;
1575  }, "");
1576}
1577
1578// Tests a successful ASSERT_PRED4 where the
1579// predicate-formatter is a function on a built-in type (int).
1580TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeSuccess) {
1581  ASSERT_PRED4(PredFunction4Int,
1582               ++n1_,
1583               ++n2_,
1584               ++n3_,
1585               ++n4_);
1586  finished_ = true;
1587}
1588
1589// Tests a successful ASSERT_PRED4 where the
1590// predicate-formatter is a function on a user-defined type (Bool).
1591TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) {
1592  ASSERT_PRED4(PredFunction4Bool,
1593               Bool(++n1_),
1594               Bool(++n2_),
1595               Bool(++n3_),
1596               Bool(++n4_));
1597  finished_ = true;
1598}
1599
1600// Tests a successful ASSERT_PRED4 where the
1601// predicate-formatter is a functor on a built-in type (int).
1602TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeSuccess) {
1603  ASSERT_PRED4(PredFunctor4(),
1604               ++n1_,
1605               ++n2_,
1606               ++n3_,
1607               ++n4_);
1608  finished_ = true;
1609}
1610
1611// Tests a successful ASSERT_PRED4 where the
1612// predicate-formatter is a functor on a user-defined type (Bool).
1613TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) {
1614  ASSERT_PRED4(PredFunctor4(),
1615               Bool(++n1_),
1616               Bool(++n2_),
1617               Bool(++n3_),
1618               Bool(++n4_));
1619  finished_ = true;
1620}
1621
1622// Tests a failed ASSERT_PRED4 where the
1623// predicate-formatter is a function on a built-in type (int).
1624TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeFailure) {
1625  expected_to_finish_ = false;
1626  EXPECT_FATAL_FAILURE({  // NOLINT
1627    ASSERT_PRED4(PredFunction4Int,
1628                 n1_++,
1629                 n2_++,
1630                 n3_++,
1631                 n4_++);
1632    finished_ = true;
1633  }, "");
1634}
1635
1636// Tests a failed ASSERT_PRED4 where the
1637// predicate-formatter is a function on a user-defined type (Bool).
1638TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeFailure) {
1639  expected_to_finish_ = false;
1640  EXPECT_FATAL_FAILURE({  // NOLINT
1641    ASSERT_PRED4(PredFunction4Bool,
1642                 Bool(n1_++),
1643                 Bool(n2_++),
1644                 Bool(n3_++),
1645                 Bool(n4_++));
1646    finished_ = true;
1647  }, "");
1648}
1649
1650// Tests a failed ASSERT_PRED4 where the
1651// predicate-formatter is a functor on a built-in type (int).
1652TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeFailure) {
1653  expected_to_finish_ = false;
1654  EXPECT_FATAL_FAILURE({  // NOLINT
1655    ASSERT_PRED4(PredFunctor4(),
1656                 n1_++,
1657                 n2_++,
1658                 n3_++,
1659                 n4_++);
1660    finished_ = true;
1661  }, "");
1662}
1663
1664// Tests a failed ASSERT_PRED4 where the
1665// predicate-formatter is a functor on a user-defined type (Bool).
1666TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeFailure) {
1667  expected_to_finish_ = false;
1668  EXPECT_FATAL_FAILURE({  // NOLINT
1669    ASSERT_PRED4(PredFunctor4(),
1670                 Bool(n1_++),
1671                 Bool(n2_++),
1672                 Bool(n3_++),
1673                 Bool(n4_++));
1674    finished_ = true;
1675  }, "");
1676}
1677
1678// Tests a successful EXPECT_PRED_FORMAT4 where the
1679// predicate-formatter is a function on a built-in type (int).
1680TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) {
1681  EXPECT_PRED_FORMAT4(PredFormatFunction4,
1682                      ++n1_,
1683                      ++n2_,
1684                      ++n3_,
1685                      ++n4_);
1686  finished_ = true;
1687}
1688
1689// Tests a successful EXPECT_PRED_FORMAT4 where the
1690// predicate-formatter is a function on a user-defined type (Bool).
1691TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) {
1692  EXPECT_PRED_FORMAT4(PredFormatFunction4,
1693                      Bool(++n1_),
1694                      Bool(++n2_),
1695                      Bool(++n3_),
1696                      Bool(++n4_));
1697  finished_ = true;
1698}
1699
1700// Tests a successful EXPECT_PRED_FORMAT4 where the
1701// predicate-formatter is a functor on a built-in type (int).
1702TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) {
1703  EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
1704                      ++n1_,
1705                      ++n2_,
1706                      ++n3_,
1707                      ++n4_);
1708  finished_ = true;
1709}
1710
1711// Tests a successful EXPECT_PRED_FORMAT4 where the
1712// predicate-formatter is a functor on a user-defined type (Bool).
1713TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) {
1714  EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
1715                      Bool(++n1_),
1716                      Bool(++n2_),
1717                      Bool(++n3_),
1718                      Bool(++n4_));
1719  finished_ = true;
1720}
1721
1722// Tests a failed EXPECT_PRED_FORMAT4 where the
1723// predicate-formatter is a function on a built-in type (int).
1724TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) {
1725  EXPECT_NONFATAL_FAILURE({  // NOLINT
1726    EXPECT_PRED_FORMAT4(PredFormatFunction4,
1727                        n1_++,
1728                        n2_++,
1729                        n3_++,
1730                        n4_++);
1731    finished_ = true;
1732  }, "");
1733}
1734
1735// Tests a failed EXPECT_PRED_FORMAT4 where the
1736// predicate-formatter is a function on a user-defined type (Bool).
1737TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) {
1738  EXPECT_NONFATAL_FAILURE({  // NOLINT
1739    EXPECT_PRED_FORMAT4(PredFormatFunction4,
1740                        Bool(n1_++),
1741                        Bool(n2_++),
1742                        Bool(n3_++),
1743                        Bool(n4_++));
1744    finished_ = true;
1745  }, "");
1746}
1747
1748// Tests a failed EXPECT_PRED_FORMAT4 where the
1749// predicate-formatter is a functor on a built-in type (int).
1750TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) {
1751  EXPECT_NONFATAL_FAILURE({  // NOLINT
1752    EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
1753                        n1_++,
1754                        n2_++,
1755                        n3_++,
1756                        n4_++);
1757    finished_ = true;
1758  }, "");
1759}
1760
1761// Tests a failed EXPECT_PRED_FORMAT4 where the
1762// predicate-formatter is a functor on a user-defined type (Bool).
1763TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) {
1764  EXPECT_NONFATAL_FAILURE({  // NOLINT
1765    EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
1766                        Bool(n1_++),
1767                        Bool(n2_++),
1768                        Bool(n3_++),
1769                        Bool(n4_++));
1770    finished_ = true;
1771  }, "");
1772}
1773
1774// Tests a successful ASSERT_PRED_FORMAT4 where the
1775// predicate-formatter is a function on a built-in type (int).
1776TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) {
1777  ASSERT_PRED_FORMAT4(PredFormatFunction4,
1778                      ++n1_,
1779                      ++n2_,
1780                      ++n3_,
1781                      ++n4_);
1782  finished_ = true;
1783}
1784
1785// Tests a successful ASSERT_PRED_FORMAT4 where the
1786// predicate-formatter is a function on a user-defined type (Bool).
1787TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) {
1788  ASSERT_PRED_FORMAT4(PredFormatFunction4,
1789                      Bool(++n1_),
1790                      Bool(++n2_),
1791                      Bool(++n3_),
1792                      Bool(++n4_));
1793  finished_ = true;
1794}
1795
1796// Tests a successful ASSERT_PRED_FORMAT4 where the
1797// predicate-formatter is a functor on a built-in type (int).
1798TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) {
1799  ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
1800                      ++n1_,
1801                      ++n2_,
1802                      ++n3_,
1803                      ++n4_);
1804  finished_ = true;
1805}
1806
1807// Tests a successful ASSERT_PRED_FORMAT4 where the
1808// predicate-formatter is a functor on a user-defined type (Bool).
1809TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) {
1810  ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
1811                      Bool(++n1_),
1812                      Bool(++n2_),
1813                      Bool(++n3_),
1814                      Bool(++n4_));
1815  finished_ = true;
1816}
1817
1818// Tests a failed ASSERT_PRED_FORMAT4 where the
1819// predicate-formatter is a function on a built-in type (int).
1820TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) {
1821  expected_to_finish_ = false;
1822  EXPECT_FATAL_FAILURE({  // NOLINT
1823    ASSERT_PRED_FORMAT4(PredFormatFunction4,
1824                        n1_++,
1825                        n2_++,
1826                        n3_++,
1827                        n4_++);
1828    finished_ = true;
1829  }, "");
1830}
1831
1832// Tests a failed ASSERT_PRED_FORMAT4 where the
1833// predicate-formatter is a function on a user-defined type (Bool).
1834TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) {
1835  expected_to_finish_ = false;
1836  EXPECT_FATAL_FAILURE({  // NOLINT
1837    ASSERT_PRED_FORMAT4(PredFormatFunction4,
1838                        Bool(n1_++),
1839                        Bool(n2_++),
1840                        Bool(n3_++),
1841                        Bool(n4_++));
1842    finished_ = true;
1843  }, "");
1844}
1845
1846// Tests a failed ASSERT_PRED_FORMAT4 where the
1847// predicate-formatter is a functor on a built-in type (int).
1848TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) {
1849  expected_to_finish_ = false;
1850  EXPECT_FATAL_FAILURE({  // NOLINT
1851    ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
1852                        n1_++,
1853                        n2_++,
1854                        n3_++,
1855                        n4_++);
1856    finished_ = true;
1857  }, "");
1858}
1859
1860// Tests a failed ASSERT_PRED_FORMAT4 where the
1861// predicate-formatter is a functor on a user-defined type (Bool).
1862TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) {
1863  expected_to_finish_ = false;
1864  EXPECT_FATAL_FAILURE({  // NOLINT
1865    ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
1866                        Bool(n1_++),
1867                        Bool(n2_++),
1868                        Bool(n3_++),
1869                        Bool(n4_++));
1870    finished_ = true;
1871  }, "");
1872}
1873// Sample functions/functors for testing 5-ary predicate assertions.
1874
1875// A 5-ary predicate function.
1876template <typename T1, typename T2, typename T3, typename T4, typename T5>
1877bool PredFunction5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) {
1878  return v1 + v2 + v3 + v4 + v5 > 0;
1879}
1880
1881// The following two functions are needed to circumvent a bug in
1882// gcc 2.95.3, which sometimes has problem with the above template
1883// function.
1884bool PredFunction5Int(int v1, int v2, int v3, int v4, int v5) {
1885  return v1 + v2 + v3 + v4 + v5 > 0;
1886}
1887bool PredFunction5Bool(Bool v1, Bool v2, Bool v3, Bool v4, Bool v5) {
1888  return v1 + v2 + v3 + v4 + v5 > 0;
1889}
1890
1891// A 5-ary predicate functor.
1892struct PredFunctor5 {
1893  template <typename T1, typename T2, typename T3, typename T4, typename T5>
1894  bool operator()(const T1& v1,
1895                  const T2& v2,
1896                  const T3& v3,
1897                  const T4& v4,
1898                  const T5& v5) {
1899    return v1 + v2 + v3 + v4 + v5 > 0;
1900  }
1901};
1902
1903// A 5-ary predicate-formatter function.
1904template <typename T1, typename T2, typename T3, typename T4, typename T5>
1905testing::AssertionResult PredFormatFunction5(const char* e1,
1906                                             const char* e2,
1907                                             const char* e3,
1908                                             const char* e4,
1909                                             const char* e5,
1910                                             const T1& v1,
1911                                             const T2& v2,
1912                                             const T3& v3,
1913                                             const T4& v4,
1914                                             const T5& v5) {
1915  if (PredFunction5(v1, v2, v3, v4, v5))
1916    return testing::AssertionSuccess();
1917
1918  return testing::AssertionFailure()
1919      << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
1920      << " is expected to be positive, but evaluates to "
1921      << v1 + v2 + v3 + v4 + v5 << ".";
1922}
1923
1924// A 5-ary predicate-formatter functor.
1925struct PredFormatFunctor5 {
1926  template <typename T1, typename T2, typename T3, typename T4, typename T5>
1927  testing::AssertionResult operator()(const char* e1,
1928                                      const char* e2,
1929                                      const char* e3,
1930                                      const char* e4,
1931                                      const char* e5,
1932                                      const T1& v1,
1933                                      const T2& v2,
1934                                      const T3& v3,
1935                                      const T4& v4,
1936                                      const T5& v5) const {
1937    return PredFormatFunction5(e1, e2, e3, e4, e5, v1, v2, v3, v4, v5);
1938  }
1939};
1940
1941// Tests for {EXPECT|ASSERT}_PRED_FORMAT5.
1942
1943class Predicate5Test : public testing::Test {
1944 protected:
1945  virtual void SetUp() {
1946    expected_to_finish_ = true;
1947    finished_ = false;
1948    n1_ = n2_ = n3_ = n4_ = n5_ = 0;
1949  }
1950
1951  virtual void TearDown() {
1952    // Verifies that each of the predicate's arguments was evaluated
1953    // exactly once.
1954    EXPECT_EQ(1, n1_) <<
1955        "The predicate assertion didn't evaluate argument 2 "
1956        "exactly once.";
1957    EXPECT_EQ(1, n2_) <<
1958        "The predicate assertion didn't evaluate argument 3 "
1959        "exactly once.";
1960    EXPECT_EQ(1, n3_) <<
1961        "The predicate assertion didn't evaluate argument 4 "
1962        "exactly once.";
1963    EXPECT_EQ(1, n4_) <<
1964        "The predicate assertion didn't evaluate argument 5 "
1965        "exactly once.";
1966    EXPECT_EQ(1, n5_) <<
1967        "The predicate assertion didn't evaluate argument 6 "
1968        "exactly once.";
1969
1970    // Verifies that the control flow in the test function is expected.
1971    if (expected_to_finish_ && !finished_) {
1972      FAIL() << "The predicate assertion unexpactedly aborted the test.";
1973    } else if (!expected_to_finish_ && finished_) {
1974      FAIL() << "The failed predicate assertion didn't abort the test "
1975                "as expected.";
1976    }
1977  }
1978
1979  // true iff the test function is expected to run to finish.
1980  static bool expected_to_finish_;
1981
1982  // true iff the test function did run to finish.
1983  static bool finished_;
1984
1985  static int n1_;
1986  static int n2_;
1987  static int n3_;
1988  static int n4_;
1989  static int n5_;
1990};
1991
1992bool Predicate5Test::expected_to_finish_;
1993bool Predicate5Test::finished_;
1994int Predicate5Test::n1_;
1995int Predicate5Test::n2_;
1996int Predicate5Test::n3_;
1997int Predicate5Test::n4_;
1998int Predicate5Test::n5_;
1999
2000typedef Predicate5Test EXPECT_PRED_FORMAT5Test;
2001typedef Predicate5Test ASSERT_PRED_FORMAT5Test;
2002typedef Predicate5Test EXPECT_PRED5Test;
2003typedef Predicate5Test ASSERT_PRED5Test;
2004
2005// Tests a successful EXPECT_PRED5 where the
2006// predicate-formatter is a function on a built-in type (int).
2007TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeSuccess) {
2008  EXPECT_PRED5(PredFunction5Int,
2009               ++n1_,
2010               ++n2_,
2011               ++n3_,
2012               ++n4_,
2013               ++n5_);
2014  finished_ = true;
2015}
2016
2017// Tests a successful EXPECT_PRED5 where the
2018// predicate-formatter is a function on a user-defined type (Bool).
2019TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeSuccess) {
2020  EXPECT_PRED5(PredFunction5Bool,
2021               Bool(++n1_),
2022               Bool(++n2_),
2023               Bool(++n3_),
2024               Bool(++n4_),
2025               Bool(++n5_));
2026  finished_ = true;
2027}
2028
2029// Tests a successful EXPECT_PRED5 where the
2030// predicate-formatter is a functor on a built-in type (int).
2031TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeSuccess) {
2032  EXPECT_PRED5(PredFunctor5(),
2033               ++n1_,
2034               ++n2_,
2035               ++n3_,
2036               ++n4_,
2037               ++n5_);
2038  finished_ = true;
2039}
2040
2041// Tests a successful EXPECT_PRED5 where the
2042// predicate-formatter is a functor on a user-defined type (Bool).
2043TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeSuccess) {
2044  EXPECT_PRED5(PredFunctor5(),
2045               Bool(++n1_),
2046               Bool(++n2_),
2047               Bool(++n3_),
2048               Bool(++n4_),
2049               Bool(++n5_));
2050  finished_ = true;
2051}
2052
2053// Tests a failed EXPECT_PRED5 where the
2054// predicate-formatter is a function on a built-in type (int).
2055TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeFailure) {
2056  EXPECT_NONFATAL_FAILURE({  // NOLINT
2057    EXPECT_PRED5(PredFunction5Int,
2058                 n1_++,
2059                 n2_++,
2060                 n3_++,
2061                 n4_++,
2062                 n5_++);
2063    finished_ = true;
2064  }, "");
2065}
2066
2067// Tests a failed EXPECT_PRED5 where the
2068// predicate-formatter is a function on a user-defined type (Bool).
2069TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeFailure) {
2070  EXPECT_NONFATAL_FAILURE({  // NOLINT
2071    EXPECT_PRED5(PredFunction5Bool,
2072                 Bool(n1_++),
2073                 Bool(n2_++),
2074                 Bool(n3_++),
2075                 Bool(n4_++),
2076                 Bool(n5_++));
2077    finished_ = true;
2078  }, "");
2079}
2080
2081// Tests a failed EXPECT_PRED5 where the
2082// predicate-formatter is a functor on a built-in type (int).
2083TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeFailure) {
2084  EXPECT_NONFATAL_FAILURE({  // NOLINT
2085    EXPECT_PRED5(PredFunctor5(),
2086                 n1_++,
2087                 n2_++,
2088                 n3_++,
2089                 n4_++,
2090                 n5_++);
2091    finished_ = true;
2092  }, "");
2093}
2094
2095// Tests a failed EXPECT_PRED5 where the
2096// predicate-formatter is a functor on a user-defined type (Bool).
2097TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeFailure) {
2098  EXPECT_NONFATAL_FAILURE({  // NOLINT
2099    EXPECT_PRED5(PredFunctor5(),
2100                 Bool(n1_++),
2101                 Bool(n2_++),
2102                 Bool(n3_++),
2103                 Bool(n4_++),
2104                 Bool(n5_++));
2105    finished_ = true;
2106  }, "");
2107}
2108
2109// Tests a successful ASSERT_PRED5 where the
2110// predicate-formatter is a function on a built-in type (int).
2111TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeSuccess) {
2112  ASSERT_PRED5(PredFunction5Int,
2113               ++n1_,
2114               ++n2_,
2115               ++n3_,
2116               ++n4_,
2117               ++n5_);
2118  finished_ = true;
2119}
2120
2121// Tests a successful ASSERT_PRED5 where the
2122// predicate-formatter is a function on a user-defined type (Bool).
2123TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeSuccess) {
2124  ASSERT_PRED5(PredFunction5Bool,
2125               Bool(++n1_),
2126               Bool(++n2_),
2127               Bool(++n3_),
2128               Bool(++n4_),
2129               Bool(++n5_));
2130  finished_ = true;
2131}
2132
2133// Tests a successful ASSERT_PRED5 where the
2134// predicate-formatter is a functor on a built-in type (int).
2135TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeSuccess) {
2136  ASSERT_PRED5(PredFunctor5(),
2137               ++n1_,
2138               ++n2_,
2139               ++n3_,
2140               ++n4_,
2141               ++n5_);
2142  finished_ = true;
2143}
2144
2145// Tests a successful ASSERT_PRED5 where the
2146// predicate-formatter is a functor on a user-defined type (Bool).
2147TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) {
2148  ASSERT_PRED5(PredFunctor5(),
2149               Bool(++n1_),
2150               Bool(++n2_),
2151               Bool(++n3_),
2152               Bool(++n4_),
2153               Bool(++n5_));
2154  finished_ = true;
2155}
2156
2157// Tests a failed ASSERT_PRED5 where the
2158// predicate-formatter is a function on a built-in type (int).
2159TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeFailure) {
2160  expected_to_finish_ = false;
2161  EXPECT_FATAL_FAILURE({  // NOLINT
2162    ASSERT_PRED5(PredFunction5Int,
2163                 n1_++,
2164                 n2_++,
2165                 n3_++,
2166                 n4_++,
2167                 n5_++);
2168    finished_ = true;
2169  }, "");
2170}
2171
2172// Tests a failed ASSERT_PRED5 where the
2173// predicate-formatter is a function on a user-defined type (Bool).
2174TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeFailure) {
2175  expected_to_finish_ = false;
2176  EXPECT_FATAL_FAILURE({  // NOLINT
2177    ASSERT_PRED5(PredFunction5Bool,
2178                 Bool(n1_++),
2179                 Bool(n2_++),
2180                 Bool(n3_++),
2181                 Bool(n4_++),
2182                 Bool(n5_++));
2183    finished_ = true;
2184  }, "");
2185}
2186
2187// Tests a failed ASSERT_PRED5 where the
2188// predicate-formatter is a functor on a built-in type (int).
2189TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeFailure) {
2190  expected_to_finish_ = false;
2191  EXPECT_FATAL_FAILURE({  // NOLINT
2192    ASSERT_PRED5(PredFunctor5(),
2193                 n1_++,
2194                 n2_++,
2195                 n3_++,
2196                 n4_++,
2197                 n5_++);
2198    finished_ = true;
2199  }, "");
2200}
2201
2202// Tests a failed ASSERT_PRED5 where the
2203// predicate-formatter is a functor on a user-defined type (Bool).
2204TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeFailure) {
2205  expected_to_finish_ = false;
2206  EXPECT_FATAL_FAILURE({  // NOLINT
2207    ASSERT_PRED5(PredFunctor5(),
2208                 Bool(n1_++),
2209                 Bool(n2_++),
2210                 Bool(n3_++),
2211                 Bool(n4_++),
2212                 Bool(n5_++));
2213    finished_ = true;
2214  }, "");
2215}
2216
2217// Tests a successful EXPECT_PRED_FORMAT5 where the
2218// predicate-formatter is a function on a built-in type (int).
2219TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) {
2220  EXPECT_PRED_FORMAT5(PredFormatFunction5,
2221                      ++n1_,
2222                      ++n2_,
2223                      ++n3_,
2224                      ++n4_,
2225                      ++n5_);
2226  finished_ = true;
2227}
2228
2229// Tests a successful EXPECT_PRED_FORMAT5 where the
2230// predicate-formatter is a function on a user-defined type (Bool).
2231TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) {
2232  EXPECT_PRED_FORMAT5(PredFormatFunction5,
2233                      Bool(++n1_),
2234                      Bool(++n2_),
2235                      Bool(++n3_),
2236                      Bool(++n4_),
2237                      Bool(++n5_));
2238  finished_ = true;
2239}
2240
2241// Tests a successful EXPECT_PRED_FORMAT5 where the
2242// predicate-formatter is a functor on a built-in type (int).
2243TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) {
2244  EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
2245                      ++n1_,
2246                      ++n2_,
2247                      ++n3_,
2248                      ++n4_,
2249                      ++n5_);
2250  finished_ = true;
2251}
2252
2253// Tests a successful EXPECT_PRED_FORMAT5 where the
2254// predicate-formatter is a functor on a user-defined type (Bool).
2255TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) {
2256  EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
2257                      Bool(++n1_),
2258                      Bool(++n2_),
2259                      Bool(++n3_),
2260                      Bool(++n4_),
2261                      Bool(++n5_));
2262  finished_ = true;
2263}
2264
2265// Tests a failed EXPECT_PRED_FORMAT5 where the
2266// predicate-formatter is a function on a built-in type (int).
2267TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) {
2268  EXPECT_NONFATAL_FAILURE({  // NOLINT
2269    EXPECT_PRED_FORMAT5(PredFormatFunction5,
2270                        n1_++,
2271                        n2_++,
2272                        n3_++,
2273                        n4_++,
2274                        n5_++);
2275    finished_ = true;
2276  }, "");
2277}
2278
2279// Tests a failed EXPECT_PRED_FORMAT5 where the
2280// predicate-formatter is a function on a user-defined type (Bool).
2281TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) {
2282  EXPECT_NONFATAL_FAILURE({  // NOLINT
2283    EXPECT_PRED_FORMAT5(PredFormatFunction5,
2284                        Bool(n1_++),
2285                        Bool(n2_++),
2286                        Bool(n3_++),
2287                        Bool(n4_++),
2288                        Bool(n5_++));
2289    finished_ = true;
2290  }, "");
2291}
2292
2293// Tests a failed EXPECT_PRED_FORMAT5 where the
2294// predicate-formatter is a functor on a built-in type (int).
2295TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) {
2296  EXPECT_NONFATAL_FAILURE({  // NOLINT
2297    EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
2298                        n1_++,
2299                        n2_++,
2300                        n3_++,
2301                        n4_++,
2302                        n5_++);
2303    finished_ = true;
2304  }, "");
2305}
2306
2307// Tests a failed EXPECT_PRED_FORMAT5 where the
2308// predicate-formatter is a functor on a user-defined type (Bool).
2309TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) {
2310  EXPECT_NONFATAL_FAILURE({  // NOLINT
2311    EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
2312                        Bool(n1_++),
2313                        Bool(n2_++),
2314                        Bool(n3_++),
2315                        Bool(n4_++),
2316                        Bool(n5_++));
2317    finished_ = true;
2318  }, "");
2319}
2320
2321// Tests a successful ASSERT_PRED_FORMAT5 where the
2322// predicate-formatter is a function on a built-in type (int).
2323TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) {
2324  ASSERT_PRED_FORMAT5(PredFormatFunction5,
2325                      ++n1_,
2326                      ++n2_,
2327                      ++n3_,
2328                      ++n4_,
2329                      ++n5_);
2330  finished_ = true;
2331}
2332
2333// Tests a successful ASSERT_PRED_FORMAT5 where the
2334// predicate-formatter is a function on a user-defined type (Bool).
2335TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) {
2336  ASSERT_PRED_FORMAT5(PredFormatFunction5,
2337                      Bool(++n1_),
2338                      Bool(++n2_),
2339                      Bool(++n3_),
2340                      Bool(++n4_),
2341                      Bool(++n5_));
2342  finished_ = true;
2343}
2344
2345// Tests a successful ASSERT_PRED_FORMAT5 where the
2346// predicate-formatter is a functor on a built-in type (int).
2347TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) {
2348  ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
2349                      ++n1_,
2350                      ++n2_,
2351                      ++n3_,
2352                      ++n4_,
2353                      ++n5_);
2354  finished_ = true;
2355}
2356
2357// Tests a successful ASSERT_PRED_FORMAT5 where the
2358// predicate-formatter is a functor on a user-defined type (Bool).
2359TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) {
2360  ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
2361                      Bool(++n1_),
2362                      Bool(++n2_),
2363                      Bool(++n3_),
2364                      Bool(++n4_),
2365                      Bool(++n5_));
2366  finished_ = true;
2367}
2368
2369// Tests a failed ASSERT_PRED_FORMAT5 where the
2370// predicate-formatter is a function on a built-in type (int).
2371TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) {
2372  expected_to_finish_ = false;
2373  EXPECT_FATAL_FAILURE({  // NOLINT
2374    ASSERT_PRED_FORMAT5(PredFormatFunction5,
2375                        n1_++,
2376                        n2_++,
2377                        n3_++,
2378                        n4_++,
2379                        n5_++);
2380    finished_ = true;
2381  }, "");
2382}
2383
2384// Tests a failed ASSERT_PRED_FORMAT5 where the
2385// predicate-formatter is a function on a user-defined type (Bool).
2386TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) {
2387  expected_to_finish_ = false;
2388  EXPECT_FATAL_FAILURE({  // NOLINT
2389    ASSERT_PRED_FORMAT5(PredFormatFunction5,
2390                        Bool(n1_++),
2391                        Bool(n2_++),
2392                        Bool(n3_++),
2393                        Bool(n4_++),
2394                        Bool(n5_++));
2395    finished_ = true;
2396  }, "");
2397}
2398
2399// Tests a failed ASSERT_PRED_FORMAT5 where the
2400// predicate-formatter is a functor on a built-in type (int).
2401TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) {
2402  expected_to_finish_ = false;
2403  EXPECT_FATAL_FAILURE({  // NOLINT
2404    ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
2405                        n1_++,
2406                        n2_++,
2407                        n3_++,
2408                        n4_++,
2409                        n5_++);
2410    finished_ = true;
2411  }, "");
2412}
2413
2414// Tests a failed ASSERT_PRED_FORMAT5 where the
2415// predicate-formatter is a functor on a user-defined type (Bool).
2416TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) {
2417  expected_to_finish_ = false;
2418  EXPECT_FATAL_FAILURE({  // NOLINT
2419    ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
2420                        Bool(n1_++),
2421                        Bool(n2_++),
2422                        Bool(n3_++),
2423                        Bool(n4_++),
2424                        Bool(n5_++));
2425    finished_ = true;
2426  }, "");
2427}
trunk/3rdparty/googletest/googletest/test/gtest_premature_exit_test.cc
r0r249096
1// Copyright 2013, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests that Google Test manipulates the premature-exit-detection
33// file correctly.
34
35#include <stdio.h>
36
37#include "gtest/gtest.h"
38
39using ::testing::InitGoogleTest;
40using ::testing::Test;
41using ::testing::internal::posix::GetEnv;
42using ::testing::internal::posix::Stat;
43using ::testing::internal::posix::StatStruct;
44
45namespace {
46
47class PrematureExitTest : public Test {
48 public:
49  // Returns true iff the given file exists.
50  static bool FileExists(const char* filepath) {
51    StatStruct stat;
52    return Stat(filepath, &stat) == 0;
53  }
54
55 protected:
56  PrematureExitTest() {
57    premature_exit_file_path_ = GetEnv("TEST_PREMATURE_EXIT_FILE");
58
59    // Normalize NULL to "" for ease of handling.
60    if (premature_exit_file_path_ == NULL) {
61      premature_exit_file_path_ = "";
62    }
63  }
64
65  // Returns true iff the premature-exit file exists.
66  bool PrematureExitFileExists() const {
67    return FileExists(premature_exit_file_path_);
68  }
69
70  const char* premature_exit_file_path_;
71};
72
73typedef PrematureExitTest PrematureExitDeathTest;
74
75// Tests that:
76//   - the premature-exit file exists during the execution of a
77//     death test (EXPECT_DEATH*), and
78//   - a death test doesn't interfere with the main test process's
79//     handling of the premature-exit file.
80TEST_F(PrematureExitDeathTest, FileExistsDuringExecutionOfDeathTest) {
81  if (*premature_exit_file_path_ == '\0') {
82    return;
83  }
84
85  EXPECT_DEATH_IF_SUPPORTED({
86      // If the file exists, crash the process such that the main test
87      // process will catch the (expected) crash and report a success;
88      // otherwise don't crash, which will cause the main test process
89      // to report that the death test has failed.
90      if (PrematureExitFileExists()) {
91        exit(1);
92      }
93    }, "");
94}
95
96// Tests that the premature-exit file exists during the execution of a
97// normal (non-death) test.
98TEST_F(PrematureExitTest, PrematureExitFileExistsDuringTestExecution) {
99  if (*premature_exit_file_path_ == '\0') {
100    return;
101  }
102
103  EXPECT_TRUE(PrematureExitFileExists())
104      << " file " << premature_exit_file_path_
105      << " should exist during test execution, but doesn't.";
106}
107
108}  // namespace
109
110int main(int argc, char **argv) {
111  InitGoogleTest(&argc, argv);
112  const int exit_code = RUN_ALL_TESTS();
113
114  // Test that the premature-exit file is deleted upon return from
115  // RUN_ALL_TESTS().
116  const char* const filepath = GetEnv("TEST_PREMATURE_EXIT_FILE");
117  if (filepath != NULL && *filepath != '\0') {
118    if (PrematureExitTest::FileExists(filepath)) {
119      printf(
120          "File %s shouldn't exist after the test program finishes, but does.",
121          filepath);
122      return 1;
123    }
124  }
125
126  return exit_code;
127}
trunk/3rdparty/googletest/googletest/test/gtest_prod_test.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Unit test for include/gtest/gtest_prod.h.
33
34#include "gtest/gtest.h"
35#include "test/production.h"
36
37// Tests that private members can be accessed from a TEST declared as
38// a friend of the class.
39TEST(PrivateCodeTest, CanAccessPrivateMembers) {
40  PrivateCode a;
41  EXPECT_EQ(0, a.x_);
42
43  a.set_x(1);
44  EXPECT_EQ(1, a.x_);
45}
46
47typedef testing::Test PrivateCodeFixtureTest;
48
49// Tests that private members can be accessed from a TEST_F declared
50// as a friend of the class.
51TEST_F(PrivateCodeFixtureTest, CanAccessPrivateMembers) {
52  PrivateCode a;
53  EXPECT_EQ(0, a.x_);
54
55  a.set_x(2);
56  EXPECT_EQ(2, a.x_);
57}
trunk/3rdparty/googletest/googletest/test/gtest_repeat_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Tests the --gtest_repeat=number flag.
33
34#include <stdlib.h>
35#include <iostream>
36#include "gtest/gtest.h"
37
38// Indicates that this translation unit is part of Google Test's
39// implementation.  It must come before gtest-internal-inl.h is
40// included, or there will be a compiler error.  This trick is to
41// prevent a user from accidentally including gtest-internal-inl.h in
42// his code.
43#define GTEST_IMPLEMENTATION_ 1
44#include "src/gtest-internal-inl.h"
45#undef GTEST_IMPLEMENTATION_
46
47namespace testing {
48
49GTEST_DECLARE_string_(death_test_style);
50GTEST_DECLARE_string_(filter);
51GTEST_DECLARE_int32_(repeat);
52
53}  // namespace testing
54
55using testing::GTEST_FLAG(death_test_style);
56using testing::GTEST_FLAG(filter);
57using testing::GTEST_FLAG(repeat);
58
59namespace {
60
61// We need this when we are testing Google Test itself and therefore
62// cannot use Google Test assertions.
63#define GTEST_CHECK_INT_EQ_(expected, actual) \
64  do {\
65    const int expected_val = (expected);\
66    const int actual_val = (actual);\
67    if (::testing::internal::IsTrue(expected_val != actual_val)) {\
68      ::std::cout << "Value of: " #actual "\n"\
69                  << "  Actual: " << actual_val << "\n"\
70                  << "Expected: " #expected "\n"\
71                  << "Which is: " << expected_val << "\n";\
72      ::testing::internal::posix::Abort();\
73    }\
74  } while (::testing::internal::AlwaysFalse())
75
76
77// Used for verifying that global environment set-up and tear-down are
78// inside the gtest_repeat loop.
79
80int g_environment_set_up_count = 0;
81int g_environment_tear_down_count = 0;
82
83class MyEnvironment : public testing::Environment {
84 public:
85  MyEnvironment() {}
86  virtual void SetUp() { g_environment_set_up_count++; }
87  virtual void TearDown() { g_environment_tear_down_count++; }
88};
89
90// A test that should fail.
91
92int g_should_fail_count = 0;
93
94TEST(FooTest, ShouldFail) {
95  g_should_fail_count++;
96  EXPECT_EQ(0, 1) << "Expected failure.";
97}
98
99// A test that should pass.
100
101int g_should_pass_count = 0;
102
103TEST(FooTest, ShouldPass) {
104  g_should_pass_count++;
105}
106
107// A test that contains a thread-safe death test and a fast death
108// test.  It should pass.
109
110int g_death_test_count = 0;
111
112TEST(BarDeathTest, ThreadSafeAndFast) {
113  g_death_test_count++;
114
115  GTEST_FLAG(death_test_style) = "threadsafe";
116  EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), "");
117
118  GTEST_FLAG(death_test_style) = "fast";
119  EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), "");
120}
121
122#if GTEST_HAS_PARAM_TEST
123int g_param_test_count = 0;
124
125const int kNumberOfParamTests = 10;
126
127class MyParamTest : public testing::TestWithParam<int> {};
128
129TEST_P(MyParamTest, ShouldPass) {
130  // TODO(vladl@google.com): Make parameter value checking robust
131  //                         WRT order of tests.
132  GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam());
133  g_param_test_count++;
134}
135INSTANTIATE_TEST_CASE_P(MyParamSequence,
136                        MyParamTest,
137                        testing::Range(0, kNumberOfParamTests));
138#endif  // GTEST_HAS_PARAM_TEST
139
140// Resets the count for each test.
141void ResetCounts() {
142  g_environment_set_up_count = 0;
143  g_environment_tear_down_count = 0;
144  g_should_fail_count = 0;
145  g_should_pass_count = 0;
146  g_death_test_count = 0;
147#if GTEST_HAS_PARAM_TEST
148  g_param_test_count = 0;
149#endif  // GTEST_HAS_PARAM_TEST
150}
151
152// Checks that the count for each test is expected.
153void CheckCounts(int expected) {
154  GTEST_CHECK_INT_EQ_(expected, g_environment_set_up_count);
155  GTEST_CHECK_INT_EQ_(expected, g_environment_tear_down_count);
156  GTEST_CHECK_INT_EQ_(expected, g_should_fail_count);
157  GTEST_CHECK_INT_EQ_(expected, g_should_pass_count);
158  GTEST_CHECK_INT_EQ_(expected, g_death_test_count);
159#if GTEST_HAS_PARAM_TEST
160  GTEST_CHECK_INT_EQ_(expected * kNumberOfParamTests, g_param_test_count);
161#endif  // GTEST_HAS_PARAM_TEST
162}
163
164// Tests the behavior of Google Test when --gtest_repeat is not specified.
165void TestRepeatUnspecified() {
166  ResetCounts();
167  GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());
168  CheckCounts(1);
169}
170
171// Tests the behavior of Google Test when --gtest_repeat has the given value.
172void TestRepeat(int repeat) {
173  GTEST_FLAG(repeat) = repeat;
174
175  ResetCounts();
176  GTEST_CHECK_INT_EQ_(repeat > 0 ? 1 : 0, RUN_ALL_TESTS());
177  CheckCounts(repeat);
178}
179
180// Tests using --gtest_repeat when --gtest_filter specifies an empty
181// set of tests.
182void TestRepeatWithEmptyFilter(int repeat) {
183  GTEST_FLAG(repeat) = repeat;
184  GTEST_FLAG(filter) = "None";
185
186  ResetCounts();
187  GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
188  CheckCounts(0);
189}
190
191// Tests using --gtest_repeat when --gtest_filter specifies a set of
192// successful tests.
193void TestRepeatWithFilterForSuccessfulTests(int repeat) {
194  GTEST_FLAG(repeat) = repeat;
195  GTEST_FLAG(filter) = "*-*ShouldFail";
196
197  ResetCounts();
198  GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
199  GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);
200  GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);
201  GTEST_CHECK_INT_EQ_(0, g_should_fail_count);
202  GTEST_CHECK_INT_EQ_(repeat, g_should_pass_count);
203  GTEST_CHECK_INT_EQ_(repeat, g_death_test_count);
204#if GTEST_HAS_PARAM_TEST
205  GTEST_CHECK_INT_EQ_(repeat * kNumberOfParamTests, g_param_test_count);
206#endif  // GTEST_HAS_PARAM_TEST
207}
208
209// Tests using --gtest_repeat when --gtest_filter specifies a set of
210// failed tests.
211void TestRepeatWithFilterForFailedTests(int repeat) {
212  GTEST_FLAG(repeat) = repeat;
213  GTEST_FLAG(filter) = "*ShouldFail";
214
215  ResetCounts();
216  GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());
217  GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);
218  GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);
219  GTEST_CHECK_INT_EQ_(repeat, g_should_fail_count);
220  GTEST_CHECK_INT_EQ_(0, g_should_pass_count);
221  GTEST_CHECK_INT_EQ_(0, g_death_test_count);
222#if GTEST_HAS_PARAM_TEST
223  GTEST_CHECK_INT_EQ_(0, g_param_test_count);
224#endif  // GTEST_HAS_PARAM_TEST
225}
226
227}  // namespace
228
229int main(int argc, char **argv) {
230  testing::InitGoogleTest(&argc, argv);
231  testing::AddGlobalTestEnvironment(new MyEnvironment);
232
233  TestRepeatUnspecified();
234  TestRepeat(0);
235  TestRepeat(1);
236  TestRepeat(5);
237
238  TestRepeatWithEmptyFilter(2);
239  TestRepeatWithEmptyFilter(3);
240
241  TestRepeatWithFilterForSuccessfulTests(3);
242
243  TestRepeatWithFilterForFailedTests(4);
244
245  // It would be nice to verify that the tests indeed loop forever
246  // when GTEST_FLAG(repeat) is negative, but this test will be quite
247  // complicated to write.  Since this flag is for interactive
248  // debugging only and doesn't affect the normal test result, such a
249  // test would be an overkill.
250
251  printf("PASS\n");
252  return 0;
253}
trunk/3rdparty/googletest/googletest/test/gtest_shuffle_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009 Google Inc. All Rights Reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9#     * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11#     * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15#     * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31"""Verifies that test shuffling works."""
32
33__author__ = 'wan@google.com (Zhanyong Wan)'
34
35import os
36import gtest_test_utils
37
38# Command to run the gtest_shuffle_test_ program.
39COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_')
40
41# The environment variables for test sharding.
42TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
43SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
44
45TEST_FILTER = 'A*.A:A*.B:C*'
46
47ALL_TESTS = []
48ACTIVE_TESTS = []
49FILTERED_TESTS = []
50SHARDED_TESTS = []
51
52SHUFFLED_ALL_TESTS = []
53SHUFFLED_ACTIVE_TESTS = []
54SHUFFLED_FILTERED_TESTS = []
55SHUFFLED_SHARDED_TESTS = []
56
57
58def AlsoRunDisabledTestsFlag():
59  return '--gtest_also_run_disabled_tests'
60
61
62def FilterFlag(test_filter):
63  return '--gtest_filter=%s' % (test_filter,)
64
65
66def RepeatFlag(n):
67  return '--gtest_repeat=%s' % (n,)
68
69
70def ShuffleFlag():
71  return '--gtest_shuffle'
72
73
74def RandomSeedFlag(n):
75  return '--gtest_random_seed=%s' % (n,)
76
77
78def RunAndReturnOutput(extra_env, args):
79  """Runs the test program and returns its output."""
80
81  environ_copy = os.environ.copy()
82  environ_copy.update(extra_env)
83
84  return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output
85
86
87def GetTestsForAllIterations(extra_env, args):
88  """Runs the test program and returns a list of test lists.
89
90  Args:
91    extra_env: a map from environment variables to their values
92    args: command line flags to pass to gtest_shuffle_test_
93
94  Returns:
95    A list where the i-th element is the list of tests run in the i-th
96    test iteration.
97  """
98
99  test_iterations = []
100  for line in RunAndReturnOutput(extra_env, args).split('\n'):
101    if line.startswith('----'):
102      tests = []
103      test_iterations.append(tests)
104    elif line.strip():
105      tests.append(line.strip())  # 'TestCaseName.TestName'
106
107  return test_iterations
108
109
110def GetTestCases(tests):
111  """Returns a list of test cases in the given full test names.
112
113  Args:
114    tests: a list of full test names
115
116  Returns:
117    A list of test cases from 'tests', in their original order.
118    Consecutive duplicates are removed.
119  """
120
121  test_cases = []
122  for test in tests:
123    test_case = test.split('.')[0]
124    if not test_case in test_cases:
125      test_cases.append(test_case)
126
127  return test_cases
128
129
130def CalculateTestLists():
131  """Calculates the list of tests run under different flags."""
132
133  if not ALL_TESTS:
134    ALL_TESTS.extend(
135        GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
136
137  if not ACTIVE_TESTS:
138    ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
139
140  if not FILTERED_TESTS:
141    FILTERED_TESTS.extend(
142        GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
143
144  if not SHARDED_TESTS:
145    SHARDED_TESTS.extend(
146        GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
147                                  SHARD_INDEX_ENV_VAR: '1'},
148                                 [])[0])
149
150  if not SHUFFLED_ALL_TESTS:
151    SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(
152        {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])
153
154  if not SHUFFLED_ACTIVE_TESTS:
155    SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
156        {}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
157
158  if not SHUFFLED_FILTERED_TESTS:
159    SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(
160        {}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])
161
162  if not SHUFFLED_SHARDED_TESTS:
163    SHUFFLED_SHARDED_TESTS.extend(
164        GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
165                                  SHARD_INDEX_ENV_VAR: '1'},
166                                 [ShuffleFlag(), RandomSeedFlag(1)])[0])
167
168
169class GTestShuffleUnitTest(gtest_test_utils.TestCase):
170  """Tests test shuffling."""
171
172  def setUp(self):
173    CalculateTestLists()
174
175  def testShufflePreservesNumberOfTests(self):
176    self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS))
177    self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS))
178    self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS))
179    self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))
180
181  def testShuffleChangesTestOrder(self):
182    self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
183    self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)
184    self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,
185                 SHUFFLED_FILTERED_TESTS)
186    self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,
187                 SHUFFLED_SHARDED_TESTS)
188
189  def testShuffleChangesTestCaseOrder(self):
190    self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
191                 GetTestCases(SHUFFLED_ALL_TESTS))
192    self.assert_(
193        GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
194        GetTestCases(SHUFFLED_ACTIVE_TESTS))
195    self.assert_(
196        GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
197        GetTestCases(SHUFFLED_FILTERED_TESTS))
198    self.assert_(
199        GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
200        GetTestCases(SHUFFLED_SHARDED_TESTS))
201
202  def testShuffleDoesNotRepeatTest(self):
203    for test in SHUFFLED_ALL_TESTS:
204      self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),
205                       '%s appears more than once' % (test,))
206    for test in SHUFFLED_ACTIVE_TESTS:
207      self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),
208                       '%s appears more than once' % (test,))
209    for test in SHUFFLED_FILTERED_TESTS:
210      self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),
211                       '%s appears more than once' % (test,))
212    for test in SHUFFLED_SHARDED_TESTS:
213      self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),
214                       '%s appears more than once' % (test,))
215
216  def testShuffleDoesNotCreateNewTest(self):
217    for test in SHUFFLED_ALL_TESTS:
218      self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))
219    for test in SHUFFLED_ACTIVE_TESTS:
220      self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
221    for test in SHUFFLED_FILTERED_TESTS:
222      self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
223    for test in SHUFFLED_SHARDED_TESTS:
224      self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
225
226  def testShuffleIncludesAllTests(self):
227    for test in ALL_TESTS:
228      self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
229    for test in ACTIVE_TESTS:
230      self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
231    for test in FILTERED_TESTS:
232      self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))
233    for test in SHARDED_TESTS:
234      self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
235
236  def testShuffleLeavesDeathTestsAtFront(self):
237    non_death_test_found = False
238    for test in SHUFFLED_ACTIVE_TESTS:
239      if 'DeathTest.' in test:
240        self.assert_(not non_death_test_found,
241                     '%s appears after a non-death test' % (test,))
242      else:
243        non_death_test_found = True
244
245  def _VerifyTestCasesDoNotInterleave(self, tests):
246    test_cases = []
247    for test in tests:
248      [test_case, _] = test.split('.')
249      if test_cases and test_cases[-1] != test_case:
250        test_cases.append(test_case)
251        self.assertEqual(1, test_cases.count(test_case),
252                         'Test case %s is not grouped together in %s' %
253                         (test_case, tests))
254
255  def testShuffleDoesNotInterleaveTestCases(self):
256    self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)
257    self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS)
258    self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS)
259    self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS)
260
261  def testShuffleRestoresOrderAfterEachIteration(self):
262    # Get the test lists in all 3 iterations, using random seed 1, 2,
263    # and 3 respectively.  Google Test picks a different seed in each
264    # iteration, and this test depends on the current implementation
265    # picking successive numbers.  This dependency is not ideal, but
266    # makes the test much easier to write.
267    [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
268        GetTestsForAllIterations(
269            {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
270
271    # Make sure running the tests with random seed 1 gets the same
272    # order as in iteration 1 above.
273    [tests_with_seed1] = GetTestsForAllIterations(
274        {}, [ShuffleFlag(), RandomSeedFlag(1)])
275    self.assertEqual(tests_in_iteration1, tests_with_seed1)
276
277    # Make sure running the tests with random seed 2 gets the same
278    # order as in iteration 2 above.  Success means that Google Test
279    # correctly restores the test order before re-shuffling at the
280    # beginning of iteration 2.
281    [tests_with_seed2] = GetTestsForAllIterations(
282        {}, [ShuffleFlag(), RandomSeedFlag(2)])
283    self.assertEqual(tests_in_iteration2, tests_with_seed2)
284
285    # Make sure running the tests with random seed 3 gets the same
286    # order as in iteration 3 above.  Success means that Google Test
287    # correctly restores the test order before re-shuffling at the
288    # beginning of iteration 3.
289    [tests_with_seed3] = GetTestsForAllIterations(
290        {}, [ShuffleFlag(), RandomSeedFlag(3)])
291    self.assertEqual(tests_in_iteration3, tests_with_seed3)
292
293  def testShuffleGeneratesNewOrderInEachIteration(self):
294    [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
295        GetTestsForAllIterations(
296            {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
297
298    self.assert_(tests_in_iteration1 != tests_in_iteration2,
299                 tests_in_iteration1)
300    self.assert_(tests_in_iteration1 != tests_in_iteration3,
301                 tests_in_iteration1)
302    self.assert_(tests_in_iteration2 != tests_in_iteration3,
303                 tests_in_iteration2)
304
305  def testShuffleShardedTestsPreservesPartition(self):
306    # If we run M tests on N shards, the same M tests should be run in
307    # total, regardless of the random seeds used by the shards.
308    [tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
309                                         SHARD_INDEX_ENV_VAR: '0'},
310                                        [ShuffleFlag(), RandomSeedFlag(1)])
311    [tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
312                                         SHARD_INDEX_ENV_VAR: '1'},
313                                        [ShuffleFlag(), RandomSeedFlag(20)])
314    [tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
315                                         SHARD_INDEX_ENV_VAR: '2'},
316                                        [ShuffleFlag(), RandomSeedFlag(25)])
317    sorted_sharded_tests = tests1 + tests2 + tests3
318    sorted_sharded_tests.sort()
319    sorted_active_tests = []
320    sorted_active_tests.extend(ACTIVE_TESTS)
321    sorted_active_tests.sort()
322    self.assertEqual(sorted_active_tests, sorted_sharded_tests)
323
324if __name__ == '__main__':
325  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_shuffle_test_.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Verifies that test shuffling works.
33
34#include "gtest/gtest.h"
35
36namespace {
37
38using ::testing::EmptyTestEventListener;
39using ::testing::InitGoogleTest;
40using ::testing::Message;
41using ::testing::Test;
42using ::testing::TestEventListeners;
43using ::testing::TestInfo;
44using ::testing::UnitTest;
45using ::testing::internal::scoped_ptr;
46
47// The test methods are empty, as the sole purpose of this program is
48// to print the test names before/after shuffling.
49
50class A : public Test {};
51TEST_F(A, A) {}
52TEST_F(A, B) {}
53
54TEST(ADeathTest, A) {}
55TEST(ADeathTest, B) {}
56TEST(ADeathTest, C) {}
57
58TEST(B, A) {}
59TEST(B, B) {}
60TEST(B, C) {}
61TEST(B, DISABLED_D) {}
62TEST(B, DISABLED_E) {}
63
64TEST(BDeathTest, A) {}
65TEST(BDeathTest, B) {}
66
67TEST(C, A) {}
68TEST(C, B) {}
69TEST(C, C) {}
70TEST(C, DISABLED_D) {}
71
72TEST(CDeathTest, A) {}
73
74TEST(DISABLED_D, A) {}
75TEST(DISABLED_D, DISABLED_B) {}
76
77// This printer prints the full test names only, starting each test
78// iteration with a "----" marker.
79class TestNamePrinter : public EmptyTestEventListener {
80 public:
81  virtual void OnTestIterationStart(const UnitTest& /* unit_test */,
82                                    int /* iteration */) {
83    printf("----\n");
84  }
85
86  virtual void OnTestStart(const TestInfo& test_info) {
87    printf("%s.%s\n", test_info.test_case_name(), test_info.name());
88  }
89};
90
91}  // namespace
92
93int main(int argc, char **argv) {
94  InitGoogleTest(&argc, argv);
95
96  // Replaces the default printer with TestNamePrinter, which prints
97  // the test name only.
98  TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
99  delete listeners.Release(listeners.default_result_printer());
100  listeners.Append(new TestNamePrinter);
101
102  return RUN_ALL_TESTS();
103}
trunk/3rdparty/googletest/googletest/test/gtest_sole_header_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: mheule@google.com (Markus Heule)
31//
32// This test verifies that it's possible to use Google Test by including
33// the gtest.h header file alone.
34
35#include "gtest/gtest.h"
36
37namespace {
38
39void Subroutine() {
40  EXPECT_EQ(42, 42);
41}
42
43TEST(NoFatalFailureTest, ExpectNoFatalFailure) {
44  EXPECT_NO_FATAL_FAILURE(;);
45  EXPECT_NO_FATAL_FAILURE(SUCCEED());
46  EXPECT_NO_FATAL_FAILURE(Subroutine());
47  EXPECT_NO_FATAL_FAILURE({ SUCCEED(); });
48}
49
50TEST(NoFatalFailureTest, AssertNoFatalFailure) {
51  ASSERT_NO_FATAL_FAILURE(;);
52  ASSERT_NO_FATAL_FAILURE(SUCCEED());
53  ASSERT_NO_FATAL_FAILURE(Subroutine());
54  ASSERT_NO_FATAL_FAILURE({ SUCCEED(); });
55}
56
57}  // namespace
trunk/3rdparty/googletest/googletest/test/gtest_stress_test.cc
r0r249096
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Tests that SCOPED_TRACE() and various Google Test assertions can be
33// used in a large number of threads concurrently.
34
35#include "gtest/gtest.h"
36
37#include <iostream>
38#include <vector>
39
40// We must define this macro in order to #include
41// gtest-internal-inl.h.  This is how Google Test prevents a user from
42// accidentally depending on its internal implementation.
43#define GTEST_IMPLEMENTATION_ 1
44#include "src/gtest-internal-inl.h"
45#undef GTEST_IMPLEMENTATION_
46
47#if GTEST_IS_THREADSAFE
48
49namespace testing {
50namespace {
51
52using internal::Notification;
53using internal::TestPropertyKeyIs;
54using internal::ThreadWithParam;
55using internal::scoped_ptr;
56
57// In order to run tests in this file, for platforms where Google Test is
58// thread safe, implement ThreadWithParam. See the description of its API
59// in gtest-port.h, where it is defined for already supported platforms.
60
61// How many threads to create?
62const int kThreadCount = 50;
63
64std::string IdToKey(int id, const char* suffix) {
65  Message key;
66  key << "key_" << id << "_" << suffix;
67  return key.GetString();
68}
69
70std::string IdToString(int id) {
71  Message id_message;
72  id_message << id;
73  return id_message.GetString();
74}
75
76void ExpectKeyAndValueWereRecordedForId(
77    const std::vector<TestProperty>& properties,
78    int id, const char* suffix) {
79  TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str());
80  const std::vector<TestProperty>::const_iterator property =
81      std::find_if(properties.begin(), properties.end(), matches_key);
82  ASSERT_TRUE(property != properties.end())
83      << "expecting " << suffix << " value for id " << id;
84  EXPECT_STREQ(IdToString(id).c_str(), property->value());
85}
86
87// Calls a large number of Google Test assertions, where exactly one of them
88// will fail.
89void ManyAsserts(int id) {
90  GTEST_LOG_(INFO) << "Thread #" << id << " running...";
91
92  SCOPED_TRACE(Message() << "Thread #" << id);
93
94  for (int i = 0; i < kThreadCount; i++) {
95    SCOPED_TRACE(Message() << "Iteration #" << i);
96
97    // A bunch of assertions that should succeed.
98    EXPECT_TRUE(true);
99    ASSERT_FALSE(false) << "This shouldn't fail.";
100    EXPECT_STREQ("a", "a");
101    ASSERT_LE(5, 6);
102    EXPECT_EQ(i, i) << "This shouldn't fail.";
103
104    // RecordProperty() should interact safely with other threads as well.
105    // The shared_key forces property updates.
106    Test::RecordProperty(IdToKey(id, "string").c_str(), IdToString(id).c_str());
107    Test::RecordProperty(IdToKey(id, "int").c_str(), id);
108    Test::RecordProperty("shared_key", IdToString(id).c_str());
109
110    // This assertion should fail kThreadCount times per thread.  It
111    // is for testing whether Google Test can handle failed assertions in a
112    // multi-threaded context.
113    EXPECT_LT(i, 0) << "This should always fail.";
114  }
115}
116
117void CheckTestFailureCount(int expected_failures) {
118  const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
119  const TestResult* const result = info->result();
120  GTEST_CHECK_(expected_failures == result->total_part_count())
121      << "Logged " << result->total_part_count() << " failures "
122      << " vs. " << expected_failures << " expected";
123}
124
125// Tests using SCOPED_TRACE() and Google Test assertions in many threads
126// concurrently.
127TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) {
128  {
129    scoped_ptr<ThreadWithParam<int> > threads[kThreadCount];
130    Notification threads_can_start;
131    for (int i = 0; i != kThreadCount; i++)
132      threads[i].reset(new ThreadWithParam<int>(&ManyAsserts,
133                                                i,
134                                                &threads_can_start));
135
136    threads_can_start.Notify();
137
138    // Blocks until all the threads are done.
139    for (int i = 0; i != kThreadCount; i++)
140      threads[i]->Join();
141  }
142
143  // Ensures that kThreadCount*kThreadCount failures have been reported.
144  const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
145  const TestResult* const result = info->result();
146
147  std::vector<TestProperty> properties;
148  // We have no access to the TestResult's list of properties but we can
149  // copy them one by one.
150  for (int i = 0; i < result->test_property_count(); ++i)
151    properties.push_back(result->GetTestProperty(i));
152
153  EXPECT_EQ(kThreadCount * 2 + 1, result->test_property_count())
154      << "String and int values recorded on each thread, "
155      << "as well as one shared_key";
156  for (int i = 0; i < kThreadCount; ++i) {
157    ExpectKeyAndValueWereRecordedForId(properties, i, "string");
158    ExpectKeyAndValueWereRecordedForId(properties, i, "int");
159  }
160  CheckTestFailureCount(kThreadCount*kThreadCount);
161}
162
163void FailingThread(bool is_fatal) {
164  if (is_fatal)
165    FAIL() << "Fatal failure in some other thread. "
166           << "(This failure is expected.)";
167  else
168    ADD_FAILURE() << "Non-fatal failure in some other thread. "
169                  << "(This failure is expected.)";
170}
171
172void GenerateFatalFailureInAnotherThread(bool is_fatal) {
173  ThreadWithParam<bool> thread(&FailingThread, is_fatal, NULL);
174  thread.Join();
175}
176
177TEST(NoFatalFailureTest, ExpectNoFatalFailureIgnoresFailuresInOtherThreads) {
178  EXPECT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true));
179  // We should only have one failure (the one from
180  // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE
181  // should succeed.
182  CheckTestFailureCount(1);
183}
184
185void AssertNoFatalFailureIgnoresFailuresInOtherThreads() {
186  ASSERT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true));
187}
188TEST(NoFatalFailureTest, AssertNoFatalFailureIgnoresFailuresInOtherThreads) {
189  // Using a subroutine, to make sure, that the test continues.
190  AssertNoFatalFailureIgnoresFailuresInOtherThreads();
191  // We should only have one failure (the one from
192  // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE
193  // should succeed.
194  CheckTestFailureCount(1);
195}
196
197TEST(FatalFailureTest, ExpectFatalFailureIgnoresFailuresInOtherThreads) {
198  // This statement should fail, since the current thread doesn't generate a
199  // fatal failure, only another one does.
200  EXPECT_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true), "expected");
201  CheckTestFailureCount(2);
202}
203
204TEST(FatalFailureOnAllThreadsTest, ExpectFatalFailureOnAllThreads) {
205  // This statement should succeed, because failures in all threads are
206  // considered.
207  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
208      GenerateFatalFailureInAnotherThread(true), "expected");
209  CheckTestFailureCount(0);
210  // We need to add a failure, because main() checks that there are failures.
211  // But when only this test is run, we shouldn't have any failures.
212  ADD_FAILURE() << "This is an expected non-fatal failure.";
213}
214
215TEST(NonFatalFailureTest, ExpectNonFatalFailureIgnoresFailuresInOtherThreads) {
216  // This statement should fail, since the current thread doesn't generate a
217  // fatal failure, only another one does.
218  EXPECT_NONFATAL_FAILURE(GenerateFatalFailureInAnotherThread(false),
219                          "expected");
220  CheckTestFailureCount(2);
221}
222
223TEST(NonFatalFailureOnAllThreadsTest, ExpectNonFatalFailureOnAllThreads) {
224  // This statement should succeed, because failures in all threads are
225  // considered.
226  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
227      GenerateFatalFailureInAnotherThread(false), "expected");
228  CheckTestFailureCount(0);
229  // We need to add a failure, because main() checks that there are failures,
230  // But when only this test is run, we shouldn't have any failures.
231  ADD_FAILURE() << "This is an expected non-fatal failure.";
232}
233
234}  // namespace
235}  // namespace testing
236
237int main(int argc, char **argv) {
238  testing::InitGoogleTest(&argc, argv);
239
240  const int result = RUN_ALL_TESTS();  // Expected to fail.
241  GTEST_CHECK_(result == 1) << "RUN_ALL_TESTS() did not fail as expected";
242
243  printf("\nPASS\n");
244  return 0;
245}
246
247#else
248TEST(StressTest,
249     DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {
250}
251
252int main(int argc, char **argv) {
253  testing::InitGoogleTest(&argc, argv);
254  return RUN_ALL_TESTS();
255}
256#endif  // GTEST_IS_THREADSAFE
trunk/3rdparty/googletest/googletest/test/gtest_test_utils.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2006, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Unit test utilities for Google C++ Testing Framework."""
33
34__author__ = 'wan@google.com (Zhanyong Wan)'
35
36import atexit
37import os
38import shutil
39import sys
40import tempfile
41import unittest
42_test_module = unittest
43
44# Suppresses the 'Import not at the top of the file' lint complaint.
45# pylint: disable-msg=C6204
46try:
47  import subprocess
48  _SUBPROCESS_MODULE_AVAILABLE = True
49except:
50  import popen2
51  _SUBPROCESS_MODULE_AVAILABLE = False
52# pylint: enable-msg=C6204
53
54GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
55
56IS_WINDOWS = os.name == 'nt'
57IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
58
59# The environment variable for specifying the path to the premature-exit file.
60PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE'
61
62environ = os.environ.copy()
63
64
65def SetEnvVar(env_var, value):
66  """Sets/unsets an environment variable to a given value."""
67
68  if value is not None:
69    environ[env_var] = value
70  elif env_var in environ:
71    del environ[env_var]
72
73
74# Here we expose a class from a particular module, depending on the
75# environment. The comment suppresses the 'Invalid variable name' lint
76# complaint.
77TestCase = _test_module.TestCase  # pylint: disable-msg=C6409
78
79# Initially maps a flag to its default value. After
80# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
81_flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
82             'build_dir': os.path.dirname(sys.argv[0])}
83_gtest_flags_are_parsed = False
84
85
86def _ParseAndStripGTestFlags(argv):
87  """Parses and strips Google Test flags from argv.  This is idempotent."""
88
89  # Suppresses the lint complaint about a global variable since we need it
90  # here to maintain module-wide state.
91  global _gtest_flags_are_parsed  # pylint: disable-msg=W0603
92  if _gtest_flags_are_parsed:
93    return
94
95  _gtest_flags_are_parsed = True
96  for flag in _flag_map:
97    # The environment variable overrides the default value.
98    if flag.upper() in os.environ:
99      _flag_map[flag] = os.environ[flag.upper()]
100
101    # The command line flag overrides the environment variable.
102    i = 1  # Skips the program name.
103    while i < len(argv):
104      prefix = '--' + flag + '='
105      if argv[i].startswith(prefix):
106        _flag_map[flag] = argv[i][len(prefix):]
107        del argv[i]
108        break
109      else:
110        # We don't increment i in case we just found a --gtest_* flag
111        # and removed it from argv.
112        i += 1
113
114
115def GetFlag(flag):
116  """Returns the value of the given flag."""
117
118  # In case GetFlag() is called before Main(), we always call
119  # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
120  # are parsed.
121  _ParseAndStripGTestFlags(sys.argv)
122
123  return _flag_map[flag]
124
125
126def GetSourceDir():
127  """Returns the absolute path of the directory where the .py files are."""
128
129  return os.path.abspath(GetFlag('source_dir'))
130
131
132def GetBuildDir():
133  """Returns the absolute path of the directory where the test binaries are."""
134
135  return os.path.abspath(GetFlag('build_dir'))
136
137
138_temp_dir = None
139
140def _RemoveTempDir():
141  if _temp_dir:
142    shutil.rmtree(_temp_dir, ignore_errors=True)
143
144atexit.register(_RemoveTempDir)
145
146
147def GetTempDir():
148  """Returns a directory for temporary files."""
149
150  global _temp_dir
151  if not _temp_dir:
152    _temp_dir = tempfile.mkdtemp()
153  return _temp_dir
154
155
156def GetTestExecutablePath(executable_name, build_dir=None):
157  """Returns the absolute path of the test binary given its name.
158
159  The function will print a message and abort the program if the resulting file
160  doesn't exist.
161
162  Args:
163    executable_name: name of the test binary that the test script runs.
164    build_dir:       directory where to look for executables, by default
165                     the result of GetBuildDir().
166
167  Returns:
168    The absolute path of the test binary.
169  """
170
171  path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
172                                      executable_name))
173  if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
174    path += '.exe'
175
176  if not os.path.exists(path):
177    message = (
178        'Unable to find the test binary "%s". Please make sure to provide\n'
179        'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
180        'environment variable.' % path)
181    print >> sys.stderr, message
182    sys.exit(1)
183
184  return path
185
186
187def GetExitStatus(exit_code):
188  """Returns the argument to exit(), or -1 if exit() wasn't called.
189
190  Args:
191    exit_code: the result value of os.system(command).
192  """
193
194  if os.name == 'nt':
195    # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
196    # the argument to exit() directly.
197    return exit_code
198  else:
199    # On Unix, os.WEXITSTATUS() must be used to extract the exit status
200    # from the result of os.system().
201    if os.WIFEXITED(exit_code):
202      return os.WEXITSTATUS(exit_code)
203    else:
204      return -1
205
206
207class Subprocess:
208  def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
209    """Changes into a specified directory, if provided, and executes a command.
210
211    Restores the old directory afterwards.
212
213    Args:
214      command:        The command to run, in the form of sys.argv.
215      working_dir:    The directory to change into.
216      capture_stderr: Determines whether to capture stderr in the output member
217                      or to discard it.
218      env:            Dictionary with environment to pass to the subprocess.
219
220    Returns:
221      An object that represents outcome of the executed process. It has the
222      following attributes:
223        terminated_by_signal   True iff the child process has been terminated
224                               by a signal.
225        signal                 Sygnal that terminated the child process.
226        exited                 True iff the child process exited normally.
227        exit_code              The code with which the child process exited.
228        output                 Child process's stdout and stderr output
229                               combined in a string.
230    """
231
232    # The subprocess module is the preferrable way of running programs
233    # since it is available and behaves consistently on all platforms,
234    # including Windows. But it is only available starting in python 2.4.
235    # In earlier python versions, we revert to the popen2 module, which is
236    # available in python 2.0 and later but doesn't provide required
237    # functionality (Popen4) under Windows. This allows us to support Mac
238    # OS X 10.4 Tiger, which has python 2.3 installed.
239    if _SUBPROCESS_MODULE_AVAILABLE:
240      if capture_stderr:
241        stderr = subprocess.STDOUT
242      else:
243        stderr = subprocess.PIPE
244
245      p = subprocess.Popen(command,
246                           stdout=subprocess.PIPE, stderr=stderr,
247                           cwd=working_dir, universal_newlines=True, env=env)
248      # communicate returns a tuple with the file obect for the child's
249      # output.
250      self.output = p.communicate()[0]
251      self._return_code = p.returncode
252    else:
253      old_dir = os.getcwd()
254
255      def _ReplaceEnvDict(dest, src):
256        # Changes made by os.environ.clear are not inheritable by child
257        # processes until Python 2.6. To produce inheritable changes we have
258        # to delete environment items with the del statement.
259        for key in dest.keys():
260          del dest[key]
261        dest.update(src)
262
263      # When 'env' is not None, backup the environment variables and replace
264      # them with the passed 'env'. When 'env' is None, we simply use the
265      # current 'os.environ' for compatibility with the subprocess.Popen
266      # semantics used above.
267      if env is not None:
268        old_environ = os.environ.copy()
269        _ReplaceEnvDict(os.environ, env)
270
271      try:
272        if working_dir is not None:
273          os.chdir(working_dir)
274        if capture_stderr:
275          p = popen2.Popen4(command)
276        else:
277          p = popen2.Popen3(command)
278        p.tochild.close()
279        self.output = p.fromchild.read()
280        ret_code = p.wait()
281      finally:
282        os.chdir(old_dir)
283
284        # Restore the old environment variables
285        # if they were replaced.
286        if env is not None:
287          _ReplaceEnvDict(os.environ, old_environ)
288
289      # Converts ret_code to match the semantics of
290      # subprocess.Popen.returncode.
291      if os.WIFSIGNALED(ret_code):
292        self._return_code = -os.WTERMSIG(ret_code)
293      else:  # os.WIFEXITED(ret_code) should return True here.
294        self._return_code = os.WEXITSTATUS(ret_code)
295
296    if self._return_code < 0:
297      self.terminated_by_signal = True
298      self.exited = False
299      self.signal = -self._return_code
300    else:
301      self.terminated_by_signal = False
302      self.exited = True
303      self.exit_code = self._return_code
304
305
306def Main():
307  """Runs the unit test."""
308
309  # We must call _ParseAndStripGTestFlags() before calling
310  # unittest.main().  Otherwise the latter will be confused by the
311  # --gtest_* flags.
312  _ParseAndStripGTestFlags(sys.argv)
313  # The tested binaries should not be writing XML output files unless the
314  # script explicitly instructs them to.
315  # TODO(vladl@google.com): Move this into Subprocess when we implement
316  # passing environment into it as a parameter.
317  if GTEST_OUTPUT_VAR_NAME in os.environ:
318    del os.environ[GTEST_OUTPUT_VAR_NAME]
319
320  _test_module.main()
trunk/3rdparty/googletest/googletest/test/gtest_throw_on_failure_ex_test.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Tests Google Test's throw-on-failure mode with exceptions enabled.
33
34#include "gtest/gtest.h"
35
36#include <stdlib.h>
37#include <stdio.h>
38#include <string.h>
39#include <stdexcept>
40
41// Prints the given failure message and exits the program with
42// non-zero.  We use this instead of a Google Test assertion to
43// indicate a failure, as the latter is been tested and cannot be
44// relied on.
45void Fail(const char* msg) {
46  printf("FAILURE: %s\n", msg);
47  fflush(stdout);
48  exit(1);
49}
50
51// Tests that an assertion failure throws a subclass of
52// std::runtime_error.
53void TestFailureThrowsRuntimeError() {
54  testing::GTEST_FLAG(throw_on_failure) = true;
55
56  // A successful assertion shouldn't throw.
57  try {
58    EXPECT_EQ(3, 3);
59  } catch(...) {
60    Fail("A successful assertion wrongfully threw.");
61  }
62
63  // A failed assertion should throw a subclass of std::runtime_error.
64  try {
65    EXPECT_EQ(2, 3) << "Expected failure";
66  } catch(const std::runtime_error& e) {
67    if (strstr(e.what(), "Expected failure") != NULL)
68      return;
69
70    printf("%s",
71           "A failed assertion did throw an exception of the right type, "
72           "but the message is incorrect.  Instead of containing \"Expected "
73           "failure\", it is:\n");
74    Fail(e.what());
75  } catch(...) {
76    Fail("A failed assertion threw the wrong type of exception.");
77  }
78  Fail("A failed assertion should've thrown but didn't.");
79}
80
81int main(int argc, char** argv) {
82  testing::InitGoogleTest(&argc, argv);
83
84  // We want to ensure that people can use Google Test assertions in
85  // other testing frameworks, as long as they initialize Google Test
86  // properly and set the thrown-on-failure mode.  Therefore, we don't
87  // use Google Test's constructs for defining and running tests
88  // (e.g. TEST and RUN_ALL_TESTS) here.
89
90  TestFailureThrowsRuntimeError();
91  return 0;
92}
trunk/3rdparty/googletest/googletest/test/gtest_throw_on_failure_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2009, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Tests Google Test's throw-on-failure mode with exceptions disabled.
33
34This script invokes gtest_throw_on_failure_test_ (a program written with
35Google Test) with different environments and command line flags.
36"""
37
38__author__ = 'wan@google.com (Zhanyong Wan)'
39
40import os
41import gtest_test_utils
42
43
44# Constants.
45
46# The command line flag for enabling/disabling the throw-on-failure mode.
47THROW_ON_FAILURE = 'gtest_throw_on_failure'
48
49# Path to the gtest_throw_on_failure_test_ program, compiled with
50# exceptions disabled.
51EXE_PATH = gtest_test_utils.GetTestExecutablePath(
52    'gtest_throw_on_failure_test_')
53
54
55# Utilities.
56
57
58def SetEnvVar(env_var, value):
59  """Sets an environment variable to a given value; unsets it when the
60  given value is None.
61  """
62
63  env_var = env_var.upper()
64  if value is not None:
65    os.environ[env_var] = value
66  elif env_var in os.environ:
67    del os.environ[env_var]
68
69
70def Run(command):
71  """Runs a command; returns True/False if its exit code is/isn't 0."""
72
73  print 'Running "%s". . .' % ' '.join(command)
74  p = gtest_test_utils.Subprocess(command)
75  return p.exited and p.exit_code == 0
76
77
78# The tests.  TODO(wan@google.com): refactor the class to share common
79# logic with code in gtest_break_on_failure_unittest.py.
80class ThrowOnFailureTest(gtest_test_utils.TestCase):
81  """Tests the throw-on-failure mode."""
82
83  def RunAndVerify(self, env_var_value, flag_value, should_fail):
84    """Runs gtest_throw_on_failure_test_ and verifies that it does
85    (or does not) exit with a non-zero code.
86
87    Args:
88      env_var_value:    value of the GTEST_BREAK_ON_FAILURE environment
89                        variable; None if the variable should be unset.
90      flag_value:       value of the --gtest_break_on_failure flag;
91                        None if the flag should not be present.
92      should_fail:      True iff the program is expected to fail.
93    """
94
95    SetEnvVar(THROW_ON_FAILURE, env_var_value)
96
97    if env_var_value is None:
98      env_var_value_msg = ' is not set'
99    else:
100      env_var_value_msg = '=' + env_var_value
101
102    if flag_value is None:
103      flag = ''
104    elif flag_value == '0':
105      flag = '--%s=0' % THROW_ON_FAILURE
106    else:
107      flag = '--%s' % THROW_ON_FAILURE
108
109    command = [EXE_PATH]
110    if flag:
111      command.append(flag)
112
113    if should_fail:
114      should_or_not = 'should'
115    else:
116      should_or_not = 'should not'
117
118    failed = not Run(command)
119
120    SetEnvVar(THROW_ON_FAILURE, None)
121
122    msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero '
123           'exit code.' %
124           (THROW_ON_FAILURE, env_var_value_msg, ' '.join(command),
125            should_or_not))
126    self.assert_(failed == should_fail, msg)
127
128  def testDefaultBehavior(self):
129    """Tests the behavior of the default mode."""
130
131    self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False)
132
133  def testThrowOnFailureEnvVar(self):
134    """Tests using the GTEST_THROW_ON_FAILURE environment variable."""
135
136    self.RunAndVerify(env_var_value='0',
137                      flag_value=None,
138                      should_fail=False)
139    self.RunAndVerify(env_var_value='1',
140                      flag_value=None,
141                      should_fail=True)
142
143  def testThrowOnFailureFlag(self):
144    """Tests using the --gtest_throw_on_failure flag."""
145
146    self.RunAndVerify(env_var_value=None,
147                      flag_value='0',
148                      should_fail=False)
149    self.RunAndVerify(env_var_value=None,
150                      flag_value='1',
151                      should_fail=True)
152
153  def testThrowOnFailureFlagOverridesEnvVar(self):
154    """Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE."""
155
156    self.RunAndVerify(env_var_value='0',
157                      flag_value='0',
158                      should_fail=False)
159    self.RunAndVerify(env_var_value='0',
160                      flag_value='1',
161                      should_fail=True)
162    self.RunAndVerify(env_var_value='1',
163                      flag_value='0',
164                      should_fail=False)
165    self.RunAndVerify(env_var_value='1',
166                      flag_value='1',
167                      should_fail=True)
168
169
170if __name__ == '__main__':
171  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_throw_on_failure_test_.cc
r0r249096
1// Copyright 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Tests Google Test's throw-on-failure mode with exceptions disabled.
33//
34// This program must be compiled with exceptions disabled.  It will be
35// invoked by gtest_throw_on_failure_test.py, and is expected to exit
36// with non-zero in the throw-on-failure mode or 0 otherwise.
37
38#include "gtest/gtest.h"
39
40#include <stdio.h>                      // for fflush, fprintf, NULL, etc.
41#include <stdlib.h>                     // for exit
42#include <exception>                    // for set_terminate
43
44// This terminate handler aborts the program using exit() rather than abort().
45// This avoids showing pop-ups on Windows systems and core dumps on Unix-like
46// ones.
47void TerminateHandler() {
48  fprintf(stderr, "%s\n", "Unhandled C++ exception terminating the program.");
49  fflush(NULL);
50  exit(1);
51}
52
53int main(int argc, char** argv) {
54#if GTEST_HAS_EXCEPTIONS
55  std::set_terminate(&TerminateHandler);
56#endif
57  testing::InitGoogleTest(&argc, argv);
58
59  // We want to ensure that people can use Google Test assertions in
60  // other testing frameworks, as long as they initialize Google Test
61  // properly and set the throw-on-failure mode.  Therefore, we don't
62  // use Google Test's constructs for defining and running tests
63  // (e.g. TEST and RUN_ALL_TESTS) here.
64
65  // In the throw-on-failure mode with exceptions disabled, this
66  // assertion will cause the program to exit with a non-zero code.
67  EXPECT_EQ(2, 3);
68
69  // When not in the throw-on-failure mode, the control will reach
70  // here.
71  return 0;
72}
trunk/3rdparty/googletest/googletest/test/gtest_uninitialized_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Verifies that Google Test warns the user when not initialized properly."""
33
34__author__ = 'wan@google.com (Zhanyong Wan)'
35
36import gtest_test_utils
37
38
39COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_')
40
41
42def Assert(condition):
43  if not condition:
44    raise AssertionError
45
46
47def AssertEq(expected, actual):
48  if expected != actual:
49    print 'Expected: %s' % (expected,)
50    print '  Actual: %s' % (actual,)
51    raise AssertionError
52
53
54def TestExitCodeAndOutput(command):
55  """Runs the given command and verifies its exit code and output."""
56
57  # Verifies that 'command' exits with code 1.
58  p = gtest_test_utils.Subprocess(command)
59  Assert(p.exited)
60  AssertEq(1, p.exit_code)
61  Assert('InitGoogleTest' in p.output)
62
63
64class GTestUninitializedTest(gtest_test_utils.TestCase):
65  def testExitCodeAndOutput(self):
66    TestExitCodeAndOutput(COMMAND)
67
68
69if __name__ == '__main__':
70  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_uninitialized_test_.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32#include "gtest/gtest.h"
33
34TEST(DummyTest, Dummy) {
35  // This test doesn't verify anything.  We just need it to create a
36  // realistic stage for testing the behavior of Google Test when
37  // RUN_ALL_TESTS() is called without testing::InitGoogleTest() being
38  // called first.
39}
40
41int main() {
42  return RUN_ALL_TESTS();
43}
trunk/3rdparty/googletest/googletest/test/gtest_unittest.cc
r0r249096
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for Google Test itself.  This verifies that the basic constructs of
33// Google Test work.
34
35#include "gtest/gtest.h"
36
37// Verifies that the command line flag variables can be accessed
38// in code once <gtest/gtest.h> has been #included.
39// Do not move it after other #includes.
40TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41  bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
42      || testing::GTEST_FLAG(break_on_failure)
43      || testing::GTEST_FLAG(catch_exceptions)
44      || testing::GTEST_FLAG(color) != "unknown"
45      || testing::GTEST_FLAG(filter) != "unknown"
46      || testing::GTEST_FLAG(list_tests)
47      || testing::GTEST_FLAG(output) != "unknown"
48      || testing::GTEST_FLAG(print_time)
49      || testing::GTEST_FLAG(random_seed)
50      || testing::GTEST_FLAG(repeat) > 0
51      || testing::GTEST_FLAG(show_internal_stack_frames)
52      || testing::GTEST_FLAG(shuffle)
53      || testing::GTEST_FLAG(stack_trace_depth) > 0
54      || testing::GTEST_FLAG(stream_result_to) != "unknown"
55      || testing::GTEST_FLAG(throw_on_failure);
56  EXPECT_TRUE(dummy || !dummy);  // Suppresses warning that dummy is unused.
57}
58
59#include <limits.h>  // For INT_MAX.
60#include <stdlib.h>
61#include <string.h>
62#include <time.h>
63
64#include <map>
65#include <vector>
66#include <ostream>
67
68#include "gtest/gtest-spi.h"
69
70// Indicates that this translation unit is part of Google Test's
71// implementation.  It must come before gtest-internal-inl.h is
72// included, or there will be a compiler error.  This trick is to
73// prevent a user from accidentally including gtest-internal-inl.h in
74// his code.
75#define GTEST_IMPLEMENTATION_ 1
76#include "src/gtest-internal-inl.h"
77#undef GTEST_IMPLEMENTATION_
78
79namespace testing {
80namespace internal {
81
82#if GTEST_CAN_STREAM_RESULTS_
83
84class StreamingListenerTest : public Test {
85 public:
86  class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
87   public:
88    // Sends a string to the socket.
89    virtual void Send(const string& message) { output_ += message; }
90
91    string output_;
92  };
93
94  StreamingListenerTest()
95      : fake_sock_writer_(new FakeSocketWriter),
96        streamer_(fake_sock_writer_),
97        test_info_obj_("FooTest", "Bar", NULL, NULL,
98                       CodeLocation(__FILE__, __LINE__), 0, NULL) {}
99
100 protected:
101  string* output() { return &(fake_sock_writer_->output_); }
102
103  FakeSocketWriter* const fake_sock_writer_;
104  StreamingListener streamer_;
105  UnitTest unit_test_;
106  TestInfo test_info_obj_;  // The name test_info_ was taken by testing::Test.
107};
108
109TEST_F(StreamingListenerTest, OnTestProgramEnd) {
110  *output() = "";
111  streamer_.OnTestProgramEnd(unit_test_);
112  EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
113}
114
115TEST_F(StreamingListenerTest, OnTestIterationEnd) {
116  *output() = "";
117  streamer_.OnTestIterationEnd(unit_test_, 42);
118  EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
119}
120
121TEST_F(StreamingListenerTest, OnTestCaseStart) {
122  *output() = "";
123  streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL));
124  EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
125}
126
127TEST_F(StreamingListenerTest, OnTestCaseEnd) {
128  *output() = "";
129  streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL));
130  EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
131}
132
133TEST_F(StreamingListenerTest, OnTestStart) {
134  *output() = "";
135  streamer_.OnTestStart(test_info_obj_);
136  EXPECT_EQ("event=TestStart&name=Bar\n", *output());
137}
138
139TEST_F(StreamingListenerTest, OnTestEnd) {
140  *output() = "";
141  streamer_.OnTestEnd(test_info_obj_);
142  EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
143}
144
145TEST_F(StreamingListenerTest, OnTestPartResult) {
146  *output() = "";
147  streamer_.OnTestPartResult(TestPartResult(
148      TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
149
150  // Meta characters in the failure message should be properly escaped.
151  EXPECT_EQ(
152      "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
153      *output());
154}
155
156#endif  // GTEST_CAN_STREAM_RESULTS_
157
158// Provides access to otherwise private parts of the TestEventListeners class
159// that are needed to test it.
160class TestEventListenersAccessor {
161 public:
162  static TestEventListener* GetRepeater(TestEventListeners* listeners) {
163    return listeners->repeater();
164  }
165
166  static void SetDefaultResultPrinter(TestEventListeners* listeners,
167                                      TestEventListener* listener) {
168    listeners->SetDefaultResultPrinter(listener);
169  }
170  static void SetDefaultXmlGenerator(TestEventListeners* listeners,
171                                     TestEventListener* listener) {
172    listeners->SetDefaultXmlGenerator(listener);
173  }
174
175  static bool EventForwardingEnabled(const TestEventListeners& listeners) {
176    return listeners.EventForwardingEnabled();
177  }
178
179  static void SuppressEventForwarding(TestEventListeners* listeners) {
180    listeners->SuppressEventForwarding();
181  }
182};
183
184class UnitTestRecordPropertyTestHelper : public Test {
185 protected:
186  UnitTestRecordPropertyTestHelper() {}
187
188  // Forwards to UnitTest::RecordProperty() to bypass access controls.
189  void UnitTestRecordProperty(const char* key, const std::string& value) {
190    unit_test_.RecordProperty(key, value);
191  }
192
193  UnitTest unit_test_;
194};
195
196}  // namespace internal
197}  // namespace testing
198
199using testing::AssertionFailure;
200using testing::AssertionResult;
201using testing::AssertionSuccess;
202using testing::DoubleLE;
203using testing::EmptyTestEventListener;
204using testing::Environment;
205using testing::FloatLE;
206using testing::GTEST_FLAG(also_run_disabled_tests);
207using testing::GTEST_FLAG(break_on_failure);
208using testing::GTEST_FLAG(catch_exceptions);
209using testing::GTEST_FLAG(color);
210using testing::GTEST_FLAG(death_test_use_fork);
211using testing::GTEST_FLAG(filter);
212using testing::GTEST_FLAG(list_tests);
213using testing::GTEST_FLAG(output);
214using testing::GTEST_FLAG(print_time);
215using testing::GTEST_FLAG(random_seed);
216using testing::GTEST_FLAG(repeat);
217using testing::GTEST_FLAG(show_internal_stack_frames);
218using testing::GTEST_FLAG(shuffle);
219using testing::GTEST_FLAG(stack_trace_depth);
220using testing::GTEST_FLAG(stream_result_to);
221using testing::GTEST_FLAG(throw_on_failure);
222using testing::IsNotSubstring;
223using testing::IsSubstring;
224using testing::Message;
225using testing::ScopedFakeTestPartResultReporter;
226using testing::StaticAssertTypeEq;
227using testing::Test;
228using testing::TestCase;
229using testing::TestEventListeners;
230using testing::TestInfo;
231using testing::TestPartResult;
232using testing::TestPartResultArray;
233using testing::TestProperty;
234using testing::TestResult;
235using testing::TimeInMillis;
236using testing::UnitTest;
237using testing::internal::AddReference;
238using testing::internal::AlwaysFalse;
239using testing::internal::AlwaysTrue;
240using testing::internal::AppendUserMessage;
241using testing::internal::ArrayAwareFind;
242using testing::internal::ArrayEq;
243using testing::internal::CodePointToUtf8;
244using testing::internal::CompileAssertTypesEqual;
245using testing::internal::CopyArray;
246using testing::internal::CountIf;
247using testing::internal::EqFailure;
248using testing::internal::FloatingPoint;
249using testing::internal::ForEach;
250using testing::internal::FormatEpochTimeInMillisAsIso8601;
251using testing::internal::FormatTimeInMillisAsSeconds;
252using testing::internal::GTestFlagSaver;
253using testing::internal::GetCurrentOsStackTraceExceptTop;
254using testing::internal::GetElementOr;
255using testing::internal::GetNextRandomSeed;
256using testing::internal::GetRandomSeedFromFlag;
257using testing::internal::GetTestTypeId;
258using testing::internal::GetTimeInMillis;
259using testing::internal::GetTypeId;
260using testing::internal::GetUnitTestImpl;
261using testing::internal::ImplicitlyConvertible;
262using testing::internal::Int32;
263using testing::internal::Int32FromEnvOrDie;
264using testing::internal::IsAProtocolMessage;
265using testing::internal::IsContainer;
266using testing::internal::IsContainerTest;
267using testing::internal::IsNotContainer;
268using testing::internal::NativeArray;
269using testing::internal::ParseInt32Flag;
270using testing::internal::RelationToSourceCopy;
271using testing::internal::RelationToSourceReference;
272using testing::internal::RemoveConst;
273using testing::internal::RemoveReference;
274using testing::internal::ShouldRunTestOnShard;
275using testing::internal::ShouldShard;
276using testing::internal::ShouldUseColor;
277using testing::internal::Shuffle;
278using testing::internal::ShuffleRange;
279using testing::internal::SkipPrefix;
280using testing::internal::StreamableToString;
281using testing::internal::String;
282using testing::internal::TestEventListenersAccessor;
283using testing::internal::TestResultAccessor;
284using testing::internal::UInt32;
285using testing::internal::WideStringToUtf8;
286using testing::internal::edit_distance::CalculateOptimalEdits;
287using testing::internal::edit_distance::CreateUnifiedDiff;
288using testing::internal::edit_distance::EditType;
289using testing::internal::kMaxRandomSeed;
290using testing::internal::kTestTypeIdInGoogleTest;
291using testing::kMaxStackTraceDepth;
292
293#if GTEST_HAS_STREAM_REDIRECTION
294using testing::internal::CaptureStdout;
295using testing::internal::GetCapturedStdout;
296#endif
297
298#if GTEST_IS_THREADSAFE
299using testing::internal::ThreadWithParam;
300#endif
301
302class TestingVector : public std::vector<int> {
303};
304
305::std::ostream& operator<<(::std::ostream& os,
306                           const TestingVector& vector) {
307  os << "{ ";
308  for (size_t i = 0; i < vector.size(); i++) {
309    os << vector[i] << " ";
310  }
311  os << "}";
312  return os;
313}
314
315// This line tests that we can define tests in an unnamed namespace.
316namespace {
317
318TEST(GetRandomSeedFromFlagTest, HandlesZero) {
319  const int seed = GetRandomSeedFromFlag(0);
320  EXPECT_LE(1, seed);
321  EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
322}
323
324TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
325  EXPECT_EQ(1, GetRandomSeedFromFlag(1));
326  EXPECT_EQ(2, GetRandomSeedFromFlag(2));
327  EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
328  EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
329            GetRandomSeedFromFlag(kMaxRandomSeed));
330}
331
332TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
333  const int seed1 = GetRandomSeedFromFlag(-1);
334  EXPECT_LE(1, seed1);
335  EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
336
337  const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
338  EXPECT_LE(1, seed2);
339  EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
340}
341
342TEST(GetNextRandomSeedTest, WorksForValidInput) {
343  EXPECT_EQ(2, GetNextRandomSeed(1));
344  EXPECT_EQ(3, GetNextRandomSeed(2));
345  EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
346            GetNextRandomSeed(kMaxRandomSeed - 1));
347  EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
348
349  // We deliberately don't test GetNextRandomSeed() with invalid
350  // inputs, as that requires death tests, which are expensive.  This
351  // is fine as GetNextRandomSeed() is internal and has a
352  // straightforward definition.
353}
354
355static void ClearCurrentTestPartResults() {
356  TestResultAccessor::ClearTestPartResults(
357      GetUnitTestImpl()->current_test_result());
358}
359
360// Tests GetTypeId.
361
362TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
363  EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
364  EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
365}
366
367class SubClassOfTest : public Test {};
368class AnotherSubClassOfTest : public Test {};
369
370TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
371  EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
372  EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
373  EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
374  EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
375  EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
376  EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
377}
378
379// Verifies that GetTestTypeId() returns the same value, no matter it
380// is called from inside Google Test or outside of it.
381TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
382  EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
383}
384
385// Tests FormatTimeInMillisAsSeconds().
386
387TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
388  EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
389}
390
391TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
392  EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
393  EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
394  EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
395  EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
396  EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
397}
398
399TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
400  EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
401  EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
402  EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
403  EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
404  EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
405}
406
407// Tests FormatEpochTimeInMillisAsIso8601().  The correctness of conversion
408// for particular dates below was verified in Python using
409// datetime.datetime.fromutctimestamp(<timetamp>/1000).
410
411// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
412// have to set up a particular timezone to obtain predictable results.
413class FormatEpochTimeInMillisAsIso8601Test : public Test {
414 public:
415  // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
416  // 32 bits, even when 64-bit integer types are available.  We have to
417  // force the constants to have a 64-bit type here.
418  static const TimeInMillis kMillisPerSec = 1000;
419
420 private:
421  virtual void SetUp() {
422    saved_tz_ = NULL;
423
424    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* getenv, strdup: deprecated */)
425    if (getenv("TZ"))
426      saved_tz_ = strdup(getenv("TZ"));
427    GTEST_DISABLE_MSC_WARNINGS_POP_()
428
429    // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use.  We
430    // cannot use the local time zone because the function's output depends
431    // on the time zone.
432    SetTimeZone("UTC+00");
433  }
434
435  virtual void TearDown() {
436    SetTimeZone(saved_tz_);
437    free(const_cast<char*>(saved_tz_));
438    saved_tz_ = NULL;
439  }
440
441  static void SetTimeZone(const char* time_zone) {
442    // tzset() distinguishes between the TZ variable being present and empty
443    // and not being present, so we have to consider the case of time_zone
444    // being NULL.
445#if _MSC_VER
446    // ...Unless it's MSVC, whose standard library's _putenv doesn't
447    // distinguish between an empty and a missing variable.
448    const std::string env_var =
449        std::string("TZ=") + (time_zone ? time_zone : "");
450    _putenv(env_var.c_str());
451    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
452    tzset();
453    GTEST_DISABLE_MSC_WARNINGS_POP_()
454#else
455    if (time_zone) {
456      setenv(("TZ"), time_zone, 1);
457    } else {
458      unsetenv("TZ");
459    }
460    tzset();
461#endif
462  }
463
464  const char* saved_tz_;
465};
466
467const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
468
469TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
470  EXPECT_EQ("2011-10-31T18:52:42",
471            FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
472}
473
474TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
475  EXPECT_EQ(
476      "2011-10-31T18:52:42",
477      FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
478}
479
480TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
481  EXPECT_EQ("2011-09-03T05:07:02",
482            FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
483}
484
485TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
486  EXPECT_EQ("2011-09-28T17:08:22",
487            FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
488}
489
490TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
491  EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
492}
493
494#if GTEST_CAN_COMPARE_NULL
495
496# ifdef __BORLANDC__
497// Silences warnings: "Condition is always true", "Unreachable code"
498#  pragma option push -w-ccc -w-rch
499# endif
500
501// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
502// pointer literal.
503TEST(NullLiteralTest, IsTrueForNullLiterals) {
504  EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
505  EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
506  EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
507  EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
508}
509
510// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
511// pointer literal.
512TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
513  EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
514  EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
515  EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
516  EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
517}
518
519# ifdef __BORLANDC__
520// Restores warnings after previous "#pragma option push" suppressed them.
521#  pragma option pop
522# endif
523
524#endif  // GTEST_CAN_COMPARE_NULL
525//
526// Tests CodePointToUtf8().
527
528// Tests that the NUL character L'\0' is encoded correctly.
529TEST(CodePointToUtf8Test, CanEncodeNul) {
530  EXPECT_EQ("", CodePointToUtf8(L'\0'));
531}
532
533// Tests that ASCII characters are encoded correctly.
534TEST(CodePointToUtf8Test, CanEncodeAscii) {
535  EXPECT_EQ("a", CodePointToUtf8(L'a'));
536  EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
537  EXPECT_EQ("&", CodePointToUtf8(L'&'));
538  EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
539}
540
541// Tests that Unicode code-points that have 8 to 11 bits are encoded
542// as 110xxxxx 10xxxxxx.
543TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
544  // 000 1101 0011 => 110-00011 10-010011
545  EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
546
547  // 101 0111 0110 => 110-10101 10-110110
548  // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
549  // in wide strings and wide chars. In order to accomodate them, we have to
550  // introduce such character constants as integers.
551  EXPECT_EQ("\xD5\xB6",
552            CodePointToUtf8(static_cast<wchar_t>(0x576)));
553}
554
555// Tests that Unicode code-points that have 12 to 16 bits are encoded
556// as 1110xxxx 10xxxxxx 10xxxxxx.
557TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
558  // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
559  EXPECT_EQ("\xE0\xA3\x93",
560            CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
561
562  // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
563  EXPECT_EQ("\xEC\x9D\x8D",
564            CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
565}
566
567#if !GTEST_WIDE_STRING_USES_UTF16_
568// Tests in this group require a wchar_t to hold > 16 bits, and thus
569// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
570// 16-bit wide. This code may not compile on those systems.
571
572// Tests that Unicode code-points that have 17 to 21 bits are encoded
573// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
574TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
575  // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
576  EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
577
578  // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
579  EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
580
581  // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
582  EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
583}
584
585// Tests that encoding an invalid code-point generates the expected result.
586TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
587  EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
588}
589
590#endif  // !GTEST_WIDE_STRING_USES_UTF16_
591
592// Tests WideStringToUtf8().
593
594// Tests that the NUL character L'\0' is encoded correctly.
595TEST(WideStringToUtf8Test, CanEncodeNul) {
596  EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
597  EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
598}
599
600// Tests that ASCII strings are encoded correctly.
601TEST(WideStringToUtf8Test, CanEncodeAscii) {
602  EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
603  EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
604  EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
605  EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
606}
607
608// Tests that Unicode code-points that have 8 to 11 bits are encoded
609// as 110xxxxx 10xxxxxx.
610TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
611  // 000 1101 0011 => 110-00011 10-010011
612  EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
613  EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
614
615  // 101 0111 0110 => 110-10101 10-110110
616  const wchar_t s[] = { 0x576, '\0' };
617  EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
618  EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
619}
620
621// Tests that Unicode code-points that have 12 to 16 bits are encoded
622// as 1110xxxx 10xxxxxx 10xxxxxx.
623TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
624  // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
625  const wchar_t s1[] = { 0x8D3, '\0' };
626  EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
627  EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
628
629  // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
630  const wchar_t s2[] = { 0xC74D, '\0' };
631  EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
632  EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
633}
634
635// Tests that the conversion stops when the function encounters \0 character.
636TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
637  EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
638}
639
640// Tests that the conversion stops when the function reaches the limit
641// specified by the 'length' parameter.
642TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
643  EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
644}
645
646#if !GTEST_WIDE_STRING_USES_UTF16_
647// Tests that Unicode code-points that have 17 to 21 bits are encoded
648// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
649// on the systems using UTF-16 encoding.
650TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
651  // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
652  EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
653  EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
654
655  // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
656  EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
657  EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
658}
659
660// Tests that encoding an invalid code-point generates the expected result.
661TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
662  EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
663               WideStringToUtf8(L"\xABCDFF", -1).c_str());
664}
665#else  // !GTEST_WIDE_STRING_USES_UTF16_
666// Tests that surrogate pairs are encoded correctly on the systems using
667// UTF-16 encoding in the wide strings.
668TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
669  const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
670  EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
671}
672
673// Tests that encoding an invalid UTF-16 surrogate pair
674// generates the expected result.
675TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
676  // Leading surrogate is at the end of the string.
677  const wchar_t s1[] = { 0xD800, '\0' };
678  EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
679  // Leading surrogate is not followed by the trailing surrogate.
680  const wchar_t s2[] = { 0xD800, 'M', '\0' };
681  EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
682  // Trailing surrogate appearas without a leading surrogate.
683  const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
684  EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
685}
686#endif  // !GTEST_WIDE_STRING_USES_UTF16_
687
688// Tests that codepoint concatenation works correctly.
689#if !GTEST_WIDE_STRING_USES_UTF16_
690TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
691  const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
692  EXPECT_STREQ(
693      "\xF4\x88\x98\xB4"
694          "\xEC\x9D\x8D"
695          "\n"
696          "\xD5\xB6"
697          "\xE0\xA3\x93"
698          "\xF4\x88\x98\xB4",
699      WideStringToUtf8(s, -1).c_str());
700}
701#else
702TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
703  const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
704  EXPECT_STREQ(
705      "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
706      WideStringToUtf8(s, -1).c_str());
707}
708#endif  // !GTEST_WIDE_STRING_USES_UTF16_
709
710// Tests the Random class.
711
712TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
713  testing::internal::Random random(42);
714  EXPECT_DEATH_IF_SUPPORTED(
715      random.Generate(0),
716      "Cannot generate a number in the range \\[0, 0\\)");
717  EXPECT_DEATH_IF_SUPPORTED(
718      random.Generate(testing::internal::Random::kMaxRange + 1),
719      "Generation of a number in \\[0, 2147483649\\) was requested, "
720      "but this can only generate numbers in \\[0, 2147483648\\)");
721}
722
723TEST(RandomTest, GeneratesNumbersWithinRange) {
724  const UInt32 kRange = 10000;
725  testing::internal::Random random(12345);
726  for (int i = 0; i < 10; i++) {
727    EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
728  }
729
730  testing::internal::Random random2(testing::internal::Random::kMaxRange);
731  for (int i = 0; i < 10; i++) {
732    EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
733  }
734}
735
736TEST(RandomTest, RepeatsWhenReseeded) {
737  const int kSeed = 123;
738  const int kArraySize = 10;
739  const UInt32 kRange = 10000;
740  UInt32 values[kArraySize];
741
742  testing::internal::Random random(kSeed);
743  for (int i = 0; i < kArraySize; i++) {
744    values[i] = random.Generate(kRange);
745  }
746
747  random.Reseed(kSeed);
748  for (int i = 0; i < kArraySize; i++) {
749    EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
750  }
751}
752
753// Tests STL container utilities.
754
755// Tests CountIf().
756
757static bool IsPositive(int n) { return n > 0; }
758
759TEST(ContainerUtilityTest, CountIf) {
760  std::vector<int> v;
761  EXPECT_EQ(0, CountIf(v, IsPositive));  // Works for an empty container.
762
763  v.push_back(-1);
764  v.push_back(0);
765  EXPECT_EQ(0, CountIf(v, IsPositive));  // Works when no value satisfies.
766
767  v.push_back(2);
768  v.push_back(-10);
769  v.push_back(10);
770  EXPECT_EQ(2, CountIf(v, IsPositive));
771}
772
773// Tests ForEach().
774
775static int g_sum = 0;
776static void Accumulate(int n) { g_sum += n; }
777
778TEST(ContainerUtilityTest, ForEach) {
779  std::vector<int> v;
780  g_sum = 0;
781  ForEach(v, Accumulate);
782  EXPECT_EQ(0, g_sum);  // Works for an empty container;
783
784  g_sum = 0;
785  v.push_back(1);
786  ForEach(v, Accumulate);
787  EXPECT_EQ(1, g_sum);  // Works for a container with one element.
788
789  g_sum = 0;
790  v.push_back(20);
791  v.push_back(300);
792  ForEach(v, Accumulate);
793  EXPECT_EQ(321, g_sum);
794}
795
796// Tests GetElementOr().
797TEST(ContainerUtilityTest, GetElementOr) {
798  std::vector<char> a;
799  EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
800
801  a.push_back('a');
802  a.push_back('b');
803  EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
804  EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
805  EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
806  EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
807}
808
809TEST(ContainerUtilityDeathTest, ShuffleRange) {
810  std::vector<int> a;
811  a.push_back(0);
812  a.push_back(1);
813  a.push_back(2);
814  testing::internal::Random random(1);
815
816  EXPECT_DEATH_IF_SUPPORTED(
817      ShuffleRange(&random, -1, 1, &a),
818      "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
819  EXPECT_DEATH_IF_SUPPORTED(
820      ShuffleRange(&random, 4, 4, &a),
821      "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
822  EXPECT_DEATH_IF_SUPPORTED(
823      ShuffleRange(&random, 3, 2, &a),
824      "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
825  EXPECT_DEATH_IF_SUPPORTED(
826      ShuffleRange(&random, 3, 4, &a),
827      "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
828}
829
830class VectorShuffleTest : public Test {
831 protected:
832  static const int kVectorSize = 20;
833
834  VectorShuffleTest() : random_(1) {
835    for (int i = 0; i < kVectorSize; i++) {
836      vector_.push_back(i);
837    }
838  }
839
840  static bool VectorIsCorrupt(const TestingVector& vector) {
841    if (kVectorSize != static_cast<int>(vector.size())) {
842      return true;
843    }
844
845    bool found_in_vector[kVectorSize] = { false };
846    for (size_t i = 0; i < vector.size(); i++) {
847      const int e = vector[i];
848      if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
849        return true;
850      }
851      found_in_vector[e] = true;
852    }
853
854    // Vector size is correct, elements' range is correct, no
855    // duplicate elements.  Therefore no corruption has occurred.
856    return false;
857  }
858
859  static bool VectorIsNotCorrupt(const TestingVector& vector) {
860    return !VectorIsCorrupt(vector);
861  }
862
863  static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
864    for (int i = begin; i < end; i++) {
865      if (i != vector[i]) {
866        return true;
867      }
868    }
869    return false;
870  }
871
872  static bool RangeIsUnshuffled(
873      const TestingVector& vector, int begin, int end) {
874    return !RangeIsShuffled(vector, begin, end);
875  }
876
877  static bool VectorIsShuffled(const TestingVector& vector) {
878    return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
879  }
880
881  static bool VectorIsUnshuffled(const TestingVector& vector) {
882    return !VectorIsShuffled(vector);
883  }
884
885  testing::internal::Random random_;
886  TestingVector vector_;
887};  // class VectorShuffleTest
888
889const int VectorShuffleTest::kVectorSize;
890
891TEST_F(VectorShuffleTest, HandlesEmptyRange) {
892  // Tests an empty range at the beginning...
893  ShuffleRange(&random_, 0, 0, &vector_);
894  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
895  ASSERT_PRED1(VectorIsUnshuffled, vector_);
896
897  // ...in the middle...
898  ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
899  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
900  ASSERT_PRED1(VectorIsUnshuffled, vector_);
901
902  // ...at the end...
903  ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
904  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
905  ASSERT_PRED1(VectorIsUnshuffled, vector_);
906
907  // ...and past the end.
908  ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
909  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
910  ASSERT_PRED1(VectorIsUnshuffled, vector_);
911}
912
913TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
914  // Tests a size one range at the beginning...
915  ShuffleRange(&random_, 0, 1, &vector_);
916  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
917  ASSERT_PRED1(VectorIsUnshuffled, vector_);
918
919  // ...in the middle...
920  ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
921  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
922  ASSERT_PRED1(VectorIsUnshuffled, vector_);
923
924  // ...and at the end.
925  ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
926  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
927  ASSERT_PRED1(VectorIsUnshuffled, vector_);
928}
929
930// Because we use our own random number generator and a fixed seed,
931// we can guarantee that the following "random" tests will succeed.
932
933TEST_F(VectorShuffleTest, ShufflesEntireVector) {
934  Shuffle(&random_, &vector_);
935  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
936  EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
937
938  // Tests the first and last elements in particular to ensure that
939  // there are no off-by-one problems in our shuffle algorithm.
940  EXPECT_NE(0, vector_[0]);
941  EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
942}
943
944TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
945  const int kRangeSize = kVectorSize/2;
946
947  ShuffleRange(&random_, 0, kRangeSize, &vector_);
948
949  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
950  EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
951  EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
952}
953
954TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
955  const int kRangeSize = kVectorSize / 2;
956  ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
957
958  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
959  EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
960  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
961}
962
963TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
964  int kRangeSize = kVectorSize/3;
965  ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
966
967  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
968  EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
969  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
970  EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
971}
972
973TEST_F(VectorShuffleTest, ShufflesRepeatably) {
974  TestingVector vector2;
975  for (int i = 0; i < kVectorSize; i++) {
976    vector2.push_back(i);
977  }
978
979  random_.Reseed(1234);
980  Shuffle(&random_, &vector_);
981  random_.Reseed(1234);
982  Shuffle(&random_, &vector2);
983
984  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
985  ASSERT_PRED1(VectorIsNotCorrupt, vector2);
986
987  for (int i = 0; i < kVectorSize; i++) {
988    EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
989  }
990}
991
992// Tests the size of the AssertHelper class.
993
994TEST(AssertHelperTest, AssertHelperIsSmall) {
995  // To avoid breaking clients that use lots of assertions in one
996  // function, we cannot grow the size of AssertHelper.
997  EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
998}
999
1000// Tests String::EndsWithCaseInsensitive().
1001TEST(StringTest, EndsWithCaseInsensitive) {
1002  EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1003  EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1004  EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1005  EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1006
1007  EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1008  EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1009  EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1010}
1011
1012// C++Builder's preprocessor is buggy; it fails to expand macros that
1013// appear in macro parameters after wide char literals.  Provide an alias
1014// for NULL as a workaround.
1015static const wchar_t* const kNull = NULL;
1016
1017// Tests String::CaseInsensitiveWideCStringEquals
1018TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1019  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
1020  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1021  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1022  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1023  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1024  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1025  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1026  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1027}
1028
1029#if GTEST_OS_WINDOWS
1030
1031// Tests String::ShowWideCString().
1032TEST(StringTest, ShowWideCString) {
1033  EXPECT_STREQ("(null)",
1034               String::ShowWideCString(NULL).c_str());
1035  EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1036  EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1037}
1038
1039# if GTEST_OS_WINDOWS_MOBILE
1040TEST(StringTest, AnsiAndUtf16Null) {
1041  EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1042  EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1043}
1044
1045TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1046  const char* ansi = String::Utf16ToAnsi(L"str");
1047  EXPECT_STREQ("str", ansi);
1048  delete [] ansi;
1049  const WCHAR* utf16 = String::AnsiToUtf16("str");
1050  EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1051  delete [] utf16;
1052}
1053
1054TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1055  const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1056  EXPECT_STREQ(".:\\ \"*?", ansi);
1057  delete [] ansi;
1058  const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1059  EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1060  delete [] utf16;
1061}
1062# endif  // GTEST_OS_WINDOWS_MOBILE
1063
1064#endif  // GTEST_OS_WINDOWS
1065
1066// Tests TestProperty construction.
1067TEST(TestPropertyTest, StringValue) {
1068  TestProperty property("key", "1");
1069  EXPECT_STREQ("key", property.key());
1070  EXPECT_STREQ("1", property.value());
1071}
1072
1073// Tests TestProperty replacing a value.
1074TEST(TestPropertyTest, ReplaceStringValue) {
1075  TestProperty property("key", "1");
1076  EXPECT_STREQ("1", property.value());
1077  property.SetValue("2");
1078  EXPECT_STREQ("2", property.value());
1079}
1080
1081// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1082// functions (i.e. their definitions cannot be inlined at the call
1083// sites), or C++Builder won't compile the code.
1084static void AddFatalFailure() {
1085  FAIL() << "Expected fatal failure.";
1086}
1087
1088static void AddNonfatalFailure() {
1089  ADD_FAILURE() << "Expected non-fatal failure.";
1090}
1091
1092class ScopedFakeTestPartResultReporterTest : public Test {
1093 public:  // Must be public and not protected due to a bug in g++ 3.4.2.
1094  enum FailureMode {
1095    FATAL_FAILURE,
1096    NONFATAL_FAILURE
1097  };
1098  static void AddFailure(FailureMode failure) {
1099    if (failure == FATAL_FAILURE) {
1100      AddFatalFailure();
1101    } else {
1102      AddNonfatalFailure();
1103    }
1104  }
1105};
1106
1107// Tests that ScopedFakeTestPartResultReporter intercepts test
1108// failures.
1109TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1110  TestPartResultArray results;
1111  {
1112    ScopedFakeTestPartResultReporter reporter(
1113        ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1114        &results);
1115    AddFailure(NONFATAL_FAILURE);
1116    AddFailure(FATAL_FAILURE);
1117  }
1118
1119  EXPECT_EQ(2, results.size());
1120  EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1121  EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1122}
1123
1124TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1125  TestPartResultArray results;
1126  {
1127    // Tests, that the deprecated constructor still works.
1128    ScopedFakeTestPartResultReporter reporter(&results);
1129    AddFailure(NONFATAL_FAILURE);
1130  }
1131  EXPECT_EQ(1, results.size());
1132}
1133
1134#if GTEST_IS_THREADSAFE
1135
1136class ScopedFakeTestPartResultReporterWithThreadsTest
1137  : public ScopedFakeTestPartResultReporterTest {
1138 protected:
1139  static void AddFailureInOtherThread(FailureMode failure) {
1140    ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1141    thread.Join();
1142  }
1143};
1144
1145TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1146       InterceptsTestFailuresInAllThreads) {
1147  TestPartResultArray results;
1148  {
1149    ScopedFakeTestPartResultReporter reporter(
1150        ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1151    AddFailure(NONFATAL_FAILURE);
1152    AddFailure(FATAL_FAILURE);
1153    AddFailureInOtherThread(NONFATAL_FAILURE);
1154    AddFailureInOtherThread(FATAL_FAILURE);
1155  }
1156
1157  EXPECT_EQ(4, results.size());
1158  EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1159  EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1160  EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1161  EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1162}
1163
1164#endif  // GTEST_IS_THREADSAFE
1165
1166// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}.  Makes sure that they
1167// work even if the failure is generated in a called function rather than
1168// the current context.
1169
1170typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1171
1172TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1173  EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1174}
1175
1176#if GTEST_HAS_GLOBAL_STRING
1177TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
1178  EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
1179}
1180#endif
1181
1182TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1183  EXPECT_FATAL_FAILURE(AddFatalFailure(),
1184                       ::std::string("Expected fatal failure."));
1185}
1186
1187TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1188  // We have another test below to verify that the macro catches fatal
1189  // failures generated on another thread.
1190  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1191                                      "Expected fatal failure.");
1192}
1193
1194#ifdef __BORLANDC__
1195// Silences warnings: "Condition is always true"
1196# pragma option push -w-ccc
1197#endif
1198
1199// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1200// function even when the statement in it contains ASSERT_*.
1201
1202int NonVoidFunction() {
1203  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1204  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1205  return 0;
1206}
1207
1208TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1209  NonVoidFunction();
1210}
1211
1212// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1213// current function even though 'statement' generates a fatal failure.
1214
1215void DoesNotAbortHelper(bool* aborted) {
1216  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1217  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1218
1219  *aborted = false;
1220}
1221
1222#ifdef __BORLANDC__
1223// Restores warnings after previous "#pragma option push" suppressed them.
1224# pragma option pop
1225#endif
1226
1227TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1228  bool aborted = true;
1229  DoesNotAbortHelper(&aborted);
1230  EXPECT_FALSE(aborted);
1231}
1232
1233// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1234// statement that contains a macro which expands to code containing an
1235// unprotected comma.
1236
1237static int global_var = 0;
1238#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1239
1240TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1241#ifndef __BORLANDC__
1242  // ICE's in C++Builder.
1243  EXPECT_FATAL_FAILURE({
1244    GTEST_USE_UNPROTECTED_COMMA_;
1245    AddFatalFailure();
1246  }, "");
1247#endif
1248
1249  EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1250    GTEST_USE_UNPROTECTED_COMMA_;
1251    AddFatalFailure();
1252  }, "");
1253}
1254
1255// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1256
1257typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1258
1259TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1260  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1261                          "Expected non-fatal failure.");
1262}
1263
1264#if GTEST_HAS_GLOBAL_STRING
1265TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
1266  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1267                          ::string("Expected non-fatal failure."));
1268}
1269#endif
1270
1271TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1272  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1273                          ::std::string("Expected non-fatal failure."));
1274}
1275
1276TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1277  // We have another test below to verify that the macro catches
1278  // non-fatal failures generated on another thread.
1279  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1280                                         "Expected non-fatal failure.");
1281}
1282
1283// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1284// statement that contains a macro which expands to code containing an
1285// unprotected comma.
1286TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1287  EXPECT_NONFATAL_FAILURE({
1288    GTEST_USE_UNPROTECTED_COMMA_;
1289    AddNonfatalFailure();
1290  }, "");
1291
1292  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1293    GTEST_USE_UNPROTECTED_COMMA_;
1294    AddNonfatalFailure();
1295  }, "");
1296}
1297
1298#if GTEST_IS_THREADSAFE
1299
1300typedef ScopedFakeTestPartResultReporterWithThreadsTest
1301    ExpectFailureWithThreadsTest;
1302
1303TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1304  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1305                                      "Expected fatal failure.");
1306}
1307
1308TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1309  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1310      AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1311}
1312
1313#endif  // GTEST_IS_THREADSAFE
1314
1315// Tests the TestProperty class.
1316
1317TEST(TestPropertyTest, ConstructorWorks) {
1318  const TestProperty property("key", "value");
1319  EXPECT_STREQ("key", property.key());
1320  EXPECT_STREQ("value", property.value());
1321}
1322
1323TEST(TestPropertyTest, SetValue) {
1324  TestProperty property("key", "value_1");
1325  EXPECT_STREQ("key", property.key());
1326  property.SetValue("value_2");
1327  EXPECT_STREQ("key", property.key());
1328  EXPECT_STREQ("value_2", property.value());
1329}
1330
1331// Tests the TestResult class
1332
1333// The test fixture for testing TestResult.
1334class TestResultTest : public Test {
1335 protected:
1336  typedef std::vector<TestPartResult> TPRVector;
1337
1338  // We make use of 2 TestPartResult objects,
1339  TestPartResult * pr1, * pr2;
1340
1341  // ... and 3 TestResult objects.
1342  TestResult * r0, * r1, * r2;
1343
1344  virtual void SetUp() {
1345    // pr1 is for success.
1346    pr1 = new TestPartResult(TestPartResult::kSuccess,
1347                             "foo/bar.cc",
1348                             10,
1349                             "Success!");
1350
1351    // pr2 is for fatal failure.
1352    pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1353                             "foo/bar.cc",
1354                             -1,  // This line number means "unknown"
1355                             "Failure!");
1356
1357    // Creates the TestResult objects.
1358    r0 = new TestResult();
1359    r1 = new TestResult();
1360    r2 = new TestResult();
1361
1362    // In order to test TestResult, we need to modify its internal
1363    // state, in particular the TestPartResult vector it holds.
1364    // test_part_results() returns a const reference to this vector.
1365    // We cast it to a non-const object s.t. it can be modified (yes,
1366    // this is a hack).
1367    TPRVector* results1 = const_cast<TPRVector*>(
1368        &TestResultAccessor::test_part_results(*r1));
1369    TPRVector* results2 = const_cast<TPRVector*>(
1370        &TestResultAccessor::test_part_results(*r2));
1371
1372    // r0 is an empty TestResult.
1373
1374    // r1 contains a single SUCCESS TestPartResult.
1375    results1->push_back(*pr1);
1376
1377    // r2 contains a SUCCESS, and a FAILURE.
1378    results2->push_back(*pr1);
1379    results2->push_back(*pr2);
1380  }
1381
1382  virtual void TearDown() {
1383    delete pr1;
1384    delete pr2;
1385
1386    delete r0;
1387    delete r1;
1388    delete r2;
1389  }
1390
1391  // Helper that compares two two TestPartResults.
1392  static void CompareTestPartResult(const TestPartResult& expected,
1393                                    const TestPartResult& actual) {
1394    EXPECT_EQ(expected.type(), actual.type());
1395    EXPECT_STREQ(expected.file_name(), actual.file_name());
1396    EXPECT_EQ(expected.line_number(), actual.line_number());
1397    EXPECT_STREQ(expected.summary(), actual.summary());
1398    EXPECT_STREQ(expected.message(), actual.message());
1399    EXPECT_EQ(expected.passed(), actual.passed());
1400    EXPECT_EQ(expected.failed(), actual.failed());
1401    EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1402    EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1403  }
1404};
1405
1406// Tests TestResult::total_part_count().
1407TEST_F(TestResultTest, total_part_count) {
1408  ASSERT_EQ(0, r0->total_part_count());
1409  ASSERT_EQ(1, r1->total_part_count());
1410  ASSERT_EQ(2, r2->total_part_count());
1411}
1412
1413// Tests TestResult::Passed().
1414TEST_F(TestResultTest, Passed) {
1415  ASSERT_TRUE(r0->Passed());
1416  ASSERT_TRUE(r1->Passed());
1417  ASSERT_FALSE(r2->Passed());
1418}
1419
1420// Tests TestResult::Failed().
1421TEST_F(TestResultTest, Failed) {
1422  ASSERT_FALSE(r0->Failed());
1423  ASSERT_FALSE(r1->Failed());
1424  ASSERT_TRUE(r2->Failed());
1425}
1426
1427// Tests TestResult::GetTestPartResult().
1428
1429typedef TestResultTest TestResultDeathTest;
1430
1431TEST_F(TestResultDeathTest, GetTestPartResult) {
1432  CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1433  CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1434  EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1435  EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1436}
1437
1438// Tests TestResult has no properties when none are added.
1439TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1440  TestResult test_result;
1441  ASSERT_EQ(0, test_result.test_property_count());
1442}
1443
1444// Tests TestResult has the expected property when added.
1445TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1446  TestResult test_result;
1447  TestProperty property("key_1", "1");
1448  TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1449  ASSERT_EQ(1, test_result.test_property_count());
1450  const TestProperty& actual_property = test_result.GetTestProperty(0);
1451  EXPECT_STREQ("key_1", actual_property.key());
1452  EXPECT_STREQ("1", actual_property.value());
1453}
1454
1455// Tests TestResult has multiple properties when added.
1456TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1457  TestResult test_result;
1458  TestProperty property_1("key_1", "1");
1459  TestProperty property_2("key_2", "2");
1460  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1461  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1462  ASSERT_EQ(2, test_result.test_property_count());
1463  const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1464  EXPECT_STREQ("key_1", actual_property_1.key());
1465  EXPECT_STREQ("1", actual_property_1.value());
1466
1467  const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1468  EXPECT_STREQ("key_2", actual_property_2.key());
1469  EXPECT_STREQ("2", actual_property_2.value());
1470}
1471
1472// Tests TestResult::RecordProperty() overrides values for duplicate keys.
1473TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1474  TestResult test_result;
1475  TestProperty property_1_1("key_1", "1");
1476  TestProperty property_2_1("key_2", "2");
1477  TestProperty property_1_2("key_1", "12");
1478  TestProperty property_2_2("key_2", "22");
1479  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1480  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1481  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1482  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1483
1484  ASSERT_EQ(2, test_result.test_property_count());
1485  const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1486  EXPECT_STREQ("key_1", actual_property_1.key());
1487  EXPECT_STREQ("12", actual_property_1.value());
1488
1489  const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1490  EXPECT_STREQ("key_2", actual_property_2.key());
1491  EXPECT_STREQ("22", actual_property_2.value());
1492}
1493
1494// Tests TestResult::GetTestProperty().
1495TEST(TestResultPropertyTest, GetTestProperty) {
1496  TestResult test_result;
1497  TestProperty property_1("key_1", "1");
1498  TestProperty property_2("key_2", "2");
1499  TestProperty property_3("key_3", "3");
1500  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1501  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1502  TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1503
1504  const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1505  const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1506  const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1507
1508  EXPECT_STREQ("key_1", fetched_property_1.key());
1509  EXPECT_STREQ("1", fetched_property_1.value());
1510
1511  EXPECT_STREQ("key_2", fetched_property_2.key());
1512  EXPECT_STREQ("2", fetched_property_2.value());
1513
1514  EXPECT_STREQ("key_3", fetched_property_3.key());
1515  EXPECT_STREQ("3", fetched_property_3.value());
1516
1517  EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1518  EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1519}
1520
1521// Tests the Test class.
1522//
1523// It's difficult to test every public method of this class (we are
1524// already stretching the limit of Google Test by using it to test itself!).
1525// Fortunately, we don't have to do that, as we are already testing
1526// the functionalities of the Test class extensively by using Google Test
1527// alone.
1528//
1529// Therefore, this section only contains one test.
1530
1531// Tests that GTestFlagSaver works on Windows and Mac.
1532
1533class GTestFlagSaverTest : public Test {
1534 protected:
1535  // Saves the Google Test flags such that we can restore them later, and
1536  // then sets them to their default values.  This will be called
1537  // before the first test in this test case is run.
1538  static void SetUpTestCase() {
1539    saver_ = new GTestFlagSaver;
1540
1541    GTEST_FLAG(also_run_disabled_tests) = false;
1542    GTEST_FLAG(break_on_failure) = false;
1543    GTEST_FLAG(catch_exceptions) = false;
1544    GTEST_FLAG(death_test_use_fork) = false;
1545    GTEST_FLAG(color) = "auto";
1546    GTEST_FLAG(filter) = "";
1547    GTEST_FLAG(list_tests) = false;
1548    GTEST_FLAG(output) = "";
1549    GTEST_FLAG(print_time) = true;
1550    GTEST_FLAG(random_seed) = 0;
1551    GTEST_FLAG(repeat) = 1;
1552    GTEST_FLAG(shuffle) = false;
1553    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1554    GTEST_FLAG(stream_result_to) = "";
1555    GTEST_FLAG(throw_on_failure) = false;
1556  }
1557
1558  // Restores the Google Test flags that the tests have modified.  This will
1559  // be called after the last test in this test case is run.
1560  static void TearDownTestCase() {
1561    delete saver_;
1562    saver_ = NULL;
1563  }
1564
1565  // Verifies that the Google Test flags have their default values, and then
1566  // modifies each of them.
1567  void VerifyAndModifyFlags() {
1568    EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1569    EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1570    EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1571    EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1572    EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1573    EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1574    EXPECT_FALSE(GTEST_FLAG(list_tests));
1575    EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1576    EXPECT_TRUE(GTEST_FLAG(print_time));
1577    EXPECT_EQ(0, GTEST_FLAG(random_seed));
1578    EXPECT_EQ(1, GTEST_FLAG(repeat));
1579    EXPECT_FALSE(GTEST_FLAG(shuffle));
1580    EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1581    EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
1582    EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1583
1584    GTEST_FLAG(also_run_disabled_tests) = true;
1585    GTEST_FLAG(break_on_failure) = true;
1586    GTEST_FLAG(catch_exceptions) = true;
1587    GTEST_FLAG(color) = "no";
1588    GTEST_FLAG(death_test_use_fork) = true;
1589    GTEST_FLAG(filter) = "abc";
1590    GTEST_FLAG(list_tests) = true;
1591    GTEST_FLAG(output) = "xml:foo.xml";
1592    GTEST_FLAG(print_time) = false;
1593    GTEST_FLAG(random_seed) = 1;
1594    GTEST_FLAG(repeat) = 100;
1595    GTEST_FLAG(shuffle) = true;
1596    GTEST_FLAG(stack_trace_depth) = 1;
1597    GTEST_FLAG(stream_result_to) = "localhost:1234";
1598    GTEST_FLAG(throw_on_failure) = true;
1599  }
1600
1601 private:
1602  // For saving Google Test flags during this test case.
1603  static GTestFlagSaver* saver_;
1604};
1605
1606GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
1607
1608// Google Test doesn't guarantee the order of tests.  The following two
1609// tests are designed to work regardless of their order.
1610
1611// Modifies the Google Test flags in the test body.
1612TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1613  VerifyAndModifyFlags();
1614}
1615
1616// Verifies that the Google Test flags in the body of the previous test were
1617// restored to their original values.
1618TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1619  VerifyAndModifyFlags();
1620}
1621
1622// Sets an environment variable with the given name to the given
1623// value.  If the value argument is "", unsets the environment
1624// variable.  The caller must ensure that both arguments are not NULL.
1625static void SetEnv(const char* name, const char* value) {
1626#if GTEST_OS_WINDOWS_MOBILE
1627  // Environment variables are not supported on Windows CE.
1628  return;
1629#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1630  // C++Builder's putenv only stores a pointer to its parameter; we have to
1631  // ensure that the string remains valid as long as it might be needed.
1632  // We use an std::map to do so.
1633  static std::map<std::string, std::string*> added_env;
1634
1635  // Because putenv stores a pointer to the string buffer, we can't delete the
1636  // previous string (if present) until after it's replaced.
1637  std::string *prev_env = NULL;
1638  if (added_env.find(name) != added_env.end()) {
1639    prev_env = added_env[name];
1640  }
1641  added_env[name] = new std::string(
1642      (Message() << name << "=" << value).GetString());
1643
1644  // The standard signature of putenv accepts a 'char*' argument. Other
1645  // implementations, like C++Builder's, accept a 'const char*'.
1646  // We cast away the 'const' since that would work for both variants.
1647  putenv(const_cast<char*>(added_env[name]->c_str()));
1648  delete prev_env;
1649#elif GTEST_OS_WINDOWS  // If we are on Windows proper.
1650  _putenv((Message() << name << "=" << value).GetString().c_str());
1651#else
1652  if (*value == '\0') {
1653    unsetenv(name);
1654  } else {
1655    setenv(name, value, 1);
1656  }
1657#endif  // GTEST_OS_WINDOWS_MOBILE
1658}
1659
1660#if !GTEST_OS_WINDOWS_MOBILE
1661// Environment variables are not supported on Windows CE.
1662
1663using testing::internal::Int32FromGTestEnv;
1664
1665// Tests Int32FromGTestEnv().
1666
1667// Tests that Int32FromGTestEnv() returns the default value when the
1668// environment variable is not set.
1669TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1670  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1671  EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1672}
1673
1674# if !defined(GTEST_GET_INT32_FROM_ENV_)
1675
1676// Tests that Int32FromGTestEnv() returns the default value when the
1677// environment variable overflows as an Int32.
1678TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1679  printf("(expecting 2 warnings)\n");
1680
1681  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1682  EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1683
1684  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1685  EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1686}
1687
1688// Tests that Int32FromGTestEnv() returns the default value when the
1689// environment variable does not represent a valid decimal integer.
1690TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1691  printf("(expecting 2 warnings)\n");
1692
1693  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1694  EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1695
1696  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1697  EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1698}
1699
1700# endif  // !defined(GTEST_GET_INT32_FROM_ENV_)
1701
1702// Tests that Int32FromGTestEnv() parses and returns the value of the
1703// environment variable when it represents a valid decimal integer in
1704// the range of an Int32.
1705TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1706  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1707  EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1708
1709  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1710  EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1711}
1712#endif  // !GTEST_OS_WINDOWS_MOBILE
1713
1714// Tests ParseInt32Flag().
1715
1716// Tests that ParseInt32Flag() returns false and doesn't change the
1717// output value when the flag has wrong format
1718TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1719  Int32 value = 123;
1720  EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1721  EXPECT_EQ(123, value);
1722
1723  EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1724  EXPECT_EQ(123, value);
1725}
1726
1727// Tests that ParseInt32Flag() returns false and doesn't change the
1728// output value when the flag overflows as an Int32.
1729TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1730  printf("(expecting 2 warnings)\n");
1731
1732  Int32 value = 123;
1733  EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1734  EXPECT_EQ(123, value);
1735
1736  EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1737  EXPECT_EQ(123, value);
1738}
1739
1740// Tests that ParseInt32Flag() returns false and doesn't change the
1741// output value when the flag does not represent a valid decimal
1742// integer.
1743TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1744  printf("(expecting 2 warnings)\n");
1745
1746  Int32 value = 123;
1747  EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1748  EXPECT_EQ(123, value);
1749
1750  EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1751  EXPECT_EQ(123, value);
1752}
1753
1754// Tests that ParseInt32Flag() parses the value of the flag and
1755// returns true when the flag represents a valid decimal integer in
1756// the range of an Int32.
1757TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1758  Int32 value = 123;
1759  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1760  EXPECT_EQ(456, value);
1761
1762  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1763                             "abc", &value));
1764  EXPECT_EQ(-789, value);
1765}
1766
1767// Tests that Int32FromEnvOrDie() parses the value of the var or
1768// returns the correct default.
1769// Environment variables are not supported on Windows CE.
1770#if !GTEST_OS_WINDOWS_MOBILE
1771TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1772  EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1773  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1774  EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1775  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1776  EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1777}
1778#endif  // !GTEST_OS_WINDOWS_MOBILE
1779
1780// Tests that Int32FromEnvOrDie() aborts with an error message
1781// if the variable is not an Int32.
1782TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1783  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1784  EXPECT_DEATH_IF_SUPPORTED(
1785      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1786      ".*");
1787}
1788
1789// Tests that Int32FromEnvOrDie() aborts with an error message
1790// if the variable cannot be represnted by an Int32.
1791TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1792  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1793  EXPECT_DEATH_IF_SUPPORTED(
1794      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1795      ".*");
1796}
1797
1798// Tests that ShouldRunTestOnShard() selects all tests
1799// where there is 1 shard.
1800TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1801  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1802  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1803  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1804  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1805  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1806}
1807
1808class ShouldShardTest : public testing::Test {
1809 protected:
1810  virtual void SetUp() {
1811    index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1812    total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1813  }
1814
1815  virtual void TearDown() {
1816    SetEnv(index_var_, "");
1817    SetEnv(total_var_, "");
1818  }
1819
1820  const char* index_var_;
1821  const char* total_var_;
1822};
1823
1824// Tests that sharding is disabled if neither of the environment variables
1825// are set.
1826TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1827  SetEnv(index_var_, "");
1828  SetEnv(total_var_, "");
1829
1830  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1831  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1832}
1833
1834// Tests that sharding is not enabled if total_shards  == 1.
1835TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1836  SetEnv(index_var_, "0");
1837  SetEnv(total_var_, "1");
1838  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1839  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1840}
1841
1842// Tests that sharding is enabled if total_shards > 1 and
1843// we are not in a death test subprocess.
1844// Environment variables are not supported on Windows CE.
1845#if !GTEST_OS_WINDOWS_MOBILE
1846TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1847  SetEnv(index_var_, "4");
1848  SetEnv(total_var_, "22");
1849  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1850  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1851
1852  SetEnv(index_var_, "8");
1853  SetEnv(total_var_, "9");
1854  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1855  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1856
1857  SetEnv(index_var_, "0");
1858  SetEnv(total_var_, "9");
1859  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1860  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1861}
1862#endif  // !GTEST_OS_WINDOWS_MOBILE
1863
1864// Tests that we exit in error if the sharding values are not valid.
1865
1866typedef ShouldShardTest ShouldShardDeathTest;
1867
1868TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1869  SetEnv(index_var_, "4");
1870  SetEnv(total_var_, "4");
1871  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1872
1873  SetEnv(index_var_, "4");
1874  SetEnv(total_var_, "-2");
1875  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1876
1877  SetEnv(index_var_, "5");
1878  SetEnv(total_var_, "");
1879  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1880
1881  SetEnv(index_var_, "");
1882  SetEnv(total_var_, "5");
1883  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1884}
1885
1886// Tests that ShouldRunTestOnShard is a partition when 5
1887// shards are used.
1888TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1889  // Choose an arbitrary number of tests and shards.
1890  const int num_tests = 17;
1891  const int num_shards = 5;
1892
1893  // Check partitioning: each test should be on exactly 1 shard.
1894  for (int test_id = 0; test_id < num_tests; test_id++) {
1895    int prev_selected_shard_index = -1;
1896    for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1897      if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1898        if (prev_selected_shard_index < 0) {
1899          prev_selected_shard_index = shard_index;
1900        } else {
1901          ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1902            << shard_index << " are both selected to run test " << test_id;
1903        }
1904      }
1905    }
1906  }
1907
1908  // Check balance: This is not required by the sharding protocol, but is a
1909  // desirable property for performance.
1910  for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1911    int num_tests_on_shard = 0;
1912    for (int test_id = 0; test_id < num_tests; test_id++) {
1913      num_tests_on_shard +=
1914        ShouldRunTestOnShard(num_shards, shard_index, test_id);
1915    }
1916    EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1917  }
1918}
1919
1920// For the same reason we are not explicitly testing everything in the
1921// Test class, there are no separate tests for the following classes
1922// (except for some trivial cases):
1923//
1924//   TestCase, UnitTest, UnitTestResultPrinter.
1925//
1926// Similarly, there are no separate tests for the following macros:
1927//
1928//   TEST, TEST_F, RUN_ALL_TESTS
1929
1930TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1931  ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1932  EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1933}
1934
1935TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1936  EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1937  EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1938}
1939
1940// When a property using a reserved key is supplied to this function, it
1941// tests that a non-fatal failure is added, a fatal failure is not added,
1942// and that the property is not recorded.
1943void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1944    const TestResult& test_result, const char* key) {
1945  EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1946  ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1947                                                  << "' recorded unexpectedly.";
1948}
1949
1950void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1951    const char* key) {
1952  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1953  ASSERT_TRUE(test_info != NULL);
1954  ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1955                                                        key);
1956}
1957
1958void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1959    const char* key) {
1960  const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1961  ASSERT_TRUE(test_case != NULL);
1962  ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1963      test_case->ad_hoc_test_result(), key);
1964}
1965
1966void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
1967    const char* key) {
1968  ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1969      UnitTest::GetInstance()->ad_hoc_test_result(), key);
1970}
1971
1972// Tests that property recording functions in UnitTest outside of tests
1973// functions correcly.  Creating a separate instance of UnitTest ensures it
1974// is in a state similar to the UnitTest's singleton's between tests.
1975class UnitTestRecordPropertyTest :
1976    public testing::internal::UnitTestRecordPropertyTestHelper {
1977 public:
1978  static void SetUpTestCase() {
1979    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1980        "disabled");
1981    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1982        "errors");
1983    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1984        "failures");
1985    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1986        "name");
1987    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1988        "tests");
1989    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1990        "time");
1991
1992    Test::RecordProperty("test_case_key_1", "1");
1993    const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1994    ASSERT_TRUE(test_case != NULL);
1995
1996    ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count());
1997    EXPECT_STREQ("test_case_key_1",
1998                 test_case->ad_hoc_test_result().GetTestProperty(0).key());
1999    EXPECT_STREQ("1",
2000                 test_case->ad_hoc_test_result().GetTestProperty(0).value());
2001  }
2002};
2003
2004// Tests TestResult has the expected property when added.
2005TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2006  UnitTestRecordProperty("key_1", "1");
2007
2008  ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2009
2010  EXPECT_STREQ("key_1",
2011               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2012  EXPECT_STREQ("1",
2013               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2014}
2015
2016// Tests TestResult has multiple properties when added.
2017TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2018  UnitTestRecordProperty("key_1", "1");
2019  UnitTestRecordProperty("key_2", "2");
2020
2021  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2022
2023  EXPECT_STREQ("key_1",
2024               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2025  EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2026
2027  EXPECT_STREQ("key_2",
2028               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2029  EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2030}
2031
2032// Tests TestResult::RecordProperty() overrides values for duplicate keys.
2033TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2034  UnitTestRecordProperty("key_1", "1");
2035  UnitTestRecordProperty("key_2", "2");
2036  UnitTestRecordProperty("key_1", "12");
2037  UnitTestRecordProperty("key_2", "22");
2038
2039  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2040
2041  EXPECT_STREQ("key_1",
2042               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2043  EXPECT_STREQ("12",
2044               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2045
2046  EXPECT_STREQ("key_2",
2047               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2048  EXPECT_STREQ("22",
2049               unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2050}
2051
2052TEST_F(UnitTestRecordPropertyTest,
2053       AddFailureInsideTestsWhenUsingTestCaseReservedKeys) {
2054  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2055      "name");
2056  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2057      "value_param");
2058  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2059      "type_param");
2060  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2061      "status");
2062  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2063      "time");
2064  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2065      "classname");
2066}
2067
2068TEST_F(UnitTestRecordPropertyTest,
2069       AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2070  EXPECT_NONFATAL_FAILURE(
2071      Test::RecordProperty("name", "1"),
2072      "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'"
2073      " are reserved");
2074}
2075
2076class UnitTestRecordPropertyTestEnvironment : public Environment {
2077 public:
2078  virtual void TearDown() {
2079    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2080        "tests");
2081    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2082        "failures");
2083    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2084        "disabled");
2085    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2086        "errors");
2087    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2088        "name");
2089    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2090        "timestamp");
2091    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2092        "time");
2093    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2094        "random_seed");
2095  }
2096};
2097
2098// This will test property recording outside of any test or test case.
2099static Environment* record_property_env =
2100    AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2101
2102// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2103// of various arities.  They do not attempt to be exhaustive.  Rather,
2104// view them as smoke tests that can be easily reviewed and verified.
2105// A more complete set of tests for predicate assertions can be found
2106// in gtest_pred_impl_unittest.cc.
2107
2108// First, some predicates and predicate-formatters needed by the tests.
2109
2110// Returns true iff the argument is an even number.
2111bool IsEven(int n) {
2112  return (n % 2) == 0;
2113}
2114
2115// A functor that returns true iff the argument is an even number.
2116struct IsEvenFunctor {
2117  bool operator()(int n) { return IsEven(n); }
2118};
2119
2120// A predicate-formatter function that asserts the argument is an even
2121// number.
2122AssertionResult AssertIsEven(const char* expr, int n) {
2123  if (IsEven(n)) {
2124    return AssertionSuccess();
2125  }
2126
2127  Message msg;
2128  msg << expr << " evaluates to " << n << ", which is not even.";
2129  return AssertionFailure(msg);
2130}
2131
2132// A predicate function that returns AssertionResult for use in
2133// EXPECT/ASSERT_TRUE/FALSE.
2134AssertionResult ResultIsEven(int n) {
2135  if (IsEven(n))
2136    return AssertionSuccess() << n << " is even";
2137  else
2138    return AssertionFailure() << n << " is odd";
2139}
2140
2141// A predicate function that returns AssertionResult but gives no
2142// explanation why it succeeds. Needed for testing that
2143// EXPECT/ASSERT_FALSE handles such functions correctly.
2144AssertionResult ResultIsEvenNoExplanation(int n) {
2145  if (IsEven(n))
2146    return AssertionSuccess();
2147  else
2148    return AssertionFailure() << n << " is odd";
2149}
2150
2151// A predicate-formatter functor that asserts the argument is an even
2152// number.
2153struct AssertIsEvenFunctor {
2154  AssertionResult operator()(const char* expr, int n) {
2155    return AssertIsEven(expr, n);
2156  }
2157};
2158
2159// Returns true iff the sum of the arguments is an even number.
2160bool SumIsEven2(int n1, int n2) {
2161  return IsEven(n1 + n2);
2162}
2163
2164// A functor that returns true iff the sum of the arguments is an even
2165// number.
2166struct SumIsEven3Functor {
2167  bool operator()(int n1, int n2, int n3) {
2168    return IsEven(n1 + n2 + n3);
2169  }
2170};
2171
2172// A predicate-formatter function that asserts the sum of the
2173// arguments is an even number.
2174AssertionResult AssertSumIsEven4(
2175    const char* e1, const char* e2, const char* e3, const char* e4,
2176    int n1, int n2, int n3, int n4) {
2177  const int sum = n1 + n2 + n3 + n4;
2178  if (IsEven(sum)) {
2179    return AssertionSuccess();
2180  }
2181
2182  Message msg;
2183  msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2184      << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2185      << ") evaluates to " << sum << ", which is not even.";
2186  return AssertionFailure(msg);
2187}
2188
2189// A predicate-formatter functor that asserts the sum of the arguments
2190// is an even number.
2191struct AssertSumIsEven5Functor {
2192  AssertionResult operator()(
2193      const char* e1, const char* e2, const char* e3, const char* e4,
2194      const char* e5, int n1, int n2, int n3, int n4, int n5) {
2195    const int sum = n1 + n2 + n3 + n4 + n5;
2196    if (IsEven(sum)) {
2197      return AssertionSuccess();
2198    }
2199
2200    Message msg;
2201    msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2202        << " ("
2203        << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2204        << ") evaluates to " << sum << ", which is not even.";
2205    return AssertionFailure(msg);
2206  }
2207};
2208
2209
2210// Tests unary predicate assertions.
2211
2212// Tests unary predicate assertions that don't use a custom formatter.
2213TEST(Pred1Test, WithoutFormat) {
2214  // Success cases.
2215  EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2216  ASSERT_PRED1(IsEven, 4);
2217
2218  // Failure cases.
2219  EXPECT_NONFATAL_FAILURE({  // NOLINT
2220    EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2221  }, "This failure is expected.");
2222  EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2223                       "evaluates to false");
2224}
2225
2226// Tests unary predicate assertions that use a custom formatter.
2227TEST(Pred1Test, WithFormat) {
2228  // Success cases.
2229  EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2230  ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2231    << "This failure is UNEXPECTED!";
2232
2233  // Failure cases.
2234  const int n = 5;
2235  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2236                          "n evaluates to 5, which is not even.");
2237  EXPECT_FATAL_FAILURE({  // NOLINT
2238    ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2239  }, "This failure is expected.");
2240}
2241
2242// Tests that unary predicate assertions evaluates their arguments
2243// exactly once.
2244TEST(Pred1Test, SingleEvaluationOnFailure) {
2245  // A success case.
2246  static int n = 0;
2247  EXPECT_PRED1(IsEven, n++);
2248  EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2249
2250  // A failure case.
2251  EXPECT_FATAL_FAILURE({  // NOLINT
2252    ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2253        << "This failure is expected.";
2254  }, "This failure is expected.");
2255  EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2256}
2257
2258
2259// Tests predicate assertions whose arity is >= 2.
2260
2261// Tests predicate assertions that don't use a custom formatter.
2262TEST(PredTest, WithoutFormat) {
2263  // Success cases.
2264  ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2265  EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2266
2267  // Failure cases.
2268  const int n1 = 1;
2269  const int n2 = 2;
2270  EXPECT_NONFATAL_FAILURE({  // NOLINT
2271    EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2272  }, "This failure is expected.");
2273  EXPECT_FATAL_FAILURE({  // NOLINT
2274    ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2275  }, "evaluates to false");
2276}
2277
2278// Tests predicate assertions that use a custom formatter.
2279TEST(PredTest, WithFormat) {
2280  // Success cases.
2281  ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2282    "This failure is UNEXPECTED!";
2283  EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2284
2285  // Failure cases.
2286  const int n1 = 1;
2287  const int n2 = 2;
2288  const int n3 = 4;
2289  const int n4 = 6;
2290  EXPECT_NONFATAL_FAILURE({  // NOLINT
2291    EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2292  }, "evaluates to 13, which is not even.");
2293  EXPECT_FATAL_FAILURE({  // NOLINT
2294    ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2295        << "This failure is expected.";
2296  }, "This failure is expected.");
2297}
2298
2299// Tests that predicate assertions evaluates their arguments
2300// exactly once.
2301TEST(PredTest, SingleEvaluationOnFailure) {
2302  // A success case.
2303  int n1 = 0;
2304  int n2 = 0;
2305  EXPECT_PRED2(SumIsEven2, n1++, n2++);
2306  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2307  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2308
2309  // Another success case.
2310  n1 = n2 = 0;
2311  int n3 = 0;
2312  int n4 = 0;
2313  int n5 = 0;
2314  ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2315                      n1++, n2++, n3++, n4++, n5++)
2316                        << "This failure is UNEXPECTED!";
2317  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2318  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2319  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2320  EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2321  EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2322
2323  // A failure case.
2324  n1 = n2 = n3 = 0;
2325  EXPECT_NONFATAL_FAILURE({  // NOLINT
2326    EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2327        << "This failure is expected.";
2328  }, "This failure is expected.");
2329  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2330  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2331  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2332
2333  // Another failure case.
2334  n1 = n2 = n3 = n4 = 0;
2335  EXPECT_NONFATAL_FAILURE({  // NOLINT
2336    EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2337  }, "evaluates to 1, which is not even.");
2338  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2339  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2340  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2341  EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2342}
2343
2344
2345// Some helper functions for testing using overloaded/template
2346// functions with ASSERT_PREDn and EXPECT_PREDn.
2347
2348bool IsPositive(double x) {
2349  return x > 0;
2350}
2351
2352template <typename T>
2353bool IsNegative(T x) {
2354  return x < 0;
2355}
2356
2357template <typename T1, typename T2>
2358bool GreaterThan(T1 x1, T2 x2) {
2359  return x1 > x2;
2360}
2361
2362// Tests that overloaded functions can be used in *_PRED* as long as
2363// their types are explicitly specified.
2364TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2365  // C++Builder requires C-style casts rather than static_cast.
2366  EXPECT_PRED1((bool (*)(int))(IsPositive), 5);  // NOLINT
2367  ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0);  // NOLINT
2368}
2369
2370// Tests that template functions can be used in *_PRED* as long as
2371// their types are explicitly specified.
2372TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2373  EXPECT_PRED1(IsNegative<int>, -5);
2374  // Makes sure that we can handle templates with more than one
2375  // parameter.
2376  ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2377}
2378
2379
2380// Some helper functions for testing using overloaded/template
2381// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2382
2383AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2384  return n > 0 ? AssertionSuccess() :
2385      AssertionFailure(Message() << "Failure");
2386}
2387
2388AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2389  return x > 0 ? AssertionSuccess() :
2390      AssertionFailure(Message() << "Failure");
2391}
2392
2393template <typename T>
2394AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2395  return x < 0 ? AssertionSuccess() :
2396      AssertionFailure(Message() << "Failure");
2397}
2398
2399template <typename T1, typename T2>
2400AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2401                             const T1& x1, const T2& x2) {
2402  return x1 == x2 ? AssertionSuccess() :
2403      AssertionFailure(Message() << "Failure");
2404}
2405
2406// Tests that overloaded functions can be used in *_PRED_FORMAT*
2407// without explicitly specifying their types.
2408TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2409  EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2410  ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2411}
2412
2413// Tests that template functions can be used in *_PRED_FORMAT* without
2414// explicitly specifying their types.
2415TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2416  EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2417  ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2418}
2419
2420
2421// Tests string assertions.
2422
2423// Tests ASSERT_STREQ with non-NULL arguments.
2424TEST(StringAssertionTest, ASSERT_STREQ) {
2425  const char * const p1 = "good";
2426  ASSERT_STREQ(p1, p1);
2427
2428  // Let p2 have the same content as p1, but be at a different address.
2429  const char p2[] = "good";
2430  ASSERT_STREQ(p1, p2);
2431
2432  EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2433                       "Expected: \"bad\"");
2434}
2435
2436// Tests ASSERT_STREQ with NULL arguments.
2437TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2438  ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2439  EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2440                       "non-null");
2441}
2442
2443// Tests ASSERT_STREQ with NULL arguments.
2444TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2445  EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2446                       "non-null");
2447}
2448
2449// Tests ASSERT_STRNE.
2450TEST(StringAssertionTest, ASSERT_STRNE) {
2451  ASSERT_STRNE("hi", "Hi");
2452  ASSERT_STRNE("Hi", NULL);
2453  ASSERT_STRNE(NULL, "Hi");
2454  ASSERT_STRNE("", NULL);
2455  ASSERT_STRNE(NULL, "");
2456  ASSERT_STRNE("", "Hi");
2457  ASSERT_STRNE("Hi", "");
2458  EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2459                       "\"Hi\" vs \"Hi\"");
2460}
2461
2462// Tests ASSERT_STRCASEEQ.
2463TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2464  ASSERT_STRCASEEQ("hi", "Hi");
2465  ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2466
2467  ASSERT_STRCASEEQ("", "");
2468  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2469                       "(ignoring case)");
2470}
2471
2472// Tests ASSERT_STRCASENE.
2473TEST(StringAssertionTest, ASSERT_STRCASENE) {
2474  ASSERT_STRCASENE("hi1", "Hi2");
2475  ASSERT_STRCASENE("Hi", NULL);
2476  ASSERT_STRCASENE(NULL, "Hi");
2477  ASSERT_STRCASENE("", NULL);
2478  ASSERT_STRCASENE(NULL, "");
2479  ASSERT_STRCASENE("", "Hi");
2480  ASSERT_STRCASENE("Hi", "");
2481  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2482                       "(ignoring case)");
2483}
2484
2485// Tests *_STREQ on wide strings.
2486TEST(StringAssertionTest, STREQ_Wide) {
2487  // NULL strings.
2488  ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2489
2490  // Empty strings.
2491  ASSERT_STREQ(L"", L"");
2492
2493  // Non-null vs NULL.
2494  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2495                          "non-null");
2496
2497  // Equal strings.
2498  EXPECT_STREQ(L"Hi", L"Hi");
2499
2500  // Unequal strings.
2501  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2502                          "Abc");
2503
2504  // Strings containing wide characters.
2505  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2506                          "abc");
2507
2508  // The streaming variation.
2509  EXPECT_NONFATAL_FAILURE({  // NOLINT
2510    EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2511  }, "Expected failure");
2512}
2513
2514// Tests *_STRNE on wide strings.
2515TEST(StringAssertionTest, STRNE_Wide) {
2516  // NULL strings.
2517  EXPECT_NONFATAL_FAILURE({  // NOLINT
2518    EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2519  }, "");
2520
2521  // Empty strings.
2522  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2523                          "L\"\"");
2524
2525  // Non-null vs NULL.
2526  ASSERT_STRNE(L"non-null", NULL);
2527
2528  // Equal strings.
2529  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2530                          "L\"Hi\"");
2531
2532  // Unequal strings.
2533  EXPECT_STRNE(L"abc", L"Abc");
2534
2535  // Strings containing wide characters.
2536  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2537                          "abc");
2538
2539  // The streaming variation.
2540  ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2541}
2542
2543// Tests for ::testing::IsSubstring().
2544
2545// Tests that IsSubstring() returns the correct result when the input
2546// argument type is const char*.
2547TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2548  EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2549  EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2550  EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2551
2552  EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2553  EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2554}
2555
2556// Tests that IsSubstring() returns the correct result when the input
2557// argument type is const wchar_t*.
2558TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2559  EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2560  EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2561  EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2562
2563  EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2564  EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2565}
2566
2567// Tests that IsSubstring() generates the correct message when the input
2568// argument type is const char*.
2569TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2570  EXPECT_STREQ("Value of: needle_expr\n"
2571               "  Actual: \"needle\"\n"
2572               "Expected: a substring of haystack_expr\n"
2573               "Which is: \"haystack\"",
2574               IsSubstring("needle_expr", "haystack_expr",
2575                           "needle", "haystack").failure_message());
2576}
2577
2578// Tests that IsSubstring returns the correct result when the input
2579// argument type is ::std::string.
2580TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2581  EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2582  EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2583}
2584
2585#if GTEST_HAS_STD_WSTRING
2586// Tests that IsSubstring returns the correct result when the input
2587// argument type is ::std::wstring.
2588TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2589  EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2590  EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2591}
2592
2593// Tests that IsSubstring() generates the correct message when the input
2594// argument type is ::std::wstring.
2595TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2596  EXPECT_STREQ("Value of: needle_expr\n"
2597               "  Actual: L\"needle\"\n"
2598               "Expected: a substring of haystack_expr\n"
2599               "Which is: L\"haystack\"",
2600               IsSubstring(
2601                   "needle_expr", "haystack_expr",
2602                   ::std::wstring(L"needle"), L"haystack").failure_message());
2603}
2604
2605#endif  // GTEST_HAS_STD_WSTRING
2606
2607// Tests for ::testing::IsNotSubstring().
2608
2609// Tests that IsNotSubstring() returns the correct result when the input
2610// argument type is const char*.
2611TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2612  EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2613  EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2614}
2615
2616// Tests that IsNotSubstring() returns the correct result when the input
2617// argument type is const wchar_t*.
2618TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2619  EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2620  EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2621}
2622
2623// Tests that IsNotSubstring() generates the correct message when the input
2624// argument type is const wchar_t*.
2625TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2626  EXPECT_STREQ("Value of: needle_expr\n"
2627               "  Actual: L\"needle\"\n"
2628               "Expected: not a substring of haystack_expr\n"
2629               "Which is: L\"two needles\"",
2630               IsNotSubstring(
2631                   "needle_expr", "haystack_expr",
2632                   L"needle", L"two needles").failure_message());
2633}
2634
2635// Tests that IsNotSubstring returns the correct result when the input
2636// argument type is ::std::string.
2637TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2638  EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2639  EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2640}
2641
2642// Tests that IsNotSubstring() generates the correct message when the input
2643// argument type is ::std::string.
2644TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2645  EXPECT_STREQ("Value of: needle_expr\n"
2646               "  Actual: \"needle\"\n"
2647               "Expected: not a substring of haystack_expr\n"
2648               "Which is: \"two needles\"",
2649               IsNotSubstring(
2650                   "needle_expr", "haystack_expr",
2651                   ::std::string("needle"), "two needles").failure_message());
2652}
2653
2654#if GTEST_HAS_STD_WSTRING
2655
2656// Tests that IsNotSubstring returns the correct result when the input
2657// argument type is ::std::wstring.
2658TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2659  EXPECT_FALSE(
2660      IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2661  EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2662}
2663
2664#endif  // GTEST_HAS_STD_WSTRING
2665
2666// Tests floating-point assertions.
2667
2668template <typename RawType>
2669class FloatingPointTest : public Test {
2670 protected:
2671  // Pre-calculated numbers to be used by the tests.
2672  struct TestValues {
2673    RawType close_to_positive_zero;
2674    RawType close_to_negative_zero;
2675    RawType further_from_negative_zero;
2676
2677    RawType close_to_one;
2678    RawType further_from_one;
2679
2680    RawType infinity;
2681    RawType close_to_infinity;
2682    RawType further_from_infinity;
2683
2684    RawType nan1;
2685    RawType nan2;
2686  };
2687
2688  typedef typename testing::internal::FloatingPoint<RawType> Floating;
2689  typedef typename Floating::Bits Bits;
2690
2691  virtual void SetUp() {
2692    const size_t max_ulps = Floating::kMaxUlps;
2693
2694    // The bits that represent 0.0.
2695    const Bits zero_bits = Floating(0).bits();
2696
2697    // Makes some numbers close to 0.0.
2698    values_.close_to_positive_zero = Floating::ReinterpretBits(
2699        zero_bits + max_ulps/2);
2700    values_.close_to_negative_zero = -Floating::ReinterpretBits(
2701        zero_bits + max_ulps - max_ulps/2);
2702    values_.further_from_negative_zero = -Floating::ReinterpretBits(
2703        zero_bits + max_ulps + 1 - max_ulps/2);
2704
2705    // The bits that represent 1.0.
2706    const Bits one_bits = Floating(1).bits();
2707
2708    // Makes some numbers close to 1.0.
2709    values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2710    values_.further_from_one = Floating::ReinterpretBits(
2711        one_bits + max_ulps + 1);
2712
2713    // +infinity.
2714    values_.infinity = Floating::Infinity();
2715
2716    // The bits that represent +infinity.
2717    const Bits infinity_bits = Floating(values_.infinity).bits();
2718
2719    // Makes some numbers close to infinity.
2720    values_.close_to_infinity = Floating::ReinterpretBits(
2721        infinity_bits - max_ulps);
2722    values_.further_from_infinity = Floating::ReinterpretBits(
2723        infinity_bits - max_ulps - 1);
2724
2725    // Makes some NAN's.  Sets the most significant bit of the fraction so that
2726    // our NaN's are quiet; trying to process a signaling NaN would raise an
2727    // exception if our environment enables floating point exceptions.
2728    values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2729        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2730    values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2731        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2732  }
2733
2734  void TestSize() {
2735    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2736  }
2737
2738  static TestValues values_;
2739};
2740
2741template <typename RawType>
2742typename FloatingPointTest<RawType>::TestValues
2743    FloatingPointTest<RawType>::values_;
2744
2745// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2746typedef FloatingPointTest<float> FloatTest;
2747
2748// Tests that the size of Float::Bits matches the size of float.
2749TEST_F(FloatTest, Size) {
2750  TestSize();
2751}
2752
2753// Tests comparing with +0 and -0.
2754TEST_F(FloatTest, Zeros) {
2755  EXPECT_FLOAT_EQ(0.0, -0.0);
2756  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2757                          "1.0");
2758  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2759                       "1.5");
2760}
2761
2762// Tests comparing numbers close to 0.
2763//
2764// This ensures that *_FLOAT_EQ handles the sign correctly and no
2765// overflow occurs when comparing numbers whose absolute value is very
2766// small.
2767TEST_F(FloatTest, AlmostZeros) {
2768  // In C++Builder, names within local classes (such as used by
2769  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2770  // scoping class.  Use a static local alias as a workaround.
2771  // We use the assignment syntax since some compilers, like Sun Studio,
2772  // don't allow initializing references using construction syntax
2773  // (parentheses).
2774  static const FloatTest::TestValues& v = this->values_;
2775
2776  EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2777  EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2778  EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2779
2780  EXPECT_FATAL_FAILURE({  // NOLINT
2781    ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2782                    v.further_from_negative_zero);
2783  }, "v.further_from_negative_zero");
2784}
2785
2786// Tests comparing numbers close to each other.
2787TEST_F(FloatTest, SmallDiff) {
2788  EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2789  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2790                          "values_.further_from_one");
2791}
2792
2793// Tests comparing numbers far apart.
2794TEST_F(FloatTest, LargeDiff) {
2795  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2796                          "3.0");
2797}
2798
2799// Tests comparing with infinity.
2800//
2801// This ensures that no overflow occurs when comparing numbers whose
2802// absolute value is very large.
2803TEST_F(FloatTest, Infinity) {
2804  EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2805  EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2806#if !GTEST_OS_SYMBIAN
2807  // Nokia's STLport crashes if we try to output infinity or NaN.
2808  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2809                          "-values_.infinity");
2810
2811  // This is interesting as the representations of infinity and nan1
2812  // are only 1 DLP apart.
2813  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2814                          "values_.nan1");
2815#endif  // !GTEST_OS_SYMBIAN
2816}
2817
2818// Tests that comparing with NAN always returns false.
2819TEST_F(FloatTest, NaN) {
2820#if !GTEST_OS_SYMBIAN
2821// Nokia's STLport crashes if we try to output infinity or NaN.
2822
2823  // In C++Builder, names within local classes (such as used by
2824  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2825  // scoping class.  Use a static local alias as a workaround.
2826  // We use the assignment syntax since some compilers, like Sun Studio,
2827  // don't allow initializing references using construction syntax
2828  // (parentheses).
2829  static const FloatTest::TestValues& v = this->values_;
2830
2831  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2832                          "v.nan1");
2833  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2834                          "v.nan2");
2835  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2836                          "v.nan1");
2837
2838  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2839                       "v.infinity");
2840#endif  // !GTEST_OS_SYMBIAN
2841}
2842
2843// Tests that *_FLOAT_EQ are reflexive.
2844TEST_F(FloatTest, Reflexive) {
2845  EXPECT_FLOAT_EQ(0.0, 0.0);
2846  EXPECT_FLOAT_EQ(1.0, 1.0);
2847  ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2848}
2849
2850// Tests that *_FLOAT_EQ are commutative.
2851TEST_F(FloatTest, Commutative) {
2852  // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2853  EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2854
2855  // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2856  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2857                          "1.0");
2858}
2859
2860// Tests EXPECT_NEAR.
2861TEST_F(FloatTest, EXPECT_NEAR) {
2862  EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2863  EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2864  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
2865                          "The difference between 1.0f and 1.5f is 0.5, "
2866                          "which exceeds 0.25f");
2867  // To work around a bug in gcc 2.95.0, there is intentionally no
2868  // space after the first comma in the previous line.
2869}
2870
2871// Tests ASSERT_NEAR.
2872TEST_F(FloatTest, ASSERT_NEAR) {
2873  ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2874  ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2875  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
2876                       "The difference between 1.0f and 1.5f is 0.5, "
2877                       "which exceeds 0.25f");
2878  // To work around a bug in gcc 2.95.0, there is intentionally no
2879  // space after the first comma in the previous line.
2880}
2881
2882// Tests the cases where FloatLE() should succeed.
2883TEST_F(FloatTest, FloatLESucceeds) {
2884  EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f);  // When val1 < val2,
2885  ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f);  // val1 == val2,
2886
2887  // or when val1 is greater than, but almost equals to, val2.
2888  EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2889}
2890
2891// Tests the cases where FloatLE() should fail.
2892TEST_F(FloatTest, FloatLEFails) {
2893  // When val1 is greater than val2 by a large margin,
2894  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2895                          "(2.0f) <= (1.0f)");
2896
2897  // or by a small yet non-negligible margin,
2898  EXPECT_NONFATAL_FAILURE({  // NOLINT
2899    EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2900  }, "(values_.further_from_one) <= (1.0f)");
2901
2902#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2903  // Nokia's STLport crashes if we try to output infinity or NaN.
2904  // C++Builder gives bad results for ordered comparisons involving NaNs
2905  // due to compiler bugs.
2906  EXPECT_NONFATAL_FAILURE({  // NOLINT
2907    EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2908  }, "(values_.nan1) <= (values_.infinity)");
2909  EXPECT_NONFATAL_FAILURE({  // NOLINT
2910    EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2911  }, "(-values_.infinity) <= (values_.nan1)");
2912  EXPECT_FATAL_FAILURE({  // NOLINT
2913    ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2914  }, "(values_.nan1) <= (values_.nan1)");
2915#endif  // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2916}
2917
2918// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2919typedef FloatingPointTest<double> DoubleTest;
2920
2921// Tests that the size of Double::Bits matches the size of double.
2922TEST_F(DoubleTest, Size) {
2923  TestSize();
2924}
2925
2926// Tests comparing with +0 and -0.
2927TEST_F(DoubleTest, Zeros) {
2928  EXPECT_DOUBLE_EQ(0.0, -0.0);
2929  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2930                          "1.0");
2931  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2932                       "1.0");
2933}
2934
2935// Tests comparing numbers close to 0.
2936//
2937// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2938// overflow occurs when comparing numbers whose absolute value is very
2939// small.
2940TEST_F(DoubleTest, AlmostZeros) {
2941  // In C++Builder, names within local classes (such as used by
2942  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2943  // scoping class.  Use a static local alias as a workaround.
2944  // We use the assignment syntax since some compilers, like Sun Studio,
2945  // don't allow initializing references using construction syntax
2946  // (parentheses).
2947  static const DoubleTest::TestValues& v = this->values_;
2948
2949  EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2950  EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2951  EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2952
2953  EXPECT_FATAL_FAILURE({  // NOLINT
2954    ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2955                     v.further_from_negative_zero);
2956  }, "v.further_from_negative_zero");
2957}
2958
2959// Tests comparing numbers close to each other.
2960TEST_F(DoubleTest, SmallDiff) {
2961  EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2962  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2963                          "values_.further_from_one");
2964}
2965
2966// Tests comparing numbers far apart.
2967TEST_F(DoubleTest, LargeDiff) {
2968  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2969                          "3.0");
2970}
2971
2972// Tests comparing with infinity.
2973//
2974// This ensures that no overflow occurs when comparing numbers whose
2975// absolute value is very large.
2976TEST_F(DoubleTest, Infinity) {
2977  EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2978  EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
2979#if !GTEST_OS_SYMBIAN
2980  // Nokia's STLport crashes if we try to output infinity or NaN.
2981  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2982                          "-values_.infinity");
2983
2984  // This is interesting as the representations of infinity_ and nan1_
2985  // are only 1 DLP apart.
2986  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2987                          "values_.nan1");
2988#endif  // !GTEST_OS_SYMBIAN
2989}
2990
2991// Tests that comparing with NAN always returns false.
2992TEST_F(DoubleTest, NaN) {
2993#if !GTEST_OS_SYMBIAN
2994  // In C++Builder, names within local classes (such as used by
2995  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2996  // scoping class.  Use a static local alias as a workaround.
2997  // We use the assignment syntax since some compilers, like Sun Studio,
2998  // don't allow initializing references using construction syntax
2999  // (parentheses).
3000  static const DoubleTest::TestValues& v = this->values_;
3001
3002  // Nokia's STLport crashes if we try to output infinity or NaN.
3003  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3004                          "v.nan1");
3005  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3006  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3007  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3008                       "v.infinity");
3009#endif  // !GTEST_OS_SYMBIAN
3010}
3011
3012// Tests that *_DOUBLE_EQ are reflexive.
3013TEST_F(DoubleTest, Reflexive) {
3014  EXPECT_DOUBLE_EQ(0.0, 0.0);
3015  EXPECT_DOUBLE_EQ(1.0, 1.0);
3016#if !GTEST_OS_SYMBIAN
3017  // Nokia's STLport crashes if we try to output infinity or NaN.
3018  ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3019#endif  // !GTEST_OS_SYMBIAN
3020}
3021
3022// Tests that *_DOUBLE_EQ are commutative.
3023TEST_F(DoubleTest, Commutative) {
3024  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3025  EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3026
3027  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3028  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3029                          "1.0");
3030}
3031
3032// Tests EXPECT_NEAR.
3033TEST_F(DoubleTest, EXPECT_NEAR) {
3034  EXPECT_NEAR(-1.0, -1.1, 0.2);
3035  EXPECT_NEAR(2.0, 3.0, 1.0);
3036  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25),  // NOLINT
3037                          "The difference between 1.0 and 1.5 is 0.5, "
3038                          "which exceeds 0.25");
3039  // To work around a bug in gcc 2.95.0, there is intentionally no
3040  // space after the first comma in the previous statement.
3041}
3042
3043// Tests ASSERT_NEAR.
3044TEST_F(DoubleTest, ASSERT_NEAR) {
3045  ASSERT_NEAR(-1.0, -1.1, 0.2);
3046  ASSERT_NEAR(2.0, 3.0, 1.0);
3047  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25),  // NOLINT
3048                       "The difference between 1.0 and 1.5 is 0.5, "
3049                       "which exceeds 0.25");
3050  // To work around a bug in gcc 2.95.0, there is intentionally no
3051  // space after the first comma in the previous statement.
3052}
3053
3054// Tests the cases where DoubleLE() should succeed.
3055TEST_F(DoubleTest, DoubleLESucceeds) {
3056  EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0);  // When val1 < val2,
3057  ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0);  // val1 == val2,
3058
3059  // or when val1 is greater than, but almost equals to, val2.
3060  EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3061}
3062
3063// Tests the cases where DoubleLE() should fail.
3064TEST_F(DoubleTest, DoubleLEFails) {
3065  // When val1 is greater than val2 by a large margin,
3066  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3067                          "(2.0) <= (1.0)");
3068
3069  // or by a small yet non-negligible margin,
3070  EXPECT_NONFATAL_FAILURE({  // NOLINT
3071    EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3072  }, "(values_.further_from_one) <= (1.0)");
3073
3074#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3075  // Nokia's STLport crashes if we try to output infinity or NaN.
3076  // C++Builder gives bad results for ordered comparisons involving NaNs
3077  // due to compiler bugs.
3078  EXPECT_NONFATAL_FAILURE({  // NOLINT
3079    EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3080  }, "(values_.nan1) <= (values_.infinity)");
3081  EXPECT_NONFATAL_FAILURE({  // NOLINT
3082    EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3083  }, " (-values_.infinity) <= (values_.nan1)");
3084  EXPECT_FATAL_FAILURE({  // NOLINT
3085    ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3086  }, "(values_.nan1) <= (values_.nan1)");
3087#endif  // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3088}
3089
3090
3091// Verifies that a test or test case whose name starts with DISABLED_ is
3092// not run.
3093
3094// A test whose name starts with DISABLED_.
3095// Should not run.
3096TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3097  FAIL() << "Unexpected failure: Disabled test should not be run.";
3098}
3099
3100// A test whose name does not start with DISABLED_.
3101// Should run.
3102TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3103  EXPECT_EQ(1, 1);
3104}
3105
3106// A test case whose name starts with DISABLED_.
3107// Should not run.
3108TEST(DISABLED_TestCase, TestShouldNotRun) {
3109  FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3110}
3111
3112// A test case and test whose names start with DISABLED_.
3113// Should not run.
3114TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3115  FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3116}
3117
3118// Check that when all tests in a test case are disabled, SetupTestCase() and
3119// TearDownTestCase() are not called.
3120class DisabledTestsTest : public Test {
3121 protected:
3122  static void SetUpTestCase() {
3123    FAIL() << "Unexpected failure: All tests disabled in test case. "
3124              "SetupTestCase() should not be called.";
3125  }
3126
3127  static void TearDownTestCase() {
3128    FAIL() << "Unexpected failure: All tests disabled in test case. "
3129              "TearDownTestCase() should not be called.";
3130  }
3131};
3132
3133TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3134  FAIL() << "Unexpected failure: Disabled test should not be run.";
3135}
3136
3137TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3138  FAIL() << "Unexpected failure: Disabled test should not be run.";
3139}
3140
3141// Tests that disabled typed tests aren't run.
3142
3143#if GTEST_HAS_TYPED_TEST
3144
3145template <typename T>
3146class TypedTest : public Test {
3147};
3148
3149typedef testing::Types<int, double> NumericTypes;
3150TYPED_TEST_CASE(TypedTest, NumericTypes);
3151
3152TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3153  FAIL() << "Unexpected failure: Disabled typed test should not run.";
3154}
3155
3156template <typename T>
3157class DISABLED_TypedTest : public Test {
3158};
3159
3160TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3161
3162TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3163  FAIL() << "Unexpected failure: Disabled typed test should not run.";
3164}
3165
3166#endif  // GTEST_HAS_TYPED_TEST
3167
3168// Tests that disabled type-parameterized tests aren't run.
3169
3170#if GTEST_HAS_TYPED_TEST_P
3171
3172template <typename T>
3173class TypedTestP : public Test {
3174};
3175
3176TYPED_TEST_CASE_P(TypedTestP);
3177
3178TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3179  FAIL() << "Unexpected failure: "
3180         << "Disabled type-parameterized test should not run.";
3181}
3182
3183REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3184
3185INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3186
3187template <typename T>
3188class DISABLED_TypedTestP : public Test {
3189};
3190
3191TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3192
3193TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3194  FAIL() << "Unexpected failure: "
3195         << "Disabled type-parameterized test should not run.";
3196}
3197
3198REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3199
3200INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3201
3202#endif  // GTEST_HAS_TYPED_TEST_P
3203
3204// Tests that assertion macros evaluate their arguments exactly once.
3205
3206class SingleEvaluationTest : public Test {
3207 public:  // Must be public and not protected due to a bug in g++ 3.4.2.
3208  // This helper function is needed by the FailedASSERT_STREQ test
3209  // below.  It's public to work around C++Builder's bug with scoping local
3210  // classes.
3211  static void CompareAndIncrementCharPtrs() {
3212    ASSERT_STREQ(p1_++, p2_++);
3213  }
3214
3215  // This helper function is needed by the FailedASSERT_NE test below.  It's
3216  // public to work around C++Builder's bug with scoping local classes.
3217  static void CompareAndIncrementInts() {
3218    ASSERT_NE(a_++, b_++);
3219  }
3220
3221 protected:
3222  SingleEvaluationTest() {
3223    p1_ = s1_;
3224    p2_ = s2_;
3225    a_ = 0;
3226    b_ = 0;
3227  }
3228
3229  static const char* const s1_;
3230  static const char* const s2_;
3231  static const char* p1_;
3232  static const char* p2_;
3233
3234  static int a_;
3235  static int b_;
3236};
3237
3238const char* const SingleEvaluationTest::s1_ = "01234";
3239const char* const SingleEvaluationTest::s2_ = "abcde";
3240const char* SingleEvaluationTest::p1_;
3241const char* SingleEvaluationTest::p2_;
3242int SingleEvaluationTest::a_;
3243int SingleEvaluationTest::b_;
3244
3245// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3246// exactly once.
3247TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3248  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3249                       "p2_++");
3250  EXPECT_EQ(s1_ + 1, p1_);
3251  EXPECT_EQ(s2_ + 1, p2_);
3252}
3253
3254// Tests that string assertion arguments are evaluated exactly once.
3255TEST_F(SingleEvaluationTest, ASSERT_STR) {
3256  // successful EXPECT_STRNE
3257  EXPECT_STRNE(p1_++, p2_++);
3258  EXPECT_EQ(s1_ + 1, p1_);
3259  EXPECT_EQ(s2_ + 1, p2_);
3260
3261  // failed EXPECT_STRCASEEQ
3262  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3263                          "ignoring case");
3264  EXPECT_EQ(s1_ + 2, p1_);
3265  EXPECT_EQ(s2_ + 2, p2_);
3266}
3267
3268// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3269// once.
3270TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3271  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3272                       "(a_++) != (b_++)");
3273  EXPECT_EQ(1, a_);
3274  EXPECT_EQ(1, b_);
3275}
3276
3277// Tests that assertion arguments are evaluated exactly once.
3278TEST_F(SingleEvaluationTest, OtherCases) {
3279  // successful EXPECT_TRUE
3280  EXPECT_TRUE(0 == a_++);  // NOLINT
3281  EXPECT_EQ(1, a_);
3282
3283  // failed EXPECT_TRUE
3284  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3285  EXPECT_EQ(2, a_);
3286
3287  // successful EXPECT_GT
3288  EXPECT_GT(a_++, b_++);
3289  EXPECT_EQ(3, a_);
3290  EXPECT_EQ(1, b_);
3291
3292  // failed EXPECT_LT
3293  EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3294  EXPECT_EQ(4, a_);
3295  EXPECT_EQ(2, b_);
3296
3297  // successful ASSERT_TRUE
3298  ASSERT_TRUE(0 < a_++);  // NOLINT
3299  EXPECT_EQ(5, a_);
3300
3301  // successful ASSERT_GT
3302  ASSERT_GT(a_++, b_++);
3303  EXPECT_EQ(6, a_);
3304  EXPECT_EQ(3, b_);
3305}
3306
3307#if GTEST_HAS_EXCEPTIONS
3308
3309void ThrowAnInteger() {
3310  throw 1;
3311}
3312
3313// Tests that assertion arguments are evaluated exactly once.
3314TEST_F(SingleEvaluationTest, ExceptionTests) {
3315  // successful EXPECT_THROW
3316  EXPECT_THROW({  // NOLINT
3317    a_++;
3318    ThrowAnInteger();
3319  }, int);
3320  EXPECT_EQ(1, a_);
3321
3322  // failed EXPECT_THROW, throws different
3323  EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
3324    a_++;
3325    ThrowAnInteger();
3326  }, bool), "throws a different type");
3327  EXPECT_EQ(2, a_);
3328
3329  // failed EXPECT_THROW, throws nothing
3330  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3331  EXPECT_EQ(3, a_);
3332
3333  // successful EXPECT_NO_THROW
3334  EXPECT_NO_THROW(a_++);
3335  EXPECT_EQ(4, a_);
3336
3337  // failed EXPECT_NO_THROW
3338  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({  // NOLINT
3339    a_++;
3340    ThrowAnInteger();
3341  }), "it throws");
3342  EXPECT_EQ(5, a_);
3343
3344  // successful EXPECT_ANY_THROW
3345  EXPECT_ANY_THROW({  // NOLINT
3346    a_++;
3347    ThrowAnInteger();
3348  });
3349  EXPECT_EQ(6, a_);
3350
3351  // failed EXPECT_ANY_THROW
3352  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3353  EXPECT_EQ(7, a_);
3354}
3355
3356#endif  // GTEST_HAS_EXCEPTIONS
3357
3358// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3359class NoFatalFailureTest : public Test {
3360 protected:
3361  void Succeeds() {}
3362  void FailsNonFatal() {
3363    ADD_FAILURE() << "some non-fatal failure";
3364  }
3365  void Fails() {
3366    FAIL() << "some fatal failure";
3367  }
3368
3369  void DoAssertNoFatalFailureOnFails() {
3370    ASSERT_NO_FATAL_FAILURE(Fails());
3371    ADD_FAILURE() << "shold not reach here.";
3372  }
3373
3374  void DoExpectNoFatalFailureOnFails() {
3375    EXPECT_NO_FATAL_FAILURE(Fails());
3376    ADD_FAILURE() << "other failure";
3377  }
3378};
3379
3380TEST_F(NoFatalFailureTest, NoFailure) {
3381  EXPECT_NO_FATAL_FAILURE(Succeeds());
3382  ASSERT_NO_FATAL_FAILURE(Succeeds());
3383}
3384
3385TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3386  EXPECT_NONFATAL_FAILURE(
3387      EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3388      "some non-fatal failure");
3389  EXPECT_NONFATAL_FAILURE(
3390      ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3391      "some non-fatal failure");
3392}
3393
3394TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3395  TestPartResultArray gtest_failures;
3396  {
3397    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3398    DoAssertNoFatalFailureOnFails();
3399  }
3400  ASSERT_EQ(2, gtest_failures.size());
3401  EXPECT_EQ(TestPartResult::kFatalFailure,
3402            gtest_failures.GetTestPartResult(0).type());
3403  EXPECT_EQ(TestPartResult::kFatalFailure,
3404            gtest_failures.GetTestPartResult(1).type());
3405  EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3406                      gtest_failures.GetTestPartResult(0).message());
3407  EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3408                      gtest_failures.GetTestPartResult(1).message());
3409}
3410
3411TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3412  TestPartResultArray gtest_failures;
3413  {
3414    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3415    DoExpectNoFatalFailureOnFails();
3416  }
3417  ASSERT_EQ(3, gtest_failures.size());
3418  EXPECT_EQ(TestPartResult::kFatalFailure,
3419            gtest_failures.GetTestPartResult(0).type());
3420  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3421            gtest_failures.GetTestPartResult(1).type());
3422  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3423            gtest_failures.GetTestPartResult(2).type());
3424  EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3425                      gtest_failures.GetTestPartResult(0).message());
3426  EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3427                      gtest_failures.GetTestPartResult(1).message());
3428  EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3429                      gtest_failures.GetTestPartResult(2).message());
3430}
3431
3432TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3433  TestPartResultArray gtest_failures;
3434  {
3435    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3436    EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3437  }
3438  ASSERT_EQ(2, gtest_failures.size());
3439  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3440            gtest_failures.GetTestPartResult(0).type());
3441  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3442            gtest_failures.GetTestPartResult(1).type());
3443  EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3444                      gtest_failures.GetTestPartResult(0).message());
3445  EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3446                      gtest_failures.GetTestPartResult(1).message());
3447}
3448
3449// Tests non-string assertions.
3450
3451std::string EditsToString(const std::vector<EditType>& edits) {
3452  std::string out;
3453  for (size_t i = 0; i < edits.size(); ++i) {
3454    static const char kEdits[] = " +-/";
3455    out.append(1, kEdits[edits[i]]);
3456  }
3457  return out;
3458}
3459
3460std::vector<size_t> CharsToIndices(const std::string& str) {
3461  std::vector<size_t> out;
3462  for (size_t i = 0; i < str.size(); ++i) {
3463    out.push_back(str[i]);
3464  }
3465  return out;
3466}
3467
3468std::vector<std::string> CharsToLines(const std::string& str) {
3469  std::vector<std::string> out;
3470  for (size_t i = 0; i < str.size(); ++i) {
3471    out.push_back(str.substr(i, 1));
3472  }
3473  return out;
3474}
3475
3476TEST(EditDistance, TestCases) {
3477  struct Case {
3478    int line;
3479    const char* left;
3480    const char* right;
3481    const char* expected_edits;
3482    const char* expected_diff;
3483  };
3484  static const Case kCases[] = {
3485      // No change.
3486      {__LINE__, "A", "A", " ", ""},
3487      {__LINE__, "ABCDE", "ABCDE", "     ", ""},
3488      // Simple adds.
3489      {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3490      {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3491      // Simple removes.
3492      {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3493      {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3494      // Simple replaces.
3495      {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3496      {__LINE__, "ABCD", "abcd", "////",
3497       "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3498      // Path finding.
3499      {__LINE__, "ABCDEFGH", "ABXEGH1", "  -/ -  +",
3500       "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
3501      {__LINE__, "AAAABCCCC", "ABABCDCDC", "- /   + / ",
3502       "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
3503      {__LINE__, "ABCDE", "BCDCD", "-   +/",
3504       "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3505      {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++     --   ++",
3506       "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3507       "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3508      {}};
3509  for (const Case* c = kCases; c->left; ++c) {
3510    EXPECT_TRUE(c->expected_edits ==
3511                EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3512                                                    CharsToIndices(c->right))))
3513        << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3514        << EditsToString(CalculateOptimalEdits(
3515               CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3516    EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3517                                                      CharsToLines(c->right)))
3518        << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3519        << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3520        << ">";
3521  }
3522}
3523
3524// Tests EqFailure(), used for implementing *EQ* assertions.
3525TEST(AssertionTest, EqFailure) {
3526  const std::string foo_val("5"), bar_val("6");
3527  const std::string msg1(
3528      EqFailure("foo", "bar", foo_val, bar_val, false)
3529      .failure_message());
3530  EXPECT_STREQ(
3531      "Value of: bar\n"
3532      "  Actual: 6\n"
3533      "Expected: foo\n"
3534      "Which is: 5",
3535      msg1.c_str());
3536
3537  const std::string msg2(
3538      EqFailure("foo", "6", foo_val, bar_val, false)
3539      .failure_message());
3540  EXPECT_STREQ(
3541      "Value of: 6\n"
3542      "Expected: foo\n"
3543      "Which is: 5",
3544      msg2.c_str());
3545
3546  const std::string msg3(
3547      EqFailure("5", "bar", foo_val, bar_val, false)
3548      .failure_message());
3549  EXPECT_STREQ(
3550      "Value of: bar\n"
3551      "  Actual: 6\n"
3552      "Expected: 5",
3553      msg3.c_str());
3554
3555  const std::string msg4(
3556      EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3557  EXPECT_STREQ(
3558      "Value of: 6\n"
3559      "Expected: 5",
3560      msg4.c_str());
3561
3562  const std::string msg5(
3563      EqFailure("foo", "bar",
3564                std::string("\"x\""), std::string("\"y\""),
3565                true).failure_message());
3566  EXPECT_STREQ(
3567      "Value of: bar\n"
3568      "  Actual: \"y\"\n"
3569      "Expected: foo (ignoring case)\n"
3570      "Which is: \"x\"",
3571      msg5.c_str());
3572}
3573
3574TEST(AssertionTest, EqFailureWithDiff) {
3575  const std::string left(
3576      "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3577  const std::string right(
3578      "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3579  const std::string msg1(
3580      EqFailure("left", "right", left, right, false).failure_message());
3581  EXPECT_STREQ(
3582      "Value of: right\n"
3583      "  Actual: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3584      "Expected: left\n"
3585      "Which is: "
3586      "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3587      "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3588      "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3589      msg1.c_str());
3590}
3591
3592// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3593TEST(AssertionTest, AppendUserMessage) {
3594  const std::string foo("foo");
3595
3596  Message msg;
3597  EXPECT_STREQ("foo",
3598               AppendUserMessage(foo, msg).c_str());
3599
3600  msg << "bar";
3601  EXPECT_STREQ("foo\nbar",
3602               AppendUserMessage(foo, msg).c_str());
3603}
3604
3605#ifdef __BORLANDC__
3606// Silences warnings: "Condition is always true", "Unreachable code"
3607# pragma option push -w-ccc -w-rch
3608#endif
3609
3610// Tests ASSERT_TRUE.
3611TEST(AssertionTest, ASSERT_TRUE) {
3612  ASSERT_TRUE(2 > 1);  // NOLINT
3613  EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3614                       "2 < 1");
3615}
3616
3617// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3618TEST(AssertionTest, AssertTrueWithAssertionResult) {
3619  ASSERT_TRUE(ResultIsEven(2));
3620#ifndef __BORLANDC__
3621  // ICE's in C++Builder.
3622  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3623                       "Value of: ResultIsEven(3)\n"
3624                       "  Actual: false (3 is odd)\n"
3625                       "Expected: true");
3626#endif
3627  ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3628  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3629                       "Value of: ResultIsEvenNoExplanation(3)\n"
3630                       "  Actual: false (3 is odd)\n"
3631                       "Expected: true");
3632}
3633
3634// Tests ASSERT_FALSE.
3635TEST(AssertionTest, ASSERT_FALSE) {
3636  ASSERT_FALSE(2 < 1);  // NOLINT
3637  EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3638                       "Value of: 2 > 1\n"
3639                       "  Actual: true\n"
3640                       "Expected: false");
3641}
3642
3643// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3644TEST(AssertionTest, AssertFalseWithAssertionResult) {
3645  ASSERT_FALSE(ResultIsEven(3));
3646#ifndef __BORLANDC__
3647  // ICE's in C++Builder.
3648  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3649                       "Value of: ResultIsEven(2)\n"
3650                       "  Actual: true (2 is even)\n"
3651                       "Expected: false");
3652#endif
3653  ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3654  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3655                       "Value of: ResultIsEvenNoExplanation(2)\n"
3656                       "  Actual: true\n"
3657                       "Expected: false");
3658}
3659
3660#ifdef __BORLANDC__
3661// Restores warnings after previous "#pragma option push" supressed them
3662# pragma option pop
3663#endif
3664
3665// Tests using ASSERT_EQ on double values.  The purpose is to make
3666// sure that the specialization we did for integer and anonymous enums
3667// isn't used for double arguments.
3668TEST(ExpectTest, ASSERT_EQ_Double) {
3669  // A success.
3670  ASSERT_EQ(5.6, 5.6);
3671
3672  // A failure.
3673  EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3674                       "5.1");
3675}
3676
3677// Tests ASSERT_EQ.
3678TEST(AssertionTest, ASSERT_EQ) {
3679  ASSERT_EQ(5, 2 + 3);
3680  EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3681                       "Value of: 2*3\n"
3682                       "  Actual: 6\n"
3683                       "Expected: 5");
3684}
3685
3686// Tests ASSERT_EQ(NULL, pointer).
3687#if GTEST_CAN_COMPARE_NULL
3688TEST(AssertionTest, ASSERT_EQ_NULL) {
3689  // A success.
3690  const char* p = NULL;
3691  // Some older GCC versions may issue a spurious waring in this or the next
3692  // assertion statement. This warning should not be suppressed with
3693  // static_cast since the test verifies the ability to use bare NULL as the
3694  // expected parameter to the macro.
3695  ASSERT_EQ(NULL, p);
3696
3697  // A failure.
3698  static int n = 0;
3699  EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3700                       "Value of: &n\n");
3701}
3702#endif  // GTEST_CAN_COMPARE_NULL
3703
3704// Tests ASSERT_EQ(0, non_pointer).  Since the literal 0 can be
3705// treated as a null pointer by the compiler, we need to make sure
3706// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3707// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3708TEST(ExpectTest, ASSERT_EQ_0) {
3709  int n = 0;
3710
3711  // A success.
3712  ASSERT_EQ(0, n);
3713
3714  // A failure.
3715  EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3716                       "Expected: 0");
3717}
3718
3719// Tests ASSERT_NE.
3720TEST(AssertionTest, ASSERT_NE) {
3721  ASSERT_NE(6, 7);
3722  EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3723                       "Expected: ('a') != ('a'), "
3724                       "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3725}
3726
3727// Tests ASSERT_LE.
3728TEST(AssertionTest, ASSERT_LE) {
3729  ASSERT_LE(2, 3);
3730  ASSERT_LE(2, 2);
3731  EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3732                       "Expected: (2) <= (0), actual: 2 vs 0");
3733}
3734
3735// Tests ASSERT_LT.
3736TEST(AssertionTest, ASSERT_LT) {
3737  ASSERT_LT(2, 3);
3738  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3739                       "Expected: (2) < (2), actual: 2 vs 2");
3740}
3741
3742// Tests ASSERT_GE.
3743TEST(AssertionTest, ASSERT_GE) {
3744  ASSERT_GE(2, 1);
3745  ASSERT_GE(2, 2);
3746  EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3747                       "Expected: (2) >= (3), actual: 2 vs 3");
3748}
3749
3750// Tests ASSERT_GT.
3751TEST(AssertionTest, ASSERT_GT) {
3752  ASSERT_GT(2, 1);
3753  EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3754                       "Expected: (2) > (2), actual: 2 vs 2");
3755}
3756
3757#if GTEST_HAS_EXCEPTIONS
3758
3759void ThrowNothing() {}
3760
3761// Tests ASSERT_THROW.
3762TEST(AssertionTest, ASSERT_THROW) {
3763  ASSERT_THROW(ThrowAnInteger(), int);
3764
3765# ifndef __BORLANDC__
3766
3767  // ICE's in C++Builder 2007 and 2009.
3768  EXPECT_FATAL_FAILURE(
3769      ASSERT_THROW(ThrowAnInteger(), bool),
3770      "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3771      "  Actual: it throws a different type.");
3772# endif
3773
3774  EXPECT_FATAL_FAILURE(
3775      ASSERT_THROW(ThrowNothing(), bool),
3776      "Expected: ThrowNothing() throws an exception of type bool.\n"
3777      "  Actual: it throws nothing.");
3778}
3779
3780// Tests ASSERT_NO_THROW.
3781TEST(AssertionTest, ASSERT_NO_THROW) {
3782  ASSERT_NO_THROW(ThrowNothing());
3783  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3784                       "Expected: ThrowAnInteger() doesn't throw an exception."
3785                       "\n  Actual: it throws.");
3786}
3787
3788// Tests ASSERT_ANY_THROW.
3789TEST(AssertionTest, ASSERT_ANY_THROW) {
3790  ASSERT_ANY_THROW(ThrowAnInteger());
3791  EXPECT_FATAL_FAILURE(
3792      ASSERT_ANY_THROW(ThrowNothing()),
3793      "Expected: ThrowNothing() throws an exception.\n"
3794      "  Actual: it doesn't.");
3795}
3796
3797#endif  // GTEST_HAS_EXCEPTIONS
3798
3799// Makes sure we deal with the precedence of <<.  This test should
3800// compile.
3801TEST(AssertionTest, AssertPrecedence) {
3802  ASSERT_EQ(1 < 2, true);
3803  bool false_value = false;
3804  ASSERT_EQ(true && false_value, false);
3805}
3806
3807// A subroutine used by the following test.
3808void TestEq1(int x) {
3809  ASSERT_EQ(1, x);
3810}
3811
3812// Tests calling a test subroutine that's not part of a fixture.
3813TEST(AssertionTest, NonFixtureSubroutine) {
3814  EXPECT_FATAL_FAILURE(TestEq1(2),
3815                       "Value of: x");
3816}
3817
3818// An uncopyable class.
3819class Uncopyable {
3820 public:
3821  explicit Uncopyable(int a_value) : value_(a_value) {}
3822
3823  int value() const { return value_; }
3824  bool operator==(const Uncopyable& rhs) const {
3825    return value() == rhs.value();
3826  }
3827 private:
3828  // This constructor deliberately has no implementation, as we don't
3829  // want this class to be copyable.
3830  Uncopyable(const Uncopyable&);  // NOLINT
3831
3832  int value_;
3833};
3834
3835::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3836  return os << value.value();
3837}
3838
3839
3840bool IsPositiveUncopyable(const Uncopyable& x) {
3841  return x.value() > 0;
3842}
3843
3844// A subroutine used by the following test.
3845void TestAssertNonPositive() {
3846  Uncopyable y(-1);
3847  ASSERT_PRED1(IsPositiveUncopyable, y);
3848}
3849// A subroutine used by the following test.
3850void TestAssertEqualsUncopyable() {
3851  Uncopyable x(5);
3852  Uncopyable y(-1);
3853  ASSERT_EQ(x, y);
3854}
3855
3856// Tests that uncopyable objects can be used in assertions.
3857TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3858  Uncopyable x(5);
3859  ASSERT_PRED1(IsPositiveUncopyable, x);
3860  ASSERT_EQ(x, x);
3861  EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3862    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3863  EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3864    "Value of: y\n  Actual: -1\nExpected: x\nWhich is: 5");
3865}
3866
3867// Tests that uncopyable objects can be used in expects.
3868TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3869  Uncopyable x(5);
3870  EXPECT_PRED1(IsPositiveUncopyable, x);
3871  Uncopyable y(-1);
3872  EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3873    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3874  EXPECT_EQ(x, x);
3875  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3876    "Value of: y\n  Actual: -1\nExpected: x\nWhich is: 5");
3877}
3878
3879enum NamedEnum {
3880  kE1 = 0,
3881  kE2 = 1
3882};
3883
3884TEST(AssertionTest, NamedEnum) {
3885  EXPECT_EQ(kE1, kE1);
3886  EXPECT_LT(kE1, kE2);
3887  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3888  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
3889}
3890
3891// The version of gcc used in XCode 2.2 has a bug and doesn't allow
3892// anonymous enums in assertions.  Therefore the following test is not
3893// done on Mac.
3894// Sun Studio and HP aCC also reject this code.
3895#if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3896
3897// Tests using assertions with anonymous enums.
3898enum {
3899  kCaseA = -1,
3900
3901# if GTEST_OS_LINUX
3902
3903  // We want to test the case where the size of the anonymous enum is
3904  // larger than sizeof(int), to make sure our implementation of the
3905  // assertions doesn't truncate the enums.  However, MSVC
3906  // (incorrectly) doesn't allow an enum value to exceed the range of
3907  // an int, so this has to be conditionally compiled.
3908  //
3909  // On Linux, kCaseB and kCaseA have the same value when truncated to
3910  // int size.  We want to test whether this will confuse the
3911  // assertions.
3912  kCaseB = testing::internal::kMaxBiggestInt,
3913
3914# else
3915
3916  kCaseB = INT_MAX,
3917
3918# endif  // GTEST_OS_LINUX
3919
3920  kCaseC = 42
3921};
3922
3923TEST(AssertionTest, AnonymousEnum) {
3924# if GTEST_OS_LINUX
3925
3926  EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3927
3928# endif  // GTEST_OS_LINUX
3929
3930  EXPECT_EQ(kCaseA, kCaseA);
3931  EXPECT_NE(kCaseA, kCaseB);
3932  EXPECT_LT(kCaseA, kCaseB);
3933  EXPECT_LE(kCaseA, kCaseB);
3934  EXPECT_GT(kCaseB, kCaseA);
3935  EXPECT_GE(kCaseA, kCaseA);
3936  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3937                          "(kCaseA) >= (kCaseB)");
3938  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3939                          "-1 vs 42");
3940
3941  ASSERT_EQ(kCaseA, kCaseA);
3942  ASSERT_NE(kCaseA, kCaseB);
3943  ASSERT_LT(kCaseA, kCaseB);
3944  ASSERT_LE(kCaseA, kCaseB);
3945  ASSERT_GT(kCaseB, kCaseA);
3946  ASSERT_GE(kCaseA, kCaseA);
3947
3948# ifndef __BORLANDC__
3949
3950  // ICE's in C++Builder.
3951  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3952                       "Value of: kCaseB");
3953  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3954                       "Actual: 42");
3955# endif
3956
3957  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3958                       "Which is: -1");
3959}
3960
3961#endif  // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3962
3963#if GTEST_OS_WINDOWS
3964
3965static HRESULT UnexpectedHRESULTFailure() {
3966  return E_UNEXPECTED;
3967}
3968
3969static HRESULT OkHRESULTSuccess() {
3970  return S_OK;
3971}
3972
3973static HRESULT FalseHRESULTSuccess() {
3974  return S_FALSE;
3975}
3976
3977// HRESULT assertion tests test both zero and non-zero
3978// success codes as well as failure message for each.
3979//
3980// Windows CE doesn't support message texts.
3981TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3982  EXPECT_HRESULT_SUCCEEDED(S_OK);
3983  EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3984
3985  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3986    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3987    "  Actual: 0x8000FFFF");
3988}
3989
3990TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3991  ASSERT_HRESULT_SUCCEEDED(S_OK);
3992  ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3993
3994  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3995    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3996    "  Actual: 0x8000FFFF");
3997}
3998
3999TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4000  EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4001
4002  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4003    "Expected: (OkHRESULTSuccess()) fails.\n"
4004    "  Actual: 0x0");
4005  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4006    "Expected: (FalseHRESULTSuccess()) fails.\n"
4007    "  Actual: 0x1");
4008}
4009
4010TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4011  ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4012
4013# ifndef __BORLANDC__
4014
4015  // ICE's in C++Builder 2007 and 2009.
4016  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4017    "Expected: (OkHRESULTSuccess()) fails.\n"
4018    "  Actual: 0x0");
4019# endif
4020
4021  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4022    "Expected: (FalseHRESULTSuccess()) fails.\n"
4023    "  Actual: 0x1");
4024}
4025
4026// Tests that streaming to the HRESULT macros works.
4027TEST(HRESULTAssertionTest, Streaming) {
4028  EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4029  ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4030  EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4031  ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4032
4033  EXPECT_NONFATAL_FAILURE(
4034      EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4035      "expected failure");
4036
4037# ifndef __BORLANDC__
4038
4039  // ICE's in C++Builder 2007 and 2009.
4040  EXPECT_FATAL_FAILURE(
4041      ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4042      "expected failure");
4043# endif
4044
4045  EXPECT_NONFATAL_FAILURE(
4046      EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4047      "expected failure");
4048
4049  EXPECT_FATAL_FAILURE(
4050      ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4051      "expected failure");
4052}
4053
4054#endif  // GTEST_OS_WINDOWS
4055
4056#ifdef __BORLANDC__
4057// Silences warnings: "Condition is always true", "Unreachable code"
4058# pragma option push -w-ccc -w-rch
4059#endif
4060
4061// Tests that the assertion macros behave like single statements.
4062TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4063  if (AlwaysFalse())
4064    ASSERT_TRUE(false) << "This should never be executed; "
4065                          "It's a compilation test only.";
4066
4067  if (AlwaysTrue())
4068    EXPECT_FALSE(false);
4069  else
4070    ;  // NOLINT
4071
4072  if (AlwaysFalse())
4073    ASSERT_LT(1, 3);
4074
4075  if (AlwaysFalse())
4076    ;  // NOLINT
4077  else
4078    EXPECT_GT(3, 2) << "";
4079}
4080
4081#if GTEST_HAS_EXCEPTIONS
4082// Tests that the compiler will not complain about unreachable code in the
4083// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4084TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4085  int n = 0;
4086
4087  EXPECT_THROW(throw 1, int);
4088  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4089  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4090  EXPECT_NO_THROW(n++);
4091  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4092  EXPECT_ANY_THROW(throw 1);
4093  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4094}
4095
4096TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4097  if (AlwaysFalse())
4098    EXPECT_THROW(ThrowNothing(), bool);
4099
4100  if (AlwaysTrue())
4101    EXPECT_THROW(ThrowAnInteger(), int);
4102  else
4103    ;  // NOLINT
4104
4105  if (AlwaysFalse())
4106    EXPECT_NO_THROW(ThrowAnInteger());
4107
4108  if (AlwaysTrue())
4109    EXPECT_NO_THROW(ThrowNothing());
4110  else
4111    ;  // NOLINT
4112
4113  if (AlwaysFalse())
4114    EXPECT_ANY_THROW(ThrowNothing());
4115
4116  if (AlwaysTrue())
4117    EXPECT_ANY_THROW(ThrowAnInteger());
4118  else
4119    ;  // NOLINT
4120}
4121#endif  // GTEST_HAS_EXCEPTIONS
4122
4123TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4124  if (AlwaysFalse())
4125    EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4126                                    << "It's a compilation test only.";
4127  else
4128    ;  // NOLINT
4129
4130  if (AlwaysFalse())
4131    ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4132  else
4133    ;  // NOLINT
4134
4135  if (AlwaysTrue())
4136    EXPECT_NO_FATAL_FAILURE(SUCCEED());
4137  else
4138    ;  // NOLINT
4139
4140  if (AlwaysFalse())
4141    ;  // NOLINT
4142  else
4143    ASSERT_NO_FATAL_FAILURE(SUCCEED());
4144}
4145
4146// Tests that the assertion macros work well with switch statements.
4147TEST(AssertionSyntaxTest, WorksWithSwitch) {
4148  switch (0) {
4149    case 1:
4150      break;
4151    default:
4152      ASSERT_TRUE(true);
4153  }
4154
4155  switch (0)
4156    case 0:
4157      EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4158
4159  // Binary assertions are implemented using a different code path
4160  // than the Boolean assertions.  Hence we test them separately.
4161  switch (0) {
4162    case 1:
4163    default:
4164      ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4165  }
4166
4167  switch (0)
4168    case 0:
4169      EXPECT_NE(1, 2);
4170}
4171
4172#if GTEST_HAS_EXCEPTIONS
4173
4174void ThrowAString() {
4175    throw "std::string";
4176}
4177
4178// Test that the exception assertion macros compile and work with const
4179// type qualifier.
4180TEST(AssertionSyntaxTest, WorksWithConst) {
4181    ASSERT_THROW(ThrowAString(), const char*);
4182
4183    EXPECT_THROW(ThrowAString(), const char*);
4184}
4185
4186#endif  // GTEST_HAS_EXCEPTIONS
4187
4188}  // namespace
4189
4190namespace testing {
4191
4192// Tests that Google Test tracks SUCCEED*.
4193TEST(SuccessfulAssertionTest, SUCCEED) {
4194  SUCCEED();
4195  SUCCEED() << "OK";
4196  EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4197}
4198
4199// Tests that Google Test doesn't track successful EXPECT_*.
4200TEST(SuccessfulAssertionTest, EXPECT) {
4201  EXPECT_TRUE(true);
4202  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4203}
4204
4205// Tests that Google Test doesn't track successful EXPECT_STR*.
4206TEST(SuccessfulAssertionTest, EXPECT_STR) {
4207  EXPECT_STREQ("", "");
4208  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4209}
4210
4211// Tests that Google Test doesn't track successful ASSERT_*.
4212TEST(SuccessfulAssertionTest, ASSERT) {
4213  ASSERT_TRUE(true);
4214  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4215}
4216
4217// Tests that Google Test doesn't track successful ASSERT_STR*.
4218TEST(SuccessfulAssertionTest, ASSERT_STR) {
4219  ASSERT_STREQ("", "");
4220  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4221}
4222
4223}  // namespace testing
4224
4225namespace {
4226
4227// Tests the message streaming variation of assertions.
4228
4229TEST(AssertionWithMessageTest, EXPECT) {
4230  EXPECT_EQ(1, 1) << "This should succeed.";
4231  EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4232                          "Expected failure #1");
4233  EXPECT_LE(1, 2) << "This should succeed.";
4234  EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4235                          "Expected failure #2.");
4236  EXPECT_GE(1, 0) << "This should succeed.";
4237  EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4238                          "Expected failure #3.");
4239
4240  EXPECT_STREQ("1", "1") << "This should succeed.";
4241  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4242                          "Expected failure #4.");
4243  EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4244  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4245                          "Expected failure #5.");
4246
4247  EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4248  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4249                          "Expected failure #6.");
4250  EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4251}
4252
4253TEST(AssertionWithMessageTest, ASSERT) {
4254  ASSERT_EQ(1, 1) << "This should succeed.";
4255  ASSERT_NE(1, 2) << "This should succeed.";
4256  ASSERT_LE(1, 2) << "This should succeed.";
4257  ASSERT_LT(1, 2) << "This should succeed.";
4258  ASSERT_GE(1, 0) << "This should succeed.";
4259  EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4260                       "Expected failure.");
4261}
4262
4263TEST(AssertionWithMessageTest, ASSERT_STR) {
4264  ASSERT_STREQ("1", "1") << "This should succeed.";
4265  ASSERT_STRNE("1", "2") << "This should succeed.";
4266  ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4267  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4268                       "Expected failure.");
4269}
4270
4271TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4272  ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4273  ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4274  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.",  // NOLINT
4275                       "Expect failure.");
4276  // To work around a bug in gcc 2.95.0, there is intentionally no
4277  // space after the first comma in the previous statement.
4278}
4279
4280// Tests using ASSERT_FALSE with a streamed message.
4281TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4282  ASSERT_FALSE(false) << "This shouldn't fail.";
4283  EXPECT_FATAL_FAILURE({  // NOLINT
4284    ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4285                       << " evaluates to " << true;
4286  }, "Expected failure");
4287}
4288
4289// Tests using FAIL with a streamed message.
4290TEST(AssertionWithMessageTest, FAIL) {
4291  EXPECT_FATAL_FAILURE(FAIL() << 0,
4292                       "0");
4293}
4294
4295// Tests using SUCCEED with a streamed message.
4296TEST(AssertionWithMessageTest, SUCCEED) {
4297  SUCCEED() << "Success == " << 1;
4298}
4299
4300// Tests using ASSERT_TRUE with a streamed message.
4301TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4302  ASSERT_TRUE(true) << "This should succeed.";
4303  ASSERT_TRUE(true) << true;
4304  EXPECT_FATAL_FAILURE({  // NOLINT
4305    ASSERT_TRUE(false) << static_cast<const char *>(NULL)
4306                       << static_cast<char *>(NULL);
4307  }, "(null)(null)");
4308}
4309
4310#if GTEST_OS_WINDOWS
4311// Tests using wide strings in assertion messages.
4312TEST(AssertionWithMessageTest, WideStringMessage) {
4313  EXPECT_NONFATAL_FAILURE({  // NOLINT
4314    EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4315  }, "This failure is expected.");
4316  EXPECT_FATAL_FAILURE({  // NOLINT
4317    ASSERT_EQ(1, 2) << "This failure is "
4318                    << L"expected too.\x8120";
4319  }, "This failure is expected too.");
4320}
4321#endif  // GTEST_OS_WINDOWS
4322
4323// Tests EXPECT_TRUE.
4324TEST(ExpectTest, EXPECT_TRUE) {
4325  EXPECT_TRUE(true) << "Intentional success";
4326  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4327                          "Intentional failure #1.");
4328  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4329                          "Intentional failure #2.");
4330  EXPECT_TRUE(2 > 1);  // NOLINT
4331  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4332                          "Value of: 2 < 1\n"
4333                          "  Actual: false\n"
4334                          "Expected: true");
4335  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4336                          "2 > 3");
4337}
4338
4339// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4340TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4341  EXPECT_TRUE(ResultIsEven(2));
4342  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4343                          "Value of: ResultIsEven(3)\n"
4344                          "  Actual: false (3 is odd)\n"
4345                          "Expected: true");
4346  EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4347  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4348                          "Value of: ResultIsEvenNoExplanation(3)\n"
4349                          "  Actual: false (3 is odd)\n"
4350                          "Expected: true");
4351}
4352
4353// Tests EXPECT_FALSE with a streamed message.
4354TEST(ExpectTest, EXPECT_FALSE) {
4355  EXPECT_FALSE(2 < 1);  // NOLINT
4356  EXPECT_FALSE(false) << "Intentional success";
4357  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4358                          "Intentional failure #1.");
4359  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4360                          "Intentional failure #2.");
4361  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4362                          "Value of: 2 > 1\n"
4363                          "  Actual: true\n"
4364                          "Expected: false");
4365  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4366                          "2 < 3");
4367}
4368
4369// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4370TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4371  EXPECT_FALSE(ResultIsEven(3));
4372  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4373                          "Value of: ResultIsEven(2)\n"
4374                          "  Actual: true (2 is even)\n"
4375                          "Expected: false");
4376  EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4377  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4378                          "Value of: ResultIsEvenNoExplanation(2)\n"
4379                          "  Actual: true\n"
4380                          "Expected: false");
4381}
4382
4383#ifdef __BORLANDC__
4384// Restores warnings after previous "#pragma option push" supressed them
4385# pragma option pop
4386#endif
4387
4388// Tests EXPECT_EQ.
4389TEST(ExpectTest, EXPECT_EQ) {
4390  EXPECT_EQ(5, 2 + 3);
4391  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4392                          "Value of: 2*3\n"
4393                          "  Actual: 6\n"
4394                          "Expected: 5");
4395  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4396                          "2 - 3");
4397}
4398
4399// Tests using EXPECT_EQ on double values.  The purpose is to make
4400// sure that the specialization we did for integer and anonymous enums
4401// isn't used for double arguments.
4402TEST(ExpectTest, EXPECT_EQ_Double) {
4403  // A success.
4404  EXPECT_EQ(5.6, 5.6);
4405
4406  // A failure.
4407  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4408                          "5.1");
4409}
4410
4411#if GTEST_CAN_COMPARE_NULL
4412// Tests EXPECT_EQ(NULL, pointer).
4413TEST(ExpectTest, EXPECT_EQ_NULL) {
4414  // A success.
4415  const char* p = NULL;
4416  // Some older GCC versions may issue a spurious warning in this or the next
4417  // assertion statement. This warning should not be suppressed with
4418  // static_cast since the test verifies the ability to use bare NULL as the
4419  // expected parameter to the macro.
4420  EXPECT_EQ(NULL, p);
4421
4422  // A failure.
4423  int n = 0;
4424  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4425                          "Value of: &n\n");
4426}
4427#endif  // GTEST_CAN_COMPARE_NULL
4428
4429// Tests EXPECT_EQ(0, non_pointer).  Since the literal 0 can be
4430// treated as a null pointer by the compiler, we need to make sure
4431// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4432// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4433TEST(ExpectTest, EXPECT_EQ_0) {
4434  int n = 0;
4435
4436  // A success.
4437  EXPECT_EQ(0, n);
4438
4439  // A failure.
4440  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4441                          "Expected: 0");
4442}
4443
4444// Tests EXPECT_NE.
4445TEST(ExpectTest, EXPECT_NE) {
4446  EXPECT_NE(6, 7);
4447
4448  EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4449                          "Expected: ('a') != ('a'), "
4450                          "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4451  EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4452                          "2");
4453  char* const p0 = NULL;
4454  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4455                          "p0");
4456  // Only way to get the Nokia compiler to compile the cast
4457  // is to have a separate void* variable first. Putting
4458  // the two casts on the same line doesn't work, neither does
4459  // a direct C-style to char*.
4460  void* pv1 = (void*)0x1234;  // NOLINT
4461  char* const p1 = reinterpret_cast<char*>(pv1);
4462  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4463                          "p1");
4464}
4465
4466// Tests EXPECT_LE.
4467TEST(ExpectTest, EXPECT_LE) {
4468  EXPECT_LE(2, 3);
4469  EXPECT_LE(2, 2);
4470  EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4471                          "Expected: (2) <= (0), actual: 2 vs 0");
4472  EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4473                          "(1.1) <= (0.9)");
4474}
4475
4476// Tests EXPECT_LT.
4477TEST(ExpectTest, EXPECT_LT) {
4478  EXPECT_LT(2, 3);
4479  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4480                          "Expected: (2) < (2), actual: 2 vs 2");
4481  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4482                          "(2) < (1)");
4483}
4484
4485// Tests EXPECT_GE.
4486TEST(ExpectTest, EXPECT_GE) {
4487  EXPECT_GE(2, 1);
4488  EXPECT_GE(2, 2);
4489  EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4490                          "Expected: (2) >= (3), actual: 2 vs 3");
4491  EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4492                          "(0.9) >= (1.1)");
4493}
4494
4495// Tests EXPECT_GT.
4496TEST(ExpectTest, EXPECT_GT) {
4497  EXPECT_GT(2, 1);
4498  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4499                          "Expected: (2) > (2), actual: 2 vs 2");
4500  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4501                          "(2) > (3)");
4502}
4503
4504#if GTEST_HAS_EXCEPTIONS
4505
4506// Tests EXPECT_THROW.
4507TEST(ExpectTest, EXPECT_THROW) {
4508  EXPECT_THROW(ThrowAnInteger(), int);
4509  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4510                          "Expected: ThrowAnInteger() throws an exception of "
4511                          "type bool.\n  Actual: it throws a different type.");
4512  EXPECT_NONFATAL_FAILURE(
4513      EXPECT_THROW(ThrowNothing(), bool),
4514      "Expected: ThrowNothing() throws an exception of type bool.\n"
4515      "  Actual: it throws nothing.");
4516}
4517
4518// Tests EXPECT_NO_THROW.
4519TEST(ExpectTest, EXPECT_NO_THROW) {
4520  EXPECT_NO_THROW(ThrowNothing());
4521  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4522                          "Expected: ThrowAnInteger() doesn't throw an "
4523                          "exception.\n  Actual: it throws.");
4524}
4525
4526// Tests EXPECT_ANY_THROW.
4527TEST(ExpectTest, EXPECT_ANY_THROW) {
4528  EXPECT_ANY_THROW(ThrowAnInteger());
4529  EXPECT_NONFATAL_FAILURE(
4530      EXPECT_ANY_THROW(ThrowNothing()),
4531      "Expected: ThrowNothing() throws an exception.\n"
4532      "  Actual: it doesn't.");
4533}
4534
4535#endif  // GTEST_HAS_EXCEPTIONS
4536
4537// Make sure we deal with the precedence of <<.
4538TEST(ExpectTest, ExpectPrecedence) {
4539  EXPECT_EQ(1 < 2, true);
4540  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4541                          "Value of: true && false");
4542}
4543
4544
4545// Tests the StreamableToString() function.
4546
4547// Tests using StreamableToString() on a scalar.
4548TEST(StreamableToStringTest, Scalar) {
4549  EXPECT_STREQ("5", StreamableToString(5).c_str());
4550}
4551
4552// Tests using StreamableToString() on a non-char pointer.
4553TEST(StreamableToStringTest, Pointer) {
4554  int n = 0;
4555  int* p = &n;
4556  EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4557}
4558
4559// Tests using StreamableToString() on a NULL non-char pointer.
4560TEST(StreamableToStringTest, NullPointer) {
4561  int* p = NULL;
4562  EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4563}
4564
4565// Tests using StreamableToString() on a C string.
4566TEST(StreamableToStringTest, CString) {
4567  EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4568}
4569
4570// Tests using StreamableToString() on a NULL C string.
4571TEST(StreamableToStringTest, NullCString) {
4572  char* p = NULL;
4573  EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4574}
4575
4576// Tests using streamable values as assertion messages.
4577
4578// Tests using std::string as an assertion message.
4579TEST(StreamableTest, string) {
4580  static const std::string str(
4581      "This failure message is a std::string, and is expected.");
4582  EXPECT_FATAL_FAILURE(FAIL() << str,
4583                       str.c_str());
4584}
4585
4586// Tests that we can output strings containing embedded NULs.
4587// Limited to Linux because we can only do this with std::string's.
4588TEST(StreamableTest, stringWithEmbeddedNUL) {
4589  static const char char_array_with_nul[] =
4590      "Here's a NUL\0 and some more string";
4591  static const std::string string_with_nul(char_array_with_nul,
4592                                           sizeof(char_array_with_nul)
4593                                           - 1);  // drops the trailing NUL
4594  EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4595                       "Here's a NUL\\0 and some more string");
4596}
4597
4598// Tests that we can output a NUL char.
4599TEST(StreamableTest, NULChar) {
4600  EXPECT_FATAL_FAILURE({  // NOLINT
4601    FAIL() << "A NUL" << '\0' << " and some more string";
4602  }, "A NUL\\0 and some more string");
4603}
4604
4605// Tests using int as an assertion message.
4606TEST(StreamableTest, int) {
4607  EXPECT_FATAL_FAILURE(FAIL() << 900913,
4608                       "900913");
4609}
4610
4611// Tests using NULL char pointer as an assertion message.
4612//
4613// In MSVC, streaming a NULL char * causes access violation.  Google Test
4614// implemented a workaround (substituting "(null)" for NULL).  This
4615// tests whether the workaround works.
4616TEST(StreamableTest, NullCharPtr) {
4617  EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4618                       "(null)");
4619}
4620
4621// Tests that basic IO manipulators (endl, ends, and flush) can be
4622// streamed to testing::Message.
4623TEST(StreamableTest, BasicIoManip) {
4624  EXPECT_FATAL_FAILURE({  // NOLINT
4625    FAIL() << "Line 1." << std::endl
4626           << "A NUL char " << std::ends << std::flush << " in line 2.";
4627  }, "Line 1.\nA NUL char \\0 in line 2.");
4628}
4629
4630// Tests the macros that haven't been covered so far.
4631
4632void AddFailureHelper(bool* aborted) {
4633  *aborted = true;
4634  ADD_FAILURE() << "Intentional failure.";
4635  *aborted = false;
4636}
4637
4638// Tests ADD_FAILURE.
4639TEST(MacroTest, ADD_FAILURE) {
4640  bool aborted = true;
4641  EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4642                          "Intentional failure.");
4643  EXPECT_FALSE(aborted);
4644}
4645
4646// Tests ADD_FAILURE_AT.
4647TEST(MacroTest, ADD_FAILURE_AT) {
4648  // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4649  // the failure message contains the user-streamed part.
4650  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4651
4652  // Verifies that the user-streamed part is optional.
4653  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4654
4655  // Unfortunately, we cannot verify that the failure message contains
4656  // the right file path and line number the same way, as
4657  // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4658  // line number.  Instead, we do that in gtest_output_test_.cc.
4659}
4660
4661// Tests FAIL.
4662TEST(MacroTest, FAIL) {
4663  EXPECT_FATAL_FAILURE(FAIL(),
4664                       "Failed");
4665  EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4666                       "Intentional failure.");
4667}
4668
4669// Tests SUCCEED
4670TEST(MacroTest, SUCCEED) {
4671  SUCCEED();
4672  SUCCEED() << "Explicit success.";
4673}
4674
4675// Tests for EXPECT_EQ() and ASSERT_EQ().
4676//
4677// These tests fail *intentionally*, s.t. the failure messages can be
4678// generated and tested.
4679//
4680// We have different tests for different argument types.
4681
4682// Tests using bool values in {EXPECT|ASSERT}_EQ.
4683TEST(EqAssertionTest, Bool) {
4684  EXPECT_EQ(true,  true);
4685  EXPECT_FATAL_FAILURE({
4686      bool false_value = false;
4687      ASSERT_EQ(false_value, true);
4688    }, "Value of: true");
4689}
4690
4691// Tests using int values in {EXPECT|ASSERT}_EQ.
4692TEST(EqAssertionTest, Int) {
4693  ASSERT_EQ(32, 32);
4694  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4695                          "33");
4696}
4697
4698// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4699TEST(EqAssertionTest, Time_T) {
4700  EXPECT_EQ(static_cast<time_t>(0),
4701            static_cast<time_t>(0));
4702  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4703                                 static_cast<time_t>(1234)),
4704                       "1234");
4705}
4706
4707// Tests using char values in {EXPECT|ASSERT}_EQ.
4708TEST(EqAssertionTest, Char) {
4709  ASSERT_EQ('z', 'z');
4710  const char ch = 'b';
4711  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4712                          "ch");
4713  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4714                          "ch");
4715}
4716
4717// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4718TEST(EqAssertionTest, WideChar) {
4719  EXPECT_EQ(L'b', L'b');
4720
4721  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4722                          "Value of: L'x'\n"
4723                          "  Actual: L'x' (120, 0x78)\n"
4724                          "Expected: L'\0'\n"
4725                          "Which is: L'\0' (0, 0x0)");
4726
4727  static wchar_t wchar;
4728  wchar = L'b';
4729  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4730                          "wchar");
4731  wchar = 0x8119;
4732  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4733                       "Value of: wchar");
4734}
4735
4736// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4737TEST(EqAssertionTest, StdString) {
4738  // Compares a const char* to an std::string that has identical
4739  // content.
4740  ASSERT_EQ("Test", ::std::string("Test"));
4741
4742  // Compares two identical std::strings.
4743  static const ::std::string str1("A * in the middle");
4744  static const ::std::string str2(str1);
4745  EXPECT_EQ(str1, str2);
4746
4747  // Compares a const char* to an std::string that has different
4748  // content
4749  EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4750                          "\"test\"");
4751
4752  // Compares an std::string to a char* that has different content.
4753  char* const p1 = const_cast<char*>("foo");
4754  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4755                          "p1");
4756
4757  // Compares two std::strings that have different contents, one of
4758  // which having a NUL character in the middle.  This should fail.
4759  static ::std::string str3(str1);
4760  str3.at(2) = '\0';
4761  EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4762                       "Value of: str3\n"
4763                       "  Actual: \"A \\0 in the middle\"");
4764}
4765
4766#if GTEST_HAS_STD_WSTRING
4767
4768// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4769TEST(EqAssertionTest, StdWideString) {
4770  // Compares two identical std::wstrings.
4771  const ::std::wstring wstr1(L"A * in the middle");
4772  const ::std::wstring wstr2(wstr1);
4773  ASSERT_EQ(wstr1, wstr2);
4774
4775  // Compares an std::wstring to a const wchar_t* that has identical
4776  // content.
4777  const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4778  EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4779
4780  // Compares an std::wstring to a const wchar_t* that has different
4781  // content.
4782  const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4783  EXPECT_NONFATAL_FAILURE({  // NOLINT
4784    EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4785  }, "kTestX8120");
4786
4787  // Compares two std::wstrings that have different contents, one of
4788  // which having a NUL character in the middle.
4789  ::std::wstring wstr3(wstr1);
4790  wstr3.at(2) = L'\0';
4791  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4792                          "wstr3");
4793
4794  // Compares a wchar_t* to an std::wstring that has different
4795  // content.
4796  EXPECT_FATAL_FAILURE({  // NOLINT
4797    ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4798  }, "");
4799}
4800
4801#endif  // GTEST_HAS_STD_WSTRING
4802
4803#if GTEST_HAS_GLOBAL_STRING
4804// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4805TEST(EqAssertionTest, GlobalString) {
4806  // Compares a const char* to a ::string that has identical content.
4807  EXPECT_EQ("Test", ::string("Test"));
4808
4809  // Compares two identical ::strings.
4810  const ::string str1("A * in the middle");
4811  const ::string str2(str1);
4812  ASSERT_EQ(str1, str2);
4813
4814  // Compares a ::string to a const char* that has different content.
4815  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4816                          "test");
4817
4818  // Compares two ::strings that have different contents, one of which
4819  // having a NUL character in the middle.
4820  ::string str3(str1);
4821  str3.at(2) = '\0';
4822  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4823                          "str3");
4824
4825  // Compares a ::string to a char* that has different content.
4826  EXPECT_FATAL_FAILURE({  // NOLINT
4827    ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4828  }, "");
4829}
4830
4831#endif  // GTEST_HAS_GLOBAL_STRING
4832
4833#if GTEST_HAS_GLOBAL_WSTRING
4834
4835// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4836TEST(EqAssertionTest, GlobalWideString) {
4837  // Compares two identical ::wstrings.
4838  static const ::wstring wstr1(L"A * in the middle");
4839  static const ::wstring wstr2(wstr1);
4840  EXPECT_EQ(wstr1, wstr2);
4841
4842  // Compares a const wchar_t* to a ::wstring that has identical content.
4843  const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4844  ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
4845
4846  // Compares a const wchar_t* to a ::wstring that has different
4847  // content.
4848  const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4849  EXPECT_NONFATAL_FAILURE({  // NOLINT
4850    EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
4851  }, "Test\\x8119");
4852
4853  // Compares a wchar_t* to a ::wstring that has different content.
4854  wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4855  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4856                          "bar");
4857
4858  // Compares two ::wstrings that have different contents, one of which
4859  // having a NUL character in the middle.
4860  static ::wstring wstr3;
4861  wstr3 = wstr1;
4862  wstr3.at(2) = L'\0';
4863  EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4864                       "wstr3");
4865}
4866
4867#endif  // GTEST_HAS_GLOBAL_WSTRING
4868
4869// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4870TEST(EqAssertionTest, CharPointer) {
4871  char* const p0 = NULL;
4872  // Only way to get the Nokia compiler to compile the cast
4873  // is to have a separate void* variable first. Putting
4874  // the two casts on the same line doesn't work, neither does
4875  // a direct C-style to char*.
4876  void* pv1 = (void*)0x1234;  // NOLINT
4877  void* pv2 = (void*)0xABC0;  // NOLINT
4878  char* const p1 = reinterpret_cast<char*>(pv1);
4879  char* const p2 = reinterpret_cast<char*>(pv2);
4880  ASSERT_EQ(p1, p1);
4881
4882  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4883                          "Value of: p2");
4884  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4885                          "p2");
4886  EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4887                                 reinterpret_cast<char*>(0xABC0)),
4888                       "ABC0");
4889}
4890
4891// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4892TEST(EqAssertionTest, WideCharPointer) {
4893  wchar_t* const p0 = NULL;
4894  // Only way to get the Nokia compiler to compile the cast
4895  // is to have a separate void* variable first. Putting
4896  // the two casts on the same line doesn't work, neither does
4897  // a direct C-style to char*.
4898  void* pv1 = (void*)0x1234;  // NOLINT
4899  void* pv2 = (void*)0xABC0;  // NOLINT
4900  wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4901  wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4902  EXPECT_EQ(p0, p0);
4903
4904  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4905                          "Value of: p2");
4906  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4907                          "p2");
4908  void* pv3 = (void*)0x1234;  // NOLINT
4909  void* pv4 = (void*)0xABC0;  // NOLINT
4910  const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4911  const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4912  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4913                          "p4");
4914}
4915
4916// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4917TEST(EqAssertionTest, OtherPointer) {
4918  ASSERT_EQ(static_cast<const int*>(NULL),
4919            static_cast<const int*>(NULL));
4920  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4921                                 reinterpret_cast<const int*>(0x1234)),
4922                       "0x1234");
4923}
4924
4925// A class that supports binary comparison operators but not streaming.
4926class UnprintableChar {
4927 public:
4928  explicit UnprintableChar(char ch) : char_(ch) {}
4929
4930  bool operator==(const UnprintableChar& rhs) const {
4931    return char_ == rhs.char_;
4932  }
4933  bool operator!=(const UnprintableChar& rhs) const {
4934    return char_ != rhs.char_;
4935  }
4936  bool operator<(const UnprintableChar& rhs) const {
4937    return char_ < rhs.char_;
4938  }
4939  bool operator<=(const UnprintableChar& rhs) const {
4940    return char_ <= rhs.char_;
4941  }
4942  bool operator>(const UnprintableChar& rhs) const {
4943    return char_ > rhs.char_;
4944  }
4945  bool operator>=(const UnprintableChar& rhs) const {
4946    return char_ >= rhs.char_;
4947  }
4948
4949 private:
4950  char char_;
4951};
4952
4953// Tests that ASSERT_EQ() and friends don't require the arguments to
4954// be printable.
4955TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4956  const UnprintableChar x('x'), y('y');
4957  ASSERT_EQ(x, x);
4958  EXPECT_NE(x, y);
4959  ASSERT_LT(x, y);
4960  EXPECT_LE(x, y);
4961  ASSERT_GT(y, x);
4962  EXPECT_GE(x, x);
4963
4964  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4965  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4966  EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4967  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4968  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4969
4970  // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4971  // variables, so we have to write UnprintableChar('x') instead of x.
4972#ifndef __BORLANDC__
4973  // ICE's in C++Builder.
4974  EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4975                       "1-byte object <78>");
4976  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4977                       "1-byte object <78>");
4978#endif
4979  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4980                       "1-byte object <79>");
4981  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4982                       "1-byte object <78>");
4983  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4984                       "1-byte object <79>");
4985}
4986
4987// Tests the FRIEND_TEST macro.
4988
4989// This class has a private member we want to test.  We will test it
4990// both in a TEST and in a TEST_F.
4991class Foo {
4992 public:
4993  Foo() {}
4994
4995 private:
4996  int Bar() const { return 1; }
4997
4998  // Declares the friend tests that can access the private member
4999  // Bar().
5000  FRIEND_TEST(FRIEND_TEST_Test, TEST);
5001  FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5002};
5003
5004// Tests that the FRIEND_TEST declaration allows a TEST to access a
5005// class's private members.  This should compile.
5006TEST(FRIEND_TEST_Test, TEST) {
5007  ASSERT_EQ(1, Foo().Bar());
5008}
5009
5010// The fixture needed to test using FRIEND_TEST with TEST_F.
5011class FRIEND_TEST_Test2 : public Test {
5012 protected:
5013  Foo foo;
5014};
5015
5016// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5017// class's private members.  This should compile.
5018TEST_F(FRIEND_TEST_Test2, TEST_F) {
5019  ASSERT_EQ(1, foo.Bar());
5020}
5021
5022// Tests the life cycle of Test objects.
5023
5024// The test fixture for testing the life cycle of Test objects.
5025//
5026// This class counts the number of live test objects that uses this
5027// fixture.
5028class TestLifeCycleTest : public Test {
5029 protected:
5030  // Constructor.  Increments the number of test objects that uses
5031  // this fixture.
5032  TestLifeCycleTest() { count_++; }
5033
5034  // Destructor.  Decrements the number of test objects that uses this
5035  // fixture.
5036  ~TestLifeCycleTest() { count_--; }
5037
5038  // Returns the number of live test objects that uses this fixture.
5039  int count() const { return count_; }
5040
5041 private:
5042  static int count_;
5043};
5044
5045int TestLifeCycleTest::count_ = 0;
5046
5047// Tests the life cycle of test objects.
5048TEST_F(TestLifeCycleTest, Test1) {
5049  // There should be only one test object in this test case that's
5050  // currently alive.
5051  ASSERT_EQ(1, count());
5052}
5053
5054// Tests the life cycle of test objects.
5055TEST_F(TestLifeCycleTest, Test2) {
5056  // After Test1 is done and Test2 is started, there should still be
5057  // only one live test object, as the object for Test1 should've been
5058  // deleted.
5059  ASSERT_EQ(1, count());
5060}
5061
5062}  // namespace
5063
5064// Tests that the copy constructor works when it is NOT optimized away by
5065// the compiler.
5066TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5067  // Checks that the copy constructor doesn't try to dereference NULL pointers
5068  // in the source object.
5069  AssertionResult r1 = AssertionSuccess();
5070  AssertionResult r2 = r1;
5071  // The following line is added to prevent the compiler from optimizing
5072  // away the constructor call.
5073  r1 << "abc";
5074
5075  AssertionResult r3 = r1;
5076  EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5077  EXPECT_STREQ("abc", r1.message());
5078}
5079
5080// Tests that AssertionSuccess and AssertionFailure construct
5081// AssertionResult objects as expected.
5082TEST(AssertionResultTest, ConstructionWorks) {
5083  AssertionResult r1 = AssertionSuccess();
5084  EXPECT_TRUE(r1);
5085  EXPECT_STREQ("", r1.message());
5086
5087  AssertionResult r2 = AssertionSuccess() << "abc";
5088  EXPECT_TRUE(r2);
5089  EXPECT_STREQ("abc", r2.message());
5090
5091  AssertionResult r3 = AssertionFailure();
5092  EXPECT_FALSE(r3);
5093  EXPECT_STREQ("", r3.message());
5094
5095  AssertionResult r4 = AssertionFailure() << "def";
5096  EXPECT_FALSE(r4);
5097  EXPECT_STREQ("def", r4.message());
5098
5099  AssertionResult r5 = AssertionFailure(Message() << "ghi");
5100  EXPECT_FALSE(r5);
5101  EXPECT_STREQ("ghi", r5.message());
5102}
5103
5104// Tests that the negation flips the predicate result but keeps the message.
5105TEST(AssertionResultTest, NegationWorks) {
5106  AssertionResult r1 = AssertionSuccess() << "abc";
5107  EXPECT_FALSE(!r1);
5108  EXPECT_STREQ("abc", (!r1).message());
5109
5110  AssertionResult r2 = AssertionFailure() << "def";
5111  EXPECT_TRUE(!r2);
5112  EXPECT_STREQ("def", (!r2).message());
5113}
5114
5115TEST(AssertionResultTest, StreamingWorks) {
5116  AssertionResult r = AssertionSuccess();
5117  r << "abc" << 'd' << 0 << true;
5118  EXPECT_STREQ("abcd0true", r.message());
5119}
5120
5121TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5122  AssertionResult r = AssertionSuccess();
5123  r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5124  EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5125}
5126
5127// The next test uses explicit conversion operators -- a C++11 feature.
5128#if GTEST_LANG_CXX11
5129
5130TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5131  struct ExplicitlyConvertibleToBool {
5132    explicit operator bool() const { return value; }
5133    bool value;
5134  };
5135  ExplicitlyConvertibleToBool v1 = {false};
5136  ExplicitlyConvertibleToBool v2 = {true};
5137  EXPECT_FALSE(v1);
5138  EXPECT_TRUE(v2);
5139}
5140
5141#endif  // GTEST_LANG_CXX11
5142
5143struct ConvertibleToAssertionResult {
5144  operator AssertionResult() const { return AssertionResult(true); }
5145};
5146
5147TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5148  ConvertibleToAssertionResult obj;
5149  EXPECT_TRUE(obj);
5150}
5151
5152// Tests streaming a user type whose definition and operator << are
5153// both in the global namespace.
5154class Base {
5155 public:
5156  explicit Base(int an_x) : x_(an_x) {}
5157  int x() const { return x_; }
5158 private:
5159  int x_;
5160};
5161std::ostream& operator<<(std::ostream& os,
5162                         const Base& val) {
5163  return os << val.x();
5164}
5165std::ostream& operator<<(std::ostream& os,
5166                         const Base* pointer) {
5167  return os << "(" << pointer->x() << ")";
5168}
5169
5170TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5171  Message msg;
5172  Base a(1);
5173
5174  msg << a << &a;  // Uses ::operator<<.
5175  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5176}
5177
5178// Tests streaming a user type whose definition and operator<< are
5179// both in an unnamed namespace.
5180namespace {
5181class MyTypeInUnnamedNameSpace : public Base {
5182 public:
5183  explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5184};
5185std::ostream& operator<<(std::ostream& os,
5186                         const MyTypeInUnnamedNameSpace& val) {
5187  return os << val.x();
5188}
5189std::ostream& operator<<(std::ostream& os,
5190                         const MyTypeInUnnamedNameSpace* pointer) {
5191  return os << "(" << pointer->x() << ")";
5192}
5193}  // namespace
5194
5195TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5196  Message msg;
5197  MyTypeInUnnamedNameSpace a(1);
5198
5199  msg << a << &a;  // Uses <unnamed_namespace>::operator<<.
5200  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5201}
5202
5203// Tests streaming a user type whose definition and operator<< are
5204// both in a user namespace.
5205namespace namespace1 {
5206class MyTypeInNameSpace1 : public Base {
5207 public:
5208  explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5209};
5210std::ostream& operator<<(std::ostream& os,
5211                         const MyTypeInNameSpace1& val) {
5212  return os << val.x();
5213}
5214std::ostream& operator<<(std::ostream& os,
5215                         const MyTypeInNameSpace1* pointer) {
5216  return os << "(" << pointer->x() << ")";
5217}
5218}  // namespace namespace1
5219
5220TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5221  Message msg;
5222  namespace1::MyTypeInNameSpace1 a(1);
5223
5224  msg << a << &a;  // Uses namespace1::operator<<.
5225  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5226}
5227
5228// Tests streaming a user type whose definition is in a user namespace
5229// but whose operator<< is in the global namespace.
5230namespace namespace2 {
5231class MyTypeInNameSpace2 : public ::Base {
5232 public:
5233  explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5234};
5235}  // namespace namespace2
5236std::ostream& operator<<(std::ostream& os,
5237                         const namespace2::MyTypeInNameSpace2& val) {
5238  return os << val.x();
5239}
5240std::ostream& operator<<(std::ostream& os,
5241                         const namespace2::MyTypeInNameSpace2* pointer) {
5242  return os << "(" << pointer->x() << ")";
5243}
5244
5245TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5246  Message msg;
5247  namespace2::MyTypeInNameSpace2 a(1);
5248
5249  msg << a << &a;  // Uses ::operator<<.
5250  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5251}
5252
5253// Tests streaming NULL pointers to testing::Message.
5254TEST(MessageTest, NullPointers) {
5255  Message msg;
5256  char* const p1 = NULL;
5257  unsigned char* const p2 = NULL;
5258  int* p3 = NULL;
5259  double* p4 = NULL;
5260  bool* p5 = NULL;
5261  Message* p6 = NULL;
5262
5263  msg << p1 << p2 << p3 << p4 << p5 << p6;
5264  ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5265               msg.GetString().c_str());
5266}
5267
5268// Tests streaming wide strings to testing::Message.
5269TEST(MessageTest, WideStrings) {
5270  // Streams a NULL of type const wchar_t*.
5271  const wchar_t* const_wstr = NULL;
5272  EXPECT_STREQ("(null)",
5273               (Message() << const_wstr).GetString().c_str());
5274
5275  // Streams a NULL of type wchar_t*.
5276  wchar_t* wstr = NULL;
5277  EXPECT_STREQ("(null)",
5278               (Message() << wstr).GetString().c_str());
5279
5280  // Streams a non-NULL of type const wchar_t*.
5281  const_wstr = L"abc\x8119";
5282  EXPECT_STREQ("abc\xe8\x84\x99",
5283               (Message() << const_wstr).GetString().c_str());
5284
5285  // Streams a non-NULL of type wchar_t*.
5286  wstr = const_cast<wchar_t*>(const_wstr);
5287  EXPECT_STREQ("abc\xe8\x84\x99",
5288               (Message() << wstr).GetString().c_str());
5289}
5290
5291
5292// This line tests that we can define tests in the testing namespace.
5293namespace testing {
5294
5295// Tests the TestInfo class.
5296
5297class TestInfoTest : public Test {
5298 protected:
5299  static const TestInfo* GetTestInfo(const char* test_name) {
5300    const TestCase* const test_case = GetUnitTestImpl()->
5301        GetTestCase("TestInfoTest", "", NULL, NULL);
5302
5303    for (int i = 0; i < test_case->total_test_count(); ++i) {
5304      const TestInfo* const test_info = test_case->GetTestInfo(i);
5305      if (strcmp(test_name, test_info->name()) == 0)
5306        return test_info;
5307    }
5308    return NULL;
5309  }
5310
5311  static const TestResult* GetTestResult(
5312      const TestInfo* test_info) {
5313    return test_info->result();
5314  }
5315};
5316
5317// Tests TestInfo::test_case_name() and TestInfo::name().
5318TEST_F(TestInfoTest, Names) {
5319  const TestInfo* const test_info = GetTestInfo("Names");
5320
5321  ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5322  ASSERT_STREQ("Names", test_info->name());
5323}
5324
5325// Tests TestInfo::result().
5326TEST_F(TestInfoTest, result) {
5327  const TestInfo* const test_info = GetTestInfo("result");
5328
5329  // Initially, there is no TestPartResult for this test.
5330  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5331
5332  // After the previous assertion, there is still none.
5333  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5334}
5335
5336#define VERIFY_CODE_LOCATION \
5337  const int expected_line = __LINE__ - 1; \
5338  const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5339  ASSERT_TRUE(test_info); \
5340  EXPECT_STREQ(__FILE__, test_info->file()); \
5341  EXPECT_EQ(expected_line, test_info->line())
5342
5343TEST(CodeLocationForTEST, Verify) {
5344  VERIFY_CODE_LOCATION;
5345}
5346
5347class CodeLocationForTESTF : public Test {
5348};
5349
5350TEST_F(CodeLocationForTESTF, Verify) {
5351  VERIFY_CODE_LOCATION;
5352}
5353
5354class CodeLocationForTESTP : public TestWithParam<int> {
5355};
5356
5357TEST_P(CodeLocationForTESTP, Verify) {
5358  VERIFY_CODE_LOCATION;
5359}
5360
5361INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0));
5362
5363template <typename T>
5364class CodeLocationForTYPEDTEST : public Test {
5365};
5366
5367TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int);
5368
5369TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5370  VERIFY_CODE_LOCATION;
5371}
5372
5373template <typename T>
5374class CodeLocationForTYPEDTESTP : public Test {
5375};
5376
5377TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP);
5378
5379TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5380  VERIFY_CODE_LOCATION;
5381}
5382
5383REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify);
5384
5385INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int);
5386
5387#undef VERIFY_CODE_LOCATION
5388
5389// Tests setting up and tearing down a test case.
5390
5391class SetUpTestCaseTest : public Test {
5392 protected:
5393  // This will be called once before the first test in this test case
5394  // is run.
5395  static void SetUpTestCase() {
5396    printf("Setting up the test case . . .\n");
5397
5398    // Initializes some shared resource.  In this simple example, we
5399    // just create a C string.  More complex stuff can be done if
5400    // desired.
5401    shared_resource_ = "123";
5402
5403    // Increments the number of test cases that have been set up.
5404    counter_++;
5405
5406    // SetUpTestCase() should be called only once.
5407    EXPECT_EQ(1, counter_);
5408  }
5409
5410  // This will be called once after the last test in this test case is
5411  // run.
5412  static void TearDownTestCase() {
5413    printf("Tearing down the test case . . .\n");
5414
5415    // Decrements the number of test cases that have been set up.
5416    counter_--;
5417
5418    // TearDownTestCase() should be called only once.
5419    EXPECT_EQ(0, counter_);
5420
5421    // Cleans up the shared resource.
5422    shared_resource_ = NULL;
5423  }
5424
5425  // This will be called before each test in this test case.
5426  virtual void SetUp() {
5427    // SetUpTestCase() should be called only once, so counter_ should
5428    // always be 1.
5429    EXPECT_EQ(1, counter_);
5430  }
5431
5432  // Number of test cases that have been set up.
5433  static int counter_;
5434
5435  // Some resource to be shared by all tests in this test case.
5436  static const char* shared_resource_;
5437};
5438
5439int SetUpTestCaseTest::counter_ = 0;
5440const char* SetUpTestCaseTest::shared_resource_ = NULL;
5441
5442// A test that uses the shared resource.
5443TEST_F(SetUpTestCaseTest, Test1) {
5444  EXPECT_STRNE(NULL, shared_resource_);
5445}
5446
5447// Another test that uses the shared resource.
5448TEST_F(SetUpTestCaseTest, Test2) {
5449  EXPECT_STREQ("123", shared_resource_);
5450}
5451
5452// The InitGoogleTestTest test case tests testing::InitGoogleTest().
5453
5454// The Flags struct stores a copy of all Google Test flags.
5455struct Flags {
5456  // Constructs a Flags struct where each flag has its default value.
5457  Flags() : also_run_disabled_tests(false),
5458            break_on_failure(false),
5459            catch_exceptions(false),
5460            death_test_use_fork(false),
5461            filter(""),
5462            list_tests(false),
5463            output(""),
5464            print_time(true),
5465            random_seed(0),
5466            repeat(1),
5467            shuffle(false),
5468            stack_trace_depth(kMaxStackTraceDepth),
5469            stream_result_to(""),
5470            throw_on_failure(false) {}
5471
5472  // Factory methods.
5473
5474  // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5475  // the given value.
5476  static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5477    Flags flags;
5478    flags.also_run_disabled_tests = also_run_disabled_tests;
5479    return flags;
5480  }
5481
5482  // Creates a Flags struct where the gtest_break_on_failure flag has
5483  // the given value.
5484  static Flags BreakOnFailure(bool break_on_failure) {
5485    Flags flags;
5486    flags.break_on_failure = break_on_failure;
5487    return flags;
5488  }
5489
5490  // Creates a Flags struct where the gtest_catch_exceptions flag has
5491  // the given value.
5492  static Flags CatchExceptions(bool catch_exceptions) {
5493    Flags flags;
5494    flags.catch_exceptions = catch_exceptions;
5495    return flags;
5496  }
5497
5498  // Creates a Flags struct where the gtest_death_test_use_fork flag has
5499  // the given value.
5500  static Flags DeathTestUseFork(bool death_test_use_fork) {
5501    Flags flags;
5502    flags.death_test_use_fork = death_test_use_fork;
5503    return flags;
5504  }
5505
5506  // Creates a Flags struct where the gtest_filter flag has the given
5507  // value.
5508  static Flags Filter(const char* filter) {
5509    Flags flags;
5510    flags.filter = filter;
5511    return flags;
5512  }
5513
5514  // Creates a Flags struct where the gtest_list_tests flag has the
5515  // given value.
5516  static Flags ListTests(bool list_tests) {
5517    Flags flags;
5518    flags.list_tests = list_tests;
5519    return flags;
5520  }
5521
5522  // Creates a Flags struct where the gtest_output flag has the given
5523  // value.
5524  static Flags Output(const char* output) {
5525    Flags flags;
5526    flags.output = output;
5527    return flags;
5528  }
5529
5530  // Creates a Flags struct where the gtest_print_time flag has the given
5531  // value.
5532  static Flags PrintTime(bool print_time) {
5533    Flags flags;
5534    flags.print_time = print_time;
5535    return flags;
5536  }
5537
5538  // Creates a Flags struct where the gtest_random_seed flag has
5539  // the given value.
5540  static Flags RandomSeed(Int32 random_seed) {
5541    Flags flags;
5542    flags.random_seed = random_seed;
5543    return flags;
5544  }
5545
5546  // Creates a Flags struct where the gtest_repeat flag has the given
5547  // value.
5548  static Flags Repeat(Int32 repeat) {
5549    Flags flags;
5550    flags.repeat = repeat;
5551    return flags;
5552  }
5553
5554  // Creates a Flags struct where the gtest_shuffle flag has
5555  // the given value.
5556  static Flags Shuffle(bool shuffle) {
5557    Flags flags;
5558    flags.shuffle = shuffle;
5559    return flags;
5560  }
5561
5562  // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5563  // the given value.
5564  static Flags StackTraceDepth(Int32 stack_trace_depth) {
5565    Flags flags;
5566    flags.stack_trace_depth = stack_trace_depth;
5567    return flags;
5568  }
5569
5570  // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5571  // the given value.
5572  static Flags StreamResultTo(const char* stream_result_to) {
5573    Flags flags;
5574    flags.stream_result_to = stream_result_to;
5575    return flags;
5576  }
5577
5578  // Creates a Flags struct where the gtest_throw_on_failure flag has
5579  // the given value.
5580  static Flags ThrowOnFailure(bool throw_on_failure) {
5581    Flags flags;
5582    flags.throw_on_failure = throw_on_failure;
5583    return flags;
5584  }
5585
5586  // These fields store the flag values.
5587  bool also_run_disabled_tests;
5588  bool break_on_failure;
5589  bool catch_exceptions;
5590  bool death_test_use_fork;
5591  const char* filter;
5592  bool list_tests;
5593  const char* output;
5594  bool print_time;
5595  Int32 random_seed;
5596  Int32 repeat;
5597  bool shuffle;
5598  Int32 stack_trace_depth;
5599  const char* stream_result_to;
5600  bool throw_on_failure;
5601};
5602
5603// Fixture for testing InitGoogleTest().
5604class InitGoogleTestTest : public Test {
5605 protected:
5606  // Clears the flags before each test.
5607  virtual void SetUp() {
5608    GTEST_FLAG(also_run_disabled_tests) = false;
5609    GTEST_FLAG(break_on_failure) = false;
5610    GTEST_FLAG(catch_exceptions) = false;
5611    GTEST_FLAG(death_test_use_fork) = false;
5612    GTEST_FLAG(filter) = "";
5613    GTEST_FLAG(list_tests) = false;
5614    GTEST_FLAG(output) = "";
5615    GTEST_FLAG(print_time) = true;
5616    GTEST_FLAG(random_seed) = 0;
5617    GTEST_FLAG(repeat) = 1;
5618    GTEST_FLAG(shuffle) = false;
5619    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5620    GTEST_FLAG(stream_result_to) = "";
5621    GTEST_FLAG(throw_on_failure) = false;
5622  }
5623
5624  // Asserts that two narrow or wide string arrays are equal.
5625  template <typename CharType>
5626  static void AssertStringArrayEq(size_t size1, CharType** array1,
5627                                  size_t size2, CharType** array2) {
5628    ASSERT_EQ(size1, size2) << " Array sizes different.";
5629
5630    for (size_t i = 0; i != size1; i++) {
5631      ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5632    }
5633  }
5634
5635  // Verifies that the flag values match the expected values.
5636  static void CheckFlags(const Flags& expected) {
5637    EXPECT_EQ(expected.also_run_disabled_tests,
5638              GTEST_FLAG(also_run_disabled_tests));
5639    EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5640    EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5641    EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5642    EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5643    EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5644    EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5645    EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5646    EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5647    EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5648    EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5649    EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5650    EXPECT_STREQ(expected.stream_result_to,
5651                 GTEST_FLAG(stream_result_to).c_str());
5652    EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5653  }
5654
5655  // Parses a command line (specified by argc1 and argv1), then
5656  // verifies that the flag values are expected and that the
5657  // recognized flags are removed from the command line.
5658  template <typename CharType>
5659  static void TestParsingFlags(int argc1, const CharType** argv1,
5660                               int argc2, const CharType** argv2,
5661                               const Flags& expected, bool should_print_help) {
5662    const bool saved_help_flag = ::testing::internal::g_help_flag;
5663    ::testing::internal::g_help_flag = false;
5664
5665#if GTEST_HAS_STREAM_REDIRECTION
5666    CaptureStdout();
5667#endif
5668
5669    // Parses the command line.
5670    internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5671
5672#if GTEST_HAS_STREAM_REDIRECTION
5673    const std::string captured_stdout = GetCapturedStdout();
5674#endif
5675
5676    // Verifies the flag values.
5677    CheckFlags(expected);
5678
5679    // Verifies that the recognized flags are removed from the command
5680    // line.
5681    AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5682
5683    // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5684    // help message for the flags it recognizes.
5685    EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5686
5687#if GTEST_HAS_STREAM_REDIRECTION
5688    const char* const expected_help_fragment =
5689        "This program contains tests written using";
5690    if (should_print_help) {
5691      EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5692    } else {
5693      EXPECT_PRED_FORMAT2(IsNotSubstring,
5694                          expected_help_fragment, captured_stdout);
5695    }
5696#endif  // GTEST_HAS_STREAM_REDIRECTION
5697
5698    ::testing::internal::g_help_flag = saved_help_flag;
5699  }
5700
5701  // This macro wraps TestParsingFlags s.t. the user doesn't need
5702  // to specify the array sizes.
5703
5704#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5705  TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5706                   sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5707                   expected, should_print_help)
5708};
5709
5710// Tests parsing an empty command line.
5711TEST_F(InitGoogleTestTest, Empty) {
5712  const char* argv[] = {
5713    NULL
5714  };
5715
5716  const char* argv2[] = {
5717    NULL
5718  };
5719
5720  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5721}
5722
5723// Tests parsing a command line that has no flag.
5724TEST_F(InitGoogleTestTest, NoFlag) {
5725  const char* argv[] = {
5726    "foo.exe",
5727    NULL
5728  };
5729
5730  const char* argv2[] = {
5731    "foo.exe",
5732    NULL
5733  };
5734
5735  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5736}
5737
5738// Tests parsing a bad --gtest_filter flag.
5739TEST_F(InitGoogleTestTest, FilterBad) {
5740  const char* argv[] = {
5741    "foo.exe",
5742    "--gtest_filter",
5743    NULL
5744  };
5745
5746  const char* argv2[] = {
5747    "foo.exe",
5748    "--gtest_filter",
5749    NULL
5750  };
5751
5752  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5753}
5754
5755// Tests parsing an empty --gtest_filter flag.
5756TEST_F(InitGoogleTestTest, FilterEmpty) {
5757  const char* argv[] = {
5758    "foo.exe",
5759    "--gtest_filter=",
5760    NULL
5761  };
5762
5763  const char* argv2[] = {
5764    "foo.exe",
5765    NULL
5766  };
5767
5768  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5769}
5770
5771// Tests parsing a non-empty --gtest_filter flag.
5772TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5773  const char* argv[] = {
5774    "foo.exe",
5775    "--gtest_filter=abc",
5776    NULL
5777  };
5778
5779  const char* argv2[] = {
5780    "foo.exe",
5781    NULL
5782  };
5783
5784  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5785}
5786
5787// Tests parsing --gtest_break_on_failure.
5788TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
5789  const char* argv[] = {
5790    "foo.exe",
5791    "--gtest_break_on_failure",
5792    NULL
5793};
5794
5795  const char* argv2[] = {
5796    "foo.exe",
5797    NULL
5798  };
5799
5800  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5801}
5802
5803// Tests parsing --gtest_break_on_failure=0.
5804TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5805  const char* argv[] = {
5806    "foo.exe",
5807    "--gtest_break_on_failure=0",
5808    NULL
5809  };
5810
5811  const char* argv2[] = {
5812    "foo.exe",
5813    NULL
5814  };
5815
5816  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5817}
5818
5819// Tests parsing --gtest_break_on_failure=f.
5820TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5821  const char* argv[] = {
5822    "foo.exe",
5823    "--gtest_break_on_failure=f",
5824    NULL
5825  };
5826
5827  const char* argv2[] = {
5828    "foo.exe",
5829    NULL
5830  };
5831
5832  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5833}
5834
5835// Tests parsing --gtest_break_on_failure=F.
5836TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5837  const char* argv[] = {
5838    "foo.exe",
5839    "--gtest_break_on_failure=F",
5840    NULL
5841  };
5842
5843  const char* argv2[] = {
5844    "foo.exe",
5845    NULL
5846  };
5847
5848  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5849}
5850
5851// Tests parsing a --gtest_break_on_failure flag that has a "true"
5852// definition.
5853TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5854  const char* argv[] = {
5855    "foo.exe",
5856    "--gtest_break_on_failure=1",
5857    NULL
5858  };
5859
5860  const char* argv2[] = {
5861    "foo.exe",
5862    NULL
5863  };
5864
5865  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5866}
5867
5868// Tests parsing --gtest_catch_exceptions.
5869TEST_F(InitGoogleTestTest, CatchExceptions) {
5870  const char* argv[] = {
5871    "foo.exe",
5872    "--gtest_catch_exceptions",
5873    NULL
5874  };
5875
5876  const char* argv2[] = {
5877    "foo.exe",
5878    NULL
5879  };
5880
5881  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5882}
5883
5884// Tests parsing --gtest_death_test_use_fork.
5885TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5886  const char* argv[] = {
5887    "foo.exe",
5888    "--gtest_death_test_use_fork",
5889    NULL
5890  };
5891
5892  const char* argv2[] = {
5893    "foo.exe",
5894    NULL
5895  };
5896
5897  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5898}
5899
5900// Tests having the same flag twice with different values.  The
5901// expected behavior is that the one coming last takes precedence.
5902TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5903  const char* argv[] = {
5904    "foo.exe",
5905    "--gtest_filter=a",
5906    "--gtest_filter=b",
5907    NULL
5908  };
5909
5910  const char* argv2[] = {
5911    "foo.exe",
5912    NULL
5913  };
5914
5915  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5916}
5917
5918// Tests having an unrecognized flag on the command line.
5919TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5920  const char* argv[] = {
5921    "foo.exe",
5922    "--gtest_break_on_failure",
5923    "bar",  // Unrecognized by Google Test.
5924    "--gtest_filter=b",
5925    NULL
5926  };
5927
5928  const char* argv2[] = {
5929    "foo.exe",
5930    "bar",
5931    NULL
5932  };
5933
5934  Flags flags;
5935  flags.break_on_failure = true;
5936  flags.filter = "b";
5937  GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5938}
5939
5940// Tests having a --gtest_list_tests flag
5941TEST_F(InitGoogleTestTest, ListTestsFlag) {
5942    const char* argv[] = {
5943      "foo.exe",
5944      "--gtest_list_tests",
5945      NULL
5946    };
5947
5948    const char* argv2[] = {
5949      "foo.exe",
5950      NULL
5951    };
5952
5953    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5954}
5955
5956// Tests having a --gtest_list_tests flag with a "true" value
5957TEST_F(InitGoogleTestTest, ListTestsTrue) {
5958    const char* argv[] = {
5959      "foo.exe",
5960      "--gtest_list_tests=1",
5961      NULL
5962    };
5963
5964    const char* argv2[] = {
5965      "foo.exe",
5966      NULL
5967    };
5968
5969    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5970}
5971
5972// Tests having a --gtest_list_tests flag with a "false" value
5973TEST_F(InitGoogleTestTest, ListTestsFalse) {
5974    const char* argv[] = {
5975      "foo.exe",
5976      "--gtest_list_tests=0",
5977      NULL
5978    };
5979
5980    const char* argv2[] = {
5981      "foo.exe",
5982      NULL
5983    };
5984
5985    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5986}
5987
5988// Tests parsing --gtest_list_tests=f.
5989TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5990  const char* argv[] = {
5991    "foo.exe",
5992    "--gtest_list_tests=f",
5993    NULL
5994  };
5995
5996  const char* argv2[] = {
5997    "foo.exe",
5998    NULL
5999  };
6000
6001  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6002}
6003
6004// Tests parsing --gtest_list_tests=F.
6005TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
6006  const char* argv[] = {
6007    "foo.exe",
6008    "--gtest_list_tests=F",
6009    NULL
6010  };
6011
6012  const char* argv2[] = {
6013    "foo.exe",
6014    NULL
6015  };
6016
6017  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6018}
6019
6020// Tests parsing --gtest_output (invalid).
6021TEST_F(InitGoogleTestTest, OutputEmpty) {
6022  const char* argv[] = {
6023    "foo.exe",
6024    "--gtest_output",
6025    NULL
6026  };
6027
6028  const char* argv2[] = {
6029    "foo.exe",
6030    "--gtest_output",
6031    NULL
6032  };
6033
6034  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6035}
6036
6037// Tests parsing --gtest_output=xml
6038TEST_F(InitGoogleTestTest, OutputXml) {
6039  const char* argv[] = {
6040    "foo.exe",
6041    "--gtest_output=xml",
6042    NULL
6043  };
6044
6045  const char* argv2[] = {
6046    "foo.exe",
6047    NULL
6048  };
6049
6050  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6051}
6052
6053// Tests parsing --gtest_output=xml:file
6054TEST_F(InitGoogleTestTest, OutputXmlFile) {
6055  const char* argv[] = {
6056    "foo.exe",
6057    "--gtest_output=xml:file",
6058    NULL
6059  };
6060
6061  const char* argv2[] = {
6062    "foo.exe",
6063    NULL
6064  };
6065
6066  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6067}
6068
6069// Tests parsing --gtest_output=xml:directory/path/
6070TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
6071  const char* argv[] = {
6072    "foo.exe",
6073    "--gtest_output=xml:directory/path/",
6074    NULL
6075  };
6076
6077  const char* argv2[] = {
6078    "foo.exe",
6079    NULL
6080  };
6081
6082  GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6083                            Flags::Output("xml:directory/path/"), false);
6084}
6085
6086// Tests having a --gtest_print_time flag
6087TEST_F(InitGoogleTestTest, PrintTimeFlag) {
6088    const char* argv[] = {
6089      "foo.exe",
6090      "--gtest_print_time",
6091      NULL
6092    };
6093
6094    const char* argv2[] = {
6095      "foo.exe",
6096      NULL
6097    };
6098
6099    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6100}
6101
6102// Tests having a --gtest_print_time flag with a "true" value
6103TEST_F(InitGoogleTestTest, PrintTimeTrue) {
6104    const char* argv[] = {
6105      "foo.exe",
6106      "--gtest_print_time=1",
6107      NULL
6108    };
6109
6110    const char* argv2[] = {
6111      "foo.exe",
6112      NULL
6113    };
6114
6115    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6116}
6117
6118// Tests having a --gtest_print_time flag with a "false" value
6119TEST_F(InitGoogleTestTest, PrintTimeFalse) {
6120    const char* argv[] = {
6121      "foo.exe",
6122      "--gtest_print_time=0",
6123      NULL
6124    };
6125
6126    const char* argv2[] = {
6127      "foo.exe",
6128      NULL
6129    };
6130
6131    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6132}
6133
6134// Tests parsing --gtest_print_time=f.
6135TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
6136  const char* argv[] = {
6137    "foo.exe",
6138    "--gtest_print_time=f",
6139    NULL
6140  };
6141
6142  const char* argv2[] = {
6143    "foo.exe",
6144    NULL
6145  };
6146
6147  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6148}
6149
6150// Tests parsing --gtest_print_time=F.
6151TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
6152  const char* argv[] = {
6153    "foo.exe",
6154    "--gtest_print_time=F",
6155    NULL
6156  };
6157
6158  const char* argv2[] = {
6159    "foo.exe",
6160    NULL
6161  };
6162
6163  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6164}
6165
6166// Tests parsing --gtest_random_seed=number
6167TEST_F(InitGoogleTestTest, RandomSeed) {
6168  const char* argv[] = {
6169    "foo.exe",
6170    "--gtest_random_seed=1000",
6171    NULL
6172  };
6173
6174  const char* argv2[] = {
6175    "foo.exe",
6176    NULL
6177  };
6178
6179  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6180}
6181
6182// Tests parsing --gtest_repeat=number
6183TEST_F(InitGoogleTestTest, Repeat) {
6184  const char* argv[] = {
6185    "foo.exe",
6186    "--gtest_repeat=1000",
6187    NULL
6188  };
6189
6190  const char* argv2[] = {
6191    "foo.exe",
6192    NULL
6193  };
6194
6195  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6196}
6197
6198// Tests having a --gtest_also_run_disabled_tests flag
6199TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
6200    const char* argv[] = {
6201      "foo.exe",
6202      "--gtest_also_run_disabled_tests",
6203      NULL
6204    };
6205
6206    const char* argv2[] = {
6207      "foo.exe",
6208      NULL
6209    };
6210
6211    GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6212                              Flags::AlsoRunDisabledTests(true), false);
6213}
6214
6215// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6216TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
6217    const char* argv[] = {
6218      "foo.exe",
6219      "--gtest_also_run_disabled_tests=1",
6220      NULL
6221    };
6222
6223    const char* argv2[] = {
6224      "foo.exe",
6225      NULL
6226    };
6227
6228    GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6229                              Flags::AlsoRunDisabledTests(true), false);
6230}
6231
6232// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6233TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
6234    const char* argv[] = {
6235      "foo.exe",
6236      "--gtest_also_run_disabled_tests=0",
6237      NULL
6238    };
6239
6240    const char* argv2[] = {
6241      "foo.exe",
6242      NULL
6243    };
6244
6245    GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6246                              Flags::AlsoRunDisabledTests(false), false);
6247}
6248
6249// Tests parsing --gtest_shuffle.
6250TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
6251  const char* argv[] = {
6252    "foo.exe",
6253    "--gtest_shuffle",
6254    NULL
6255};
6256
6257  const char* argv2[] = {
6258    "foo.exe",
6259    NULL
6260  };
6261
6262  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6263}
6264
6265// Tests parsing --gtest_shuffle=0.
6266TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
6267  const char* argv[] = {
6268    "foo.exe",
6269    "--gtest_shuffle=0",
6270    NULL
6271  };
6272
6273  const char* argv2[] = {
6274    "foo.exe",
6275    NULL
6276  };
6277
6278  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6279}
6280
6281// Tests parsing a --gtest_shuffle flag that has a "true"
6282// definition.
6283TEST_F(InitGoogleTestTest, ShuffleTrue) {
6284  const char* argv[] = {
6285    "foo.exe",
6286    "--gtest_shuffle=1",
6287    NULL
6288  };
6289
6290  const char* argv2[] = {
6291    "foo.exe",
6292    NULL
6293  };
6294
6295  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6296}
6297
6298// Tests parsing --gtest_stack_trace_depth=number.
6299TEST_F(InitGoogleTestTest, StackTraceDepth) {
6300  const char* argv[] = {
6301    "foo.exe",
6302    "--gtest_stack_trace_depth=5",
6303    NULL
6304  };
6305
6306  const char* argv2[] = {
6307    "foo.exe",
6308    NULL
6309  };
6310
6311  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6312}
6313
6314TEST_F(InitGoogleTestTest, StreamResultTo) {
6315  const char* argv[] = {
6316    "foo.exe",
6317    "--gtest_stream_result_to=localhost:1234",
6318    NULL
6319  };
6320
6321  const char* argv2[] = {
6322    "foo.exe",
6323    NULL
6324  };
6325
6326  GTEST_TEST_PARSING_FLAGS_(
6327      argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6328}
6329
6330// Tests parsing --gtest_throw_on_failure.
6331TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
6332  const char* argv[] = {
6333    "foo.exe",
6334    "--gtest_throw_on_failure",
6335    NULL
6336};
6337
6338  const char* argv2[] = {
6339    "foo.exe",
6340    NULL
6341  };
6342
6343  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6344}
6345
6346// Tests parsing --gtest_throw_on_failure=0.
6347TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
6348  const char* argv[] = {
6349    "foo.exe",
6350    "--gtest_throw_on_failure=0",
6351    NULL
6352  };
6353
6354  const char* argv2[] = {
6355    "foo.exe",
6356    NULL
6357  };
6358
6359  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6360}
6361
6362// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6363// definition.
6364TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
6365  const char* argv[] = {
6366    "foo.exe",
6367    "--gtest_throw_on_failure=1",
6368    NULL
6369  };
6370
6371  const char* argv2[] = {
6372    "foo.exe",
6373    NULL
6374  };
6375
6376  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6377}
6378
6379#if GTEST_OS_WINDOWS
6380// Tests parsing wide strings.
6381TEST_F(InitGoogleTestTest, WideStrings) {
6382  const wchar_t* argv[] = {
6383    L"foo.exe",
6384    L"--gtest_filter=Foo*",
6385    L"--gtest_list_tests=1",
6386    L"--gtest_break_on_failure",
6387    L"--non_gtest_flag",
6388    NULL
6389  };
6390
6391  const wchar_t* argv2[] = {
6392    L"foo.exe",
6393    L"--non_gtest_flag",
6394    NULL
6395  };
6396
6397  Flags expected_flags;
6398  expected_flags.break_on_failure = true;
6399  expected_flags.filter = "Foo*";
6400  expected_flags.list_tests = true;
6401
6402  GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6403}
6404# endif  // GTEST_OS_WINDOWS
6405
6406#if GTEST_USE_OWN_FLAGFILE_FLAG_
6407class FlagfileTest : public InitGoogleTestTest {
6408 public:
6409  virtual void SetUp() {
6410    InitGoogleTestTest::SetUp();
6411
6412    testdata_path_.Set(internal::FilePath(
6413        internal::TempDir() + internal::GetCurrentExecutableName().string() +
6414        "_flagfile_test"));
6415    testing::internal::posix::RmDir(testdata_path_.c_str());
6416    EXPECT_TRUE(testdata_path_.CreateFolder());
6417  }
6418
6419  virtual void TearDown() {
6420    testing::internal::posix::RmDir(testdata_path_.c_str());
6421    InitGoogleTestTest::TearDown();
6422  }
6423
6424  internal::FilePath CreateFlagfile(const char* contents) {
6425    internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6426        testdata_path_, internal::FilePath("unique"), "txt"));
6427    FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6428    fprintf(f, "%s", contents);
6429    fclose(f);
6430    return file_path;
6431  }
6432
6433 private:
6434  internal::FilePath testdata_path_;
6435};
6436
6437// Tests an empty flagfile.
6438TEST_F(FlagfileTest, Empty) {
6439  internal::FilePath flagfile_path(CreateFlagfile(""));
6440  std::string flagfile_flag =
6441      std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6442
6443  const char* argv[] = {
6444    "foo.exe",
6445    flagfile_flag.c_str(),
6446    NULL
6447  };
6448
6449  const char* argv2[] = {
6450    "foo.exe",
6451    NULL
6452  };
6453
6454  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6455}
6456
6457// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6458TEST_F(FlagfileTest, FilterNonEmpty) {
6459  internal::FilePath flagfile_path(CreateFlagfile(
6460      "--"  GTEST_FLAG_PREFIX_  "filter=abc"));
6461  std::string flagfile_flag =
6462      std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6463
6464  const char* argv[] = {
6465    "foo.exe",
6466    flagfile_flag.c_str(),
6467    NULL
6468  };
6469
6470  const char* argv2[] = {
6471    "foo.exe",
6472    NULL
6473  };
6474
6475  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6476}
6477
6478// Tests passing several flags via --gtest_flagfile.
6479TEST_F(FlagfileTest, SeveralFlags) {
6480  internal::FilePath flagfile_path(CreateFlagfile(
6481      "--"  GTEST_FLAG_PREFIX_  "filter=abc\n"
6482      "--"  GTEST_FLAG_PREFIX_  "break_on_failure\n"
6483      "--"  GTEST_FLAG_PREFIX_  "list_tests"));
6484  std::string flagfile_flag =
6485      std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6486
6487  const char* argv[] = {
6488    "foo.exe",
6489    flagfile_flag.c_str(),
6490    NULL
6491  };
6492
6493  const char* argv2[] = {
6494    "foo.exe",
6495    NULL
6496  };
6497
6498  Flags expected_flags;
6499  expected_flags.break_on_failure = true;
6500  expected_flags.filter = "abc";
6501  expected_flags.list_tests = true;
6502
6503  GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6504}
6505#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
6506
6507// Tests current_test_info() in UnitTest.
6508class CurrentTestInfoTest : public Test {
6509 protected:
6510  // Tests that current_test_info() returns NULL before the first test in
6511  // the test case is run.
6512  static void SetUpTestCase() {
6513    // There should be no tests running at this point.
6514    const TestInfo* test_info =
6515      UnitTest::GetInstance()->current_test_info();
6516    EXPECT_TRUE(test_info == NULL)
6517        << "There should be no tests running at this point.";
6518  }
6519
6520  // Tests that current_test_info() returns NULL after the last test in
6521  // the test case has run.
6522  static void TearDownTestCase() {
6523    const TestInfo* test_info =
6524      UnitTest::GetInstance()->current_test_info();
6525    EXPECT_TRUE(test_info == NULL)
6526        << "There should be no tests running at this point.";
6527  }
6528};
6529
6530// Tests that current_test_info() returns TestInfo for currently running
6531// test by checking the expected test name against the actual one.
6532TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6533  const TestInfo* test_info =
6534    UnitTest::GetInstance()->current_test_info();
6535  ASSERT_TRUE(NULL != test_info)
6536      << "There is a test running so we should have a valid TestInfo.";
6537  EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6538      << "Expected the name of the currently running test case.";
6539  EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6540      << "Expected the name of the currently running test.";
6541}
6542
6543// Tests that current_test_info() returns TestInfo for currently running
6544// test by checking the expected test name against the actual one.  We
6545// use this test to see that the TestInfo object actually changed from
6546// the previous invocation.
6547TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6548  const TestInfo* test_info =
6549    UnitTest::GetInstance()->current_test_info();
6550  ASSERT_TRUE(NULL != test_info)
6551      << "There is a test running so we should have a valid TestInfo.";
6552  EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6553      << "Expected the name of the currently running test case.";
6554  EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6555      << "Expected the name of the currently running test.";
6556}
6557
6558}  // namespace testing
6559
6560// These two lines test that we can define tests in a namespace that
6561// has the name "testing" and is nested in another namespace.
6562namespace my_namespace {
6563namespace testing {
6564
6565// Makes sure that TEST knows to use ::testing::Test instead of
6566// ::my_namespace::testing::Test.
6567class Test {};
6568
6569// Makes sure that an assertion knows to use ::testing::Message instead of
6570// ::my_namespace::testing::Message.
6571class Message {};
6572
6573// Makes sure that an assertion knows to use
6574// ::testing::AssertionResult instead of
6575// ::my_namespace::testing::AssertionResult.
6576class AssertionResult {};
6577
6578// Tests that an assertion that should succeed works as expected.
6579TEST(NestedTestingNamespaceTest, Success) {
6580  EXPECT_EQ(1, 1) << "This shouldn't fail.";
6581}
6582
6583// Tests that an assertion that should fail works as expected.
6584TEST(NestedTestingNamespaceTest, Failure) {
6585  EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6586                       "This failure is expected.");
6587}
6588
6589}  // namespace testing
6590}  // namespace my_namespace
6591
6592// Tests that one can call superclass SetUp and TearDown methods--
6593// that is, that they are not private.
6594// No tests are based on this fixture; the test "passes" if it compiles
6595// successfully.
6596class ProtectedFixtureMethodsTest : public Test {
6597 protected:
6598  virtual void SetUp() {
6599    Test::SetUp();
6600  }
6601  virtual void TearDown() {
6602    Test::TearDown();
6603  }
6604};
6605
6606// StreamingAssertionsTest tests the streaming versions of a representative
6607// sample of assertions.
6608TEST(StreamingAssertionsTest, Unconditional) {
6609  SUCCEED() << "expected success";
6610  EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6611                          "expected failure");
6612  EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6613                       "expected failure");
6614}
6615
6616#ifdef __BORLANDC__
6617// Silences warnings: "Condition is always true", "Unreachable code"
6618# pragma option push -w-ccc -w-rch
6619#endif
6620
6621TEST(StreamingAssertionsTest, Truth) {
6622  EXPECT_TRUE(true) << "unexpected failure";
6623  ASSERT_TRUE(true) << "unexpected failure";
6624  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6625                          "expected failure");
6626  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6627                       "expected failure");
6628}
6629
6630TEST(StreamingAssertionsTest, Truth2) {
6631  EXPECT_FALSE(false) << "unexpected failure";
6632  ASSERT_FALSE(false) << "unexpected failure";
6633  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6634                          "expected failure");
6635  EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6636                       "expected failure");
6637}
6638
6639#ifdef __BORLANDC__
6640// Restores warnings after previous "#pragma option push" supressed them
6641# pragma option pop
6642#endif
6643
6644TEST(StreamingAssertionsTest, IntegerEquals) {
6645  EXPECT_EQ(1, 1) << "unexpected failure";
6646  ASSERT_EQ(1, 1) << "unexpected failure";
6647  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6648                          "expected failure");
6649  EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6650                       "expected failure");
6651}
6652
6653TEST(StreamingAssertionsTest, IntegerLessThan) {
6654  EXPECT_LT(1, 2) << "unexpected failure";
6655  ASSERT_LT(1, 2) << "unexpected failure";
6656  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6657                          "expected failure");
6658  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6659                       "expected failure");
6660}
6661
6662TEST(StreamingAssertionsTest, StringsEqual) {
6663  EXPECT_STREQ("foo", "foo") << "unexpected failure";
6664  ASSERT_STREQ("foo", "foo") << "unexpected failure";
6665  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6666                          "expected failure");
6667  EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6668                       "expected failure");
6669}
6670
6671TEST(StreamingAssertionsTest, StringsNotEqual) {
6672  EXPECT_STRNE("foo", "bar") << "unexpected failure";
6673  ASSERT_STRNE("foo", "bar") << "unexpected failure";
6674  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6675                          "expected failure");
6676  EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6677                       "expected failure");
6678}
6679
6680TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6681  EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6682  ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6683  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6684                          "expected failure");
6685  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6686                       "expected failure");
6687}
6688
6689TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6690  EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6691  ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6692  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6693                          "expected failure");
6694  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6695                       "expected failure");
6696}
6697
6698TEST(StreamingAssertionsTest, FloatingPointEquals) {
6699  EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6700  ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6701  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6702                          "expected failure");
6703  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6704                       "expected failure");
6705}
6706
6707#if GTEST_HAS_EXCEPTIONS
6708
6709TEST(StreamingAssertionsTest, Throw) {
6710  EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6711  ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6712  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6713                          "expected failure", "expected failure");
6714  EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6715                       "expected failure", "expected failure");
6716}
6717
6718TEST(StreamingAssertionsTest, NoThrow) {
6719  EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6720  ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6721  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6722                          "expected failure", "expected failure");
6723  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6724                       "expected failure", "expected failure");
6725}
6726
6727TEST(StreamingAssertionsTest, AnyThrow) {
6728  EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6729  ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6730  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6731                          "expected failure", "expected failure");
6732  EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6733                       "expected failure", "expected failure");
6734}
6735
6736#endif  // GTEST_HAS_EXCEPTIONS
6737
6738// Tests that Google Test correctly decides whether to use colors in the output.
6739
6740TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6741  GTEST_FLAG(color) = "yes";
6742
6743  SetEnv("TERM", "xterm");  // TERM supports colors.
6744  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6745  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6746
6747  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6748  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6749  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6750}
6751
6752TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6753  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6754
6755  GTEST_FLAG(color) = "True";
6756  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6757
6758  GTEST_FLAG(color) = "t";
6759  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6760
6761  GTEST_FLAG(color) = "1";
6762  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6763}
6764
6765TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6766  GTEST_FLAG(color) = "no";
6767
6768  SetEnv("TERM", "xterm");  // TERM supports colors.
6769  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6770  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
6771
6772  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6773  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6774  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
6775}
6776
6777TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6778  SetEnv("TERM", "xterm");  // TERM supports colors.
6779
6780  GTEST_FLAG(color) = "F";
6781  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6782
6783  GTEST_FLAG(color) = "0";
6784  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6785
6786  GTEST_FLAG(color) = "unknown";
6787  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6788}
6789
6790TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6791  GTEST_FLAG(color) = "auto";
6792
6793  SetEnv("TERM", "xterm");  // TERM supports colors.
6794  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
6795  EXPECT_TRUE(ShouldUseColor(true));    // Stdout is a TTY.
6796}
6797
6798TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6799  GTEST_FLAG(color) = "auto";
6800
6801#if GTEST_OS_WINDOWS
6802  // On Windows, we ignore the TERM variable as it's usually not set.
6803
6804  SetEnv("TERM", "dumb");
6805  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6806
6807  SetEnv("TERM", "");
6808  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6809
6810  SetEnv("TERM", "xterm");
6811  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6812#else
6813  // On non-Windows platforms, we rely on TERM to determine if the
6814  // terminal supports colors.
6815
6816  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6817  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6818
6819  SetEnv("TERM", "emacs");  // TERM doesn't support colors.
6820  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6821
6822  SetEnv("TERM", "vt100");  // TERM doesn't support colors.
6823  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6824
6825  SetEnv("TERM", "xterm-mono");  // TERM doesn't support colors.
6826  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6827
6828  SetEnv("TERM", "xterm");  // TERM supports colors.
6829  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6830
6831  SetEnv("TERM", "xterm-color");  // TERM supports colors.
6832  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6833
6834  SetEnv("TERM", "xterm-256color");  // TERM supports colors.
6835  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6836
6837  SetEnv("TERM", "screen");  // TERM supports colors.
6838  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6839
6840  SetEnv("TERM", "screen-256color");  // TERM supports colors.
6841  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6842
6843  SetEnv("TERM", "rxvt-unicode");  // TERM supports colors.
6844  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6845
6846  SetEnv("TERM", "rxvt-unicode-256color");  // TERM supports colors.
6847  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6848
6849  SetEnv("TERM", "linux");  // TERM supports colors.
6850  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6851
6852  SetEnv("TERM", "cygwin");  // TERM supports colors.
6853  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6854#endif  // GTEST_OS_WINDOWS
6855}
6856
6857// Verifies that StaticAssertTypeEq works in a namespace scope.
6858
6859static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6860static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6861    StaticAssertTypeEq<const int, const int>();
6862
6863// Verifies that StaticAssertTypeEq works in a class.
6864
6865template <typename T>
6866class StaticAssertTypeEqTestHelper {
6867 public:
6868  StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6869};
6870
6871TEST(StaticAssertTypeEqTest, WorksInClass) {
6872  StaticAssertTypeEqTestHelper<bool>();
6873}
6874
6875// Verifies that StaticAssertTypeEq works inside a function.
6876
6877typedef int IntAlias;
6878
6879TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6880  StaticAssertTypeEq<int, IntAlias>();
6881  StaticAssertTypeEq<int*, IntAlias*>();
6882}
6883
6884TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6885  testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6886
6887  // We don't have a stack walker in Google Test yet.
6888  EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6889  EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6890}
6891
6892TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6893  EXPECT_FALSE(HasNonfatalFailure());
6894}
6895
6896static void FailFatally() { FAIL(); }
6897
6898TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6899  FailFatally();
6900  const bool has_nonfatal_failure = HasNonfatalFailure();
6901  ClearCurrentTestPartResults();
6902  EXPECT_FALSE(has_nonfatal_failure);
6903}
6904
6905TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6906  ADD_FAILURE();
6907  const bool has_nonfatal_failure = HasNonfatalFailure();
6908  ClearCurrentTestPartResults();
6909  EXPECT_TRUE(has_nonfatal_failure);
6910}
6911
6912TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6913  FailFatally();
6914  ADD_FAILURE();
6915  const bool has_nonfatal_failure = HasNonfatalFailure();
6916  ClearCurrentTestPartResults();
6917  EXPECT_TRUE(has_nonfatal_failure);
6918}
6919
6920// A wrapper for calling HasNonfatalFailure outside of a test body.
6921static bool HasNonfatalFailureHelper() {
6922  return testing::Test::HasNonfatalFailure();
6923}
6924
6925TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6926  EXPECT_FALSE(HasNonfatalFailureHelper());
6927}
6928
6929TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6930  ADD_FAILURE();
6931  const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6932  ClearCurrentTestPartResults();
6933  EXPECT_TRUE(has_nonfatal_failure);
6934}
6935
6936TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6937  EXPECT_FALSE(HasFailure());
6938}
6939
6940TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6941  FailFatally();
6942  const bool has_failure = HasFailure();
6943  ClearCurrentTestPartResults();
6944  EXPECT_TRUE(has_failure);
6945}
6946
6947TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6948  ADD_FAILURE();
6949  const bool has_failure = HasFailure();
6950  ClearCurrentTestPartResults();
6951  EXPECT_TRUE(has_failure);
6952}
6953
6954TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6955  FailFatally();
6956  ADD_FAILURE();
6957  const bool has_failure = HasFailure();
6958  ClearCurrentTestPartResults();
6959  EXPECT_TRUE(has_failure);
6960}
6961
6962// A wrapper for calling HasFailure outside of a test body.
6963static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6964
6965TEST(HasFailureTest, WorksOutsideOfTestBody) {
6966  EXPECT_FALSE(HasFailureHelper());
6967}
6968
6969TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6970  ADD_FAILURE();
6971  const bool has_failure = HasFailureHelper();
6972  ClearCurrentTestPartResults();
6973  EXPECT_TRUE(has_failure);
6974}
6975
6976class TestListener : public EmptyTestEventListener {
6977 public:
6978  TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6979  TestListener(int* on_start_counter, bool* is_destroyed)
6980      : on_start_counter_(on_start_counter),
6981        is_destroyed_(is_destroyed) {}
6982
6983  virtual ~TestListener() {
6984    if (is_destroyed_)
6985      *is_destroyed_ = true;
6986  }
6987
6988 protected:
6989  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
6990    if (on_start_counter_ != NULL)
6991      (*on_start_counter_)++;
6992  }
6993
6994 private:
6995  int* on_start_counter_;
6996  bool* is_destroyed_;
6997};
6998
6999// Tests the constructor.
7000TEST(TestEventListenersTest, ConstructionWorks) {
7001  TestEventListeners listeners;
7002
7003  EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
7004  EXPECT_TRUE(listeners.default_result_printer() == NULL);
7005  EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7006}
7007
7008// Tests that the TestEventListeners destructor deletes all the listeners it
7009// owns.
7010TEST(TestEventListenersTest, DestructionWorks) {
7011  bool default_result_printer_is_destroyed = false;
7012  bool default_xml_printer_is_destroyed = false;
7013  bool extra_listener_is_destroyed = false;
7014  TestListener* default_result_printer = new TestListener(
7015      NULL, &default_result_printer_is_destroyed);
7016  TestListener* default_xml_printer = new TestListener(
7017      NULL, &default_xml_printer_is_destroyed);
7018  TestListener* extra_listener = new TestListener(
7019      NULL, &extra_listener_is_destroyed);
7020
7021  {
7022    TestEventListeners listeners;
7023    TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
7024                                                        default_result_printer);
7025    TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
7026                                                       default_xml_printer);
7027    listeners.Append(extra_listener);
7028  }
7029  EXPECT_TRUE(default_result_printer_is_destroyed);
7030  EXPECT_TRUE(default_xml_printer_is_destroyed);
7031  EXPECT_TRUE(extra_listener_is_destroyed);
7032}
7033
7034// Tests that a listener Append'ed to a TestEventListeners list starts
7035// receiving events.
7036TEST(TestEventListenersTest, Append) {
7037  int on_start_counter = 0;
7038  bool is_destroyed = false;
7039  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7040  {
7041    TestEventListeners listeners;
7042    listeners.Append(listener);
7043    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7044        *UnitTest::GetInstance());
7045    EXPECT_EQ(1, on_start_counter);
7046  }
7047  EXPECT_TRUE(is_destroyed);
7048}
7049
7050// Tests that listeners receive events in the order they were appended to
7051// the list, except for *End requests, which must be received in the reverse
7052// order.
7053class SequenceTestingListener : public EmptyTestEventListener {
7054 public:
7055  SequenceTestingListener(std::vector<std::string>* vector, const char* id)
7056      : vector_(vector), id_(id) {}
7057
7058 protected:
7059  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
7060    vector_->push_back(GetEventDescription("OnTestProgramStart"));
7061  }
7062
7063  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
7064    vector_->push_back(GetEventDescription("OnTestProgramEnd"));
7065  }
7066
7067  virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
7068                                    int /*iteration*/) {
7069    vector_->push_back(GetEventDescription("OnTestIterationStart"));
7070  }
7071
7072  virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
7073                                  int /*iteration*/) {
7074    vector_->push_back(GetEventDescription("OnTestIterationEnd"));
7075  }
7076
7077 private:
7078  std::string GetEventDescription(const char* method) {
7079    Message message;
7080    message << id_ << "." << method;
7081    return message.GetString();
7082  }
7083
7084  std::vector<std::string>* vector_;
7085  const char* const id_;
7086
7087  GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
7088};
7089
7090TEST(EventListenerTest, AppendKeepsOrder) {
7091  std::vector<std::string> vec;
7092  TestEventListeners listeners;
7093  listeners.Append(new SequenceTestingListener(&vec, "1st"));
7094  listeners.Append(new SequenceTestingListener(&vec, "2nd"));
7095  listeners.Append(new SequenceTestingListener(&vec, "3rd"));
7096
7097  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7098      *UnitTest::GetInstance());
7099  ASSERT_EQ(3U, vec.size());
7100  EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
7101  EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
7102  EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
7103
7104  vec.clear();
7105  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
7106      *UnitTest::GetInstance());
7107  ASSERT_EQ(3U, vec.size());
7108  EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
7109  EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
7110  EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
7111
7112  vec.clear();
7113  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
7114      *UnitTest::GetInstance(), 0);
7115  ASSERT_EQ(3U, vec.size());
7116  EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
7117  EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
7118  EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
7119
7120  vec.clear();
7121  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
7122      *UnitTest::GetInstance(), 0);
7123  ASSERT_EQ(3U, vec.size());
7124  EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
7125  EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
7126  EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
7127}
7128
7129// Tests that a listener removed from a TestEventListeners list stops receiving
7130// events and is not deleted when the list is destroyed.
7131TEST(TestEventListenersTest, Release) {
7132  int on_start_counter = 0;
7133  bool is_destroyed = false;
7134  // Although Append passes the ownership of this object to the list,
7135  // the following calls release it, and we need to delete it before the
7136  // test ends.
7137  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7138  {
7139    TestEventListeners listeners;
7140    listeners.Append(listener);
7141    EXPECT_EQ(listener, listeners.Release(listener));
7142    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7143        *UnitTest::GetInstance());
7144    EXPECT_TRUE(listeners.Release(listener) == NULL);
7145  }
7146  EXPECT_EQ(0, on_start_counter);
7147  EXPECT_FALSE(is_destroyed);
7148  delete listener;
7149}
7150
7151// Tests that no events are forwarded when event forwarding is disabled.
7152TEST(EventListenerTest, SuppressEventForwarding) {
7153  int on_start_counter = 0;
7154  TestListener* listener = new TestListener(&on_start_counter, NULL);
7155
7156  TestEventListeners listeners;
7157  listeners.Append(listener);
7158  ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7159  TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7160  ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7161  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7162      *UnitTest::GetInstance());
7163  EXPECT_EQ(0, on_start_counter);
7164}
7165
7166// Tests that events generated by Google Test are not forwarded in
7167// death test subprocesses.
7168TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7169  EXPECT_DEATH_IF_SUPPORTED({
7170      GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7171          *GetUnitTestImpl()->listeners())) << "expected failure";},
7172      "expected failure");
7173}
7174
7175// Tests that a listener installed via SetDefaultResultPrinter() starts
7176// receiving events and is returned via default_result_printer() and that
7177// the previous default_result_printer is removed from the list and deleted.
7178TEST(EventListenerTest, default_result_printer) {
7179  int on_start_counter = 0;
7180  bool is_destroyed = false;
7181  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7182
7183  TestEventListeners listeners;
7184  TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7185
7186  EXPECT_EQ(listener, listeners.default_result_printer());
7187
7188  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7189      *UnitTest::GetInstance());
7190
7191  EXPECT_EQ(1, on_start_counter);
7192
7193  // Replacing default_result_printer with something else should remove it
7194  // from the list and destroy it.
7195  TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
7196
7197  EXPECT_TRUE(listeners.default_result_printer() == NULL);
7198  EXPECT_TRUE(is_destroyed);
7199
7200  // After broadcasting an event the counter is still the same, indicating
7201  // the listener is not in the list anymore.
7202  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7203      *UnitTest::GetInstance());
7204  EXPECT_EQ(1, on_start_counter);
7205}
7206
7207// Tests that the default_result_printer listener stops receiving events
7208// when removed via Release and that is not owned by the list anymore.
7209TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7210  int on_start_counter = 0;
7211  bool is_destroyed = false;
7212  // Although Append passes the ownership of this object to the list,
7213  // the following calls release it, and we need to delete it before the
7214  // test ends.
7215  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7216  {
7217    TestEventListeners listeners;
7218    TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7219
7220    EXPECT_EQ(listener, listeners.Release(listener));
7221    EXPECT_TRUE(listeners.default_result_printer() == NULL);
7222    EXPECT_FALSE(is_destroyed);
7223
7224    // Broadcasting events now should not affect default_result_printer.
7225    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7226        *UnitTest::GetInstance());
7227    EXPECT_EQ(0, on_start_counter);
7228  }
7229  // Destroying the list should not affect the listener now, too.
7230  EXPECT_FALSE(is_destroyed);
7231  delete listener;
7232}
7233
7234// Tests that a listener installed via SetDefaultXmlGenerator() starts
7235// receiving events and is returned via default_xml_generator() and that
7236// the previous default_xml_generator is removed from the list and deleted.
7237TEST(EventListenerTest, default_xml_generator) {
7238  int on_start_counter = 0;
7239  bool is_destroyed = false;
7240  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7241
7242  TestEventListeners listeners;
7243  TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7244
7245  EXPECT_EQ(listener, listeners.default_xml_generator());
7246
7247  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7248      *UnitTest::GetInstance());
7249
7250  EXPECT_EQ(1, on_start_counter);
7251
7252  // Replacing default_xml_generator with something else should remove it
7253  // from the list and destroy it.
7254  TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
7255
7256  EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7257  EXPECT_TRUE(is_destroyed);
7258
7259  // After broadcasting an event the counter is still the same, indicating
7260  // the listener is not in the list anymore.
7261  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7262      *UnitTest::GetInstance());
7263  EXPECT_EQ(1, on_start_counter);
7264}
7265
7266// Tests that the default_xml_generator listener stops receiving events
7267// when removed via Release and that is not owned by the list anymore.
7268TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7269  int on_start_counter = 0;
7270  bool is_destroyed = false;
7271  // Although Append passes the ownership of this object to the list,
7272  // the following calls release it, and we need to delete it before the
7273  // test ends.
7274  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7275  {
7276    TestEventListeners listeners;
7277    TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7278
7279    EXPECT_EQ(listener, listeners.Release(listener));
7280    EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7281    EXPECT_FALSE(is_destroyed);
7282
7283    // Broadcasting events now should not affect default_xml_generator.
7284    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7285        *UnitTest::GetInstance());
7286    EXPECT_EQ(0, on_start_counter);
7287  }
7288  // Destroying the list should not affect the listener now, too.
7289  EXPECT_FALSE(is_destroyed);
7290  delete listener;
7291}
7292
7293// Sanity tests to ensure that the alternative, verbose spellings of
7294// some of the macros work.  We don't test them thoroughly as that
7295// would be quite involved.  Since their implementations are
7296// straightforward, and they are rarely used, we'll just rely on the
7297// users to tell us when they are broken.
7298GTEST_TEST(AlternativeNameTest, Works) {  // GTEST_TEST is the same as TEST.
7299  GTEST_SUCCEED() << "OK";  // GTEST_SUCCEED is the same as SUCCEED.
7300
7301  // GTEST_FAIL is the same as FAIL.
7302  EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7303                       "An expected failure");
7304
7305  // GTEST_ASSERT_XY is the same as ASSERT_XY.
7306
7307  GTEST_ASSERT_EQ(0, 0);
7308  EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7309                       "An expected failure");
7310  EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7311                       "An expected failure");
7312
7313  GTEST_ASSERT_NE(0, 1);
7314  GTEST_ASSERT_NE(1, 0);
7315  EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7316                       "An expected failure");
7317
7318  GTEST_ASSERT_LE(0, 0);
7319  GTEST_ASSERT_LE(0, 1);
7320  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7321                       "An expected failure");
7322
7323  GTEST_ASSERT_LT(0, 1);
7324  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7325                       "An expected failure");
7326  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7327                       "An expected failure");
7328
7329  GTEST_ASSERT_GE(0, 0);
7330  GTEST_ASSERT_GE(1, 0);
7331  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7332                       "An expected failure");
7333
7334  GTEST_ASSERT_GT(1, 0);
7335  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7336                       "An expected failure");
7337  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7338                       "An expected failure");
7339}
7340
7341// Tests for internal utilities necessary for implementation of the universal
7342// printing.
7343// TODO(vladl@google.com): Find a better home for them.
7344
7345class ConversionHelperBase {};
7346class ConversionHelperDerived : public ConversionHelperBase {};
7347
7348// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
7349TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
7350  GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
7351                        const_true);
7352  GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
7353}
7354
7355// Tests that IsAProtocolMessage<T>::value is true when T is
7356// proto2::Message or a sub-class of it.
7357TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
7358  EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
7359  EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
7360}
7361
7362// Tests that IsAProtocolMessage<T>::value is false when T is neither
7363// ProtocolMessage nor a sub-class of it.
7364TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7365  EXPECT_FALSE(IsAProtocolMessage<int>::value);
7366  EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
7367}
7368
7369// Tests that CompileAssertTypesEqual compiles when the type arguments are
7370// equal.
7371TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
7372  CompileAssertTypesEqual<void, void>();
7373  CompileAssertTypesEqual<int*, int*>();
7374}
7375
7376// Tests that RemoveReference does not affect non-reference types.
7377TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
7378  CompileAssertTypesEqual<int, RemoveReference<int>::type>();
7379  CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
7380}
7381
7382// Tests that RemoveReference removes reference from reference types.
7383TEST(RemoveReferenceTest, RemovesReference) {
7384  CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
7385  CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
7386}
7387
7388// Tests GTEST_REMOVE_REFERENCE_.
7389
7390template <typename T1, typename T2>
7391void TestGTestRemoveReference() {
7392  CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
7393}
7394
7395TEST(RemoveReferenceTest, MacroVersion) {
7396  TestGTestRemoveReference<int, int>();
7397  TestGTestRemoveReference<const char, const char&>();
7398}
7399
7400
7401// Tests that RemoveConst does not affect non-const types.
7402TEST(RemoveConstTest, DoesNotAffectNonConstType) {
7403  CompileAssertTypesEqual<int, RemoveConst<int>::type>();
7404  CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
7405}
7406
7407// Tests that RemoveConst removes const from const types.
7408TEST(RemoveConstTest, RemovesConst) {
7409  CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
7410  CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
7411  CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
7412}
7413
7414// Tests GTEST_REMOVE_CONST_.
7415
7416template <typename T1, typename T2>
7417void TestGTestRemoveConst() {
7418  CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
7419}
7420
7421TEST(RemoveConstTest, MacroVersion) {
7422  TestGTestRemoveConst<int, int>();
7423  TestGTestRemoveConst<double&, double&>();
7424  TestGTestRemoveConst<char, const char>();
7425}
7426
7427// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7428
7429template <typename T1, typename T2>
7430void TestGTestRemoveReferenceAndConst() {
7431  CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
7432}
7433
7434TEST(RemoveReferenceToConstTest, Works) {
7435  TestGTestRemoveReferenceAndConst<int, int>();
7436  TestGTestRemoveReferenceAndConst<double, double&>();
7437  TestGTestRemoveReferenceAndConst<char, const char>();
7438  TestGTestRemoveReferenceAndConst<char, const char&>();
7439  TestGTestRemoveReferenceAndConst<const char*, const char*>();
7440}
7441
7442// Tests that AddReference does not affect reference types.
7443TEST(AddReferenceTest, DoesNotAffectReferenceType) {
7444  CompileAssertTypesEqual<int&, AddReference<int&>::type>();
7445  CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
7446}
7447
7448// Tests that AddReference adds reference to non-reference types.
7449TEST(AddReferenceTest, AddsReference) {
7450  CompileAssertTypesEqual<int&, AddReference<int>::type>();
7451  CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
7452}
7453
7454// Tests GTEST_ADD_REFERENCE_.
7455
7456template <typename T1, typename T2>
7457void TestGTestAddReference() {
7458  CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
7459}
7460
7461TEST(AddReferenceTest, MacroVersion) {
7462  TestGTestAddReference<int&, int>();
7463  TestGTestAddReference<const char&, const char&>();
7464}
7465
7466// Tests GTEST_REFERENCE_TO_CONST_.
7467
7468template <typename T1, typename T2>
7469void TestGTestReferenceToConst() {
7470  CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
7471}
7472
7473TEST(GTestReferenceToConstTest, Works) {
7474  TestGTestReferenceToConst<const char&, char>();
7475  TestGTestReferenceToConst<const int&, const int>();
7476  TestGTestReferenceToConst<const double&, double>();
7477  TestGTestReferenceToConst<const std::string&, const std::string&>();
7478}
7479
7480// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
7481TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
7482  GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
7483  GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
7484                        const_false);
7485}
7486
7487// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
7488// be implicitly converted to T2.
7489TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
7490  EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
7491  EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
7492  EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
7493  EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
7494  EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
7495                                     const ConversionHelperBase&>::value));
7496  EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
7497                                     ConversionHelperBase>::value));
7498}
7499
7500// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
7501// cannot be implicitly converted to T2.
7502TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
7503  EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
7504  EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
7505  EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
7506  EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
7507                                      ConversionHelperDerived&>::value));
7508}
7509
7510// Tests IsContainerTest.
7511
7512class NonContainer {};
7513
7514TEST(IsContainerTestTest, WorksForNonContainer) {
7515  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7516  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7517  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7518}
7519
7520TEST(IsContainerTestTest, WorksForContainer) {
7521  EXPECT_EQ(sizeof(IsContainer),
7522            sizeof(IsContainerTest<std::vector<bool> >(0)));
7523  EXPECT_EQ(sizeof(IsContainer),
7524            sizeof(IsContainerTest<std::map<int, double> >(0)));
7525}
7526
7527// Tests ArrayEq().
7528
7529TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7530  EXPECT_TRUE(ArrayEq(5, 5L));
7531  EXPECT_FALSE(ArrayEq('a', 0));
7532}
7533
7534TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7535  // Note that a and b are distinct but compatible types.
7536  const int a[] = { 0, 1 };
7537  long b[] = { 0, 1 };
7538  EXPECT_TRUE(ArrayEq(a, b));
7539  EXPECT_TRUE(ArrayEq(a, 2, b));
7540
7541  b[0] = 2;
7542  EXPECT_FALSE(ArrayEq(a, b));
7543  EXPECT_FALSE(ArrayEq(a, 1, b));
7544}
7545
7546TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7547  const char a[][3] = { "hi", "lo" };
7548  const char b[][3] = { "hi", "lo" };
7549  const char c[][3] = { "hi", "li" };
7550
7551  EXPECT_TRUE(ArrayEq(a, b));
7552  EXPECT_TRUE(ArrayEq(a, 2, b));
7553
7554  EXPECT_FALSE(ArrayEq(a, c));
7555  EXPECT_FALSE(ArrayEq(a, 2, c));
7556}
7557
7558// Tests ArrayAwareFind().
7559
7560TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7561  const char a[] = "hello";
7562  EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7563  EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7564}
7565
7566TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7567  int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7568  const int b[2] = { 2, 3 };
7569  EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7570
7571  const int c[2] = { 6, 7 };
7572  EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7573}
7574
7575// Tests CopyArray().
7576
7577TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7578  int n = 0;
7579  CopyArray('a', &n);
7580  EXPECT_EQ('a', n);
7581}
7582
7583TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7584  const char a[3] = "hi";
7585  int b[3];
7586#ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
7587  CopyArray(a, &b);
7588  EXPECT_TRUE(ArrayEq(a, b));
7589#endif
7590
7591  int c[3];
7592  CopyArray(a, 3, c);
7593  EXPECT_TRUE(ArrayEq(a, c));
7594}
7595
7596TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7597  const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7598  int b[2][3];
7599#ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
7600  CopyArray(a, &b);
7601  EXPECT_TRUE(ArrayEq(a, b));
7602#endif
7603
7604  int c[2][3];
7605  CopyArray(a, 2, c);
7606  EXPECT_TRUE(ArrayEq(a, c));
7607}
7608
7609// Tests NativeArray.
7610
7611TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7612  const int a[3] = { 0, 1, 2 };
7613  NativeArray<int> na(a, 3, RelationToSourceReference());
7614  EXPECT_EQ(3U, na.size());
7615  EXPECT_EQ(a, na.begin());
7616}
7617
7618TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7619  typedef int Array[2];
7620  Array* a = new Array[1];
7621  (*a)[0] = 0;
7622  (*a)[1] = 1;
7623  NativeArray<int> na(*a, 2, RelationToSourceCopy());
7624  EXPECT_NE(*a, na.begin());
7625  delete[] a;
7626  EXPECT_EQ(0, na.begin()[0]);
7627  EXPECT_EQ(1, na.begin()[1]);
7628
7629  // We rely on the heap checker to verify that na deletes the copy of
7630  // array.
7631}
7632
7633TEST(NativeArrayTest, TypeMembersAreCorrect) {
7634  StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7635  StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7636
7637  StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7638  StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7639}
7640
7641TEST(NativeArrayTest, MethodsWork) {
7642  const int a[3] = { 0, 1, 2 };
7643  NativeArray<int> na(a, 3, RelationToSourceCopy());
7644  ASSERT_EQ(3U, na.size());
7645  EXPECT_EQ(3, na.end() - na.begin());
7646
7647  NativeArray<int>::const_iterator it = na.begin();
7648  EXPECT_EQ(0, *it);
7649  ++it;
7650  EXPECT_EQ(1, *it);
7651  it++;
7652  EXPECT_EQ(2, *it);
7653  ++it;
7654  EXPECT_EQ(na.end(), it);
7655
7656  EXPECT_TRUE(na == na);
7657
7658  NativeArray<int> na2(a, 3, RelationToSourceReference());
7659  EXPECT_TRUE(na == na2);
7660
7661  const int b1[3] = { 0, 1, 1 };
7662  const int b2[4] = { 0, 1, 2, 3 };
7663  EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7664  EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7665}
7666
7667TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7668  const char a[2][3] = { "hi", "lo" };
7669  NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7670  ASSERT_EQ(2U, na.size());
7671  EXPECT_EQ(a, na.begin());
7672}
7673
7674// Tests SkipPrefix().
7675
7676TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7677  const char* const str = "hello";
7678
7679  const char* p = str;
7680  EXPECT_TRUE(SkipPrefix("", &p));
7681  EXPECT_EQ(str, p);
7682
7683  p = str;
7684  EXPECT_TRUE(SkipPrefix("hell", &p));
7685  EXPECT_EQ(str + 4, p);
7686}
7687
7688TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7689  const char* const str = "world";
7690
7691  const char* p = str;
7692  EXPECT_FALSE(SkipPrefix("W", &p));
7693  EXPECT_EQ(str, p);
7694
7695  p = str;
7696  EXPECT_FALSE(SkipPrefix("world!", &p));
7697  EXPECT_EQ(str, p);
7698}
7699
trunk/3rdparty/googletest/googletest/test/gtest_xml_outfile1_test_.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: keith.ray@gmail.com (Keith Ray)
31//
32// gtest_xml_outfile1_test_ writes some xml via TestProperty used by
33// gtest_xml_outfiles_test.py
34
35#include "gtest/gtest.h"
36
37class PropertyOne : public testing::Test {
38 protected:
39  virtual void SetUp() {
40    RecordProperty("SetUpProp", 1);
41  }
42  virtual void TearDown() {
43    RecordProperty("TearDownProp", 1);
44  }
45};
46
47TEST_F(PropertyOne, TestSomeProperties) {
48  RecordProperty("TestSomeProperty", 1);
49}
trunk/3rdparty/googletest/googletest/test/gtest_xml_outfile2_test_.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: keith.ray@gmail.com (Keith Ray)
31//
32// gtest_xml_outfile2_test_ writes some xml via TestProperty used by
33// gtest_xml_outfiles_test.py
34
35#include "gtest/gtest.h"
36
37class PropertyTwo : public testing::Test {
38 protected:
39  virtual void SetUp() {
40    RecordProperty("SetUpProp", 2);
41  }
42  virtual void TearDown() {
43    RecordProperty("TearDownProp", 2);
44  }
45};
46
47TEST_F(PropertyTwo, TestSomeProperties) {
48  RecordProperty("TestSomeProperty", 2);
49}
trunk/3rdparty/googletest/googletest/test/gtest_xml_outfiles_test.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Unit test for the gtest_xml_output module."""
33
34__author__ = "keith.ray@gmail.com (Keith Ray)"
35
36import os
37from xml.dom import minidom, Node
38
39import gtest_test_utils
40import gtest_xml_test_utils
41
42
43GTEST_OUTPUT_SUBDIR = "xml_outfiles"
44GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_"
45GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"
46
47EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
48<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
49  <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*">
50    <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" />
51  </testsuite>
52</testsuites>
53"""
54
55EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
56<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
57  <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*">
58    <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" />
59  </testsuite>
60</testsuites>
61"""
62
63
64class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
65  """Unit test for Google Test's XML output functionality."""
66
67  def setUp(self):
68    # We want the trailing '/' that the last "" provides in os.path.join, for
69    # telling Google Test to create an output directory instead of a single file
70    # for xml output.
71    self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),
72                                    GTEST_OUTPUT_SUBDIR, "")
73    self.DeleteFilesAndDir()
74
75  def tearDown(self):
76    self.DeleteFilesAndDir()
77
78  def DeleteFilesAndDir(self):
79    try:
80      os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + ".xml"))
81    except os.error:
82      pass
83    try:
84      os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + ".xml"))
85    except os.error:
86      pass
87    try:
88      os.rmdir(self.output_dir_)
89    except os.error:
90      pass
91
92  def testOutfile1(self):
93    self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1)
94
95  def testOutfile2(self):
96    self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2)
97
98  def _TestOutFile(self, test_name, expected_xml):
99    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
100    command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_]
101    p = gtest_test_utils.Subprocess(command,
102                                    working_dir=gtest_test_utils.GetTempDir())
103    self.assert_(p.exited)
104    self.assertEquals(0, p.exit_code)
105
106    # TODO(wan@google.com): libtool causes the built test binary to be
107    #   named lt-gtest_xml_outfiles_test_ instead of
108    #   gtest_xml_outfiles_test_.  To account for this possibillity, we
109    #   allow both names in the following code.  We should remove this
110    #   hack when Chandler Carruth's libtool replacement tool is ready.
111    output_file_name1 = test_name + ".xml"
112    output_file1 = os.path.join(self.output_dir_, output_file_name1)
113    output_file_name2 = 'lt-' + output_file_name1
114    output_file2 = os.path.join(self.output_dir_, output_file_name2)
115    self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
116                 output_file1)
117
118    expected = minidom.parseString(expected_xml)
119    if os.path.isfile(output_file1):
120      actual = minidom.parse(output_file1)
121    else:
122      actual = minidom.parse(output_file2)
123    self.NormalizeXml(actual.documentElement)
124    self.AssertEquivalentNodes(expected.documentElement,
125                               actual.documentElement)
126    expected.unlink()
127    actual.unlink()
128
129
130if __name__ == "__main__":
131  os.environ["GTEST_STACK_TRACE_DEPTH"] = "0"
132  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_xml_output_unittest.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2006, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Unit test for the gtest_xml_output module"""
33
34__author__ = 'eefacm@gmail.com (Sean Mcafee)'
35
36import datetime
37import errno
38import os
39import re
40import sys
41from xml.dom import minidom, Node
42
43import gtest_test_utils
44import gtest_xml_test_utils
45
46
47GTEST_FILTER_FLAG = '--gtest_filter'
48GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
49GTEST_OUTPUT_FLAG         = "--gtest_output"
50GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
51GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_"
52
53SUPPORTS_STACK_TRACES = False
54
55if SUPPORTS_STACK_TRACES:
56  STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
57else:
58  STACK_TRACE_TEMPLATE = ''
59
60EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
61<testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
62  <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
63    <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
64  </testsuite>
65  <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
66    <testcase name="Fails" status="run" time="*" classname="FailedTest">
67      <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
68Value of: 2
69Expected: 1%(stack)s]]></failure>
70    </testcase>
71  </testsuite>
72  <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
73    <testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
74    <testcase name="Fails" status="run" time="*" classname="MixedResultTest">
75      <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
76Value of: 2
77Expected: 1%(stack)s]]></failure>
78      <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 3&#x0A;Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
79Value of: 3
80Expected: 2%(stack)s]]></failure>
81    </testcase>
82    <testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
83  </testsuite>
84  <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*">
85    <testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest">
86      <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
87Failed
88XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure>
89    </testcase>
90  </testsuite>
91  <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*">
92    <testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest">
93      <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
94Failed
95Invalid characters in brackets []%(stack)s]]></failure>
96    </testcase>
97  </testsuite>
98  <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*">
99    <testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/>
100  </testsuite>
101  <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" SetUpTestCase="yes" TearDownTestCase="aye">
102    <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/>
103    <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/>
104    <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/>
105    <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/>
106  </testsuite>
107  <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*">
108     <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
109     <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/>
110     <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/>
111  </testsuite>
112  <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*">
113    <testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" />
114    <testcase name="HasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" />
115    <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" />
116    <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" />
117  </testsuite>
118  <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*">
119    <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/0" />
120  </testsuite>
121  <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*">
122    <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/1" />
123  </testsuite>
124  <testsuite name="Single/TypeParameterizedTestCase/0" tests="1" failures="0" disabled="0" errors="0" time="*">
125    <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/0" />
126  </testsuite>
127  <testsuite name="Single/TypeParameterizedTestCase/1" tests="1" failures="0" disabled="0" errors="0" time="*">
128    <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/1" />
129  </testsuite>
130</testsuites>""" % {'stack': STACK_TRACE_TEMPLATE}
131
132EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
133<testsuites tests="1" failures="0" disabled="0" errors="0" time="*"
134            timestamp="*" name="AllTests" ad_hoc_property="42">
135  <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0"
136             errors="0" time="*">
137    <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
138  </testsuite>
139</testsuites>"""
140
141EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
142<testsuites tests="0" failures="0" disabled="0" errors="0" time="*"
143            timestamp="*" name="AllTests">
144</testsuites>"""
145
146GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
147
148SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
149    [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
150
151
152class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
153  """
154  Unit test for Google Test's XML output functionality.
155  """
156
157  # This test currently breaks on platforms that do not support typed and
158  # type-parameterized tests, so we don't run it under them.
159  if SUPPORTS_TYPED_TESTS:
160    def testNonEmptyXmlOutput(self):
161      """
162      Runs a test program that generates a non-empty XML output, and
163      tests that the XML output is expected.
164      """
165      self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
166
167  def testEmptyXmlOutput(self):
168    """Verifies XML output for a Google Test binary without actual tests.
169
170    Runs a test program that generates an empty XML output, and
171    tests that the XML output is expected.
172    """
173
174    self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0)
175
176  def testTimestampValue(self):
177    """Checks whether the timestamp attribute in the XML output is valid.
178
179    Runs a test program that generates an empty XML output, and checks if
180    the timestamp attribute in the testsuites tag is valid.
181    """
182    actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0)
183    date_time_str = actual.documentElement.getAttributeNode('timestamp').value
184    # datetime.strptime() is only available in Python 2.5+ so we have to
185    # parse the expected datetime manually.
186    match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
187    self.assertTrue(
188        re.match,
189        'XML datettime string %s has incorrect format' % date_time_str)
190    date_time_from_xml = datetime.datetime(
191        year=int(match.group(1)), month=int(match.group(2)),
192        day=int(match.group(3)), hour=int(match.group(4)),
193        minute=int(match.group(5)), second=int(match.group(6)))
194
195    time_delta = abs(datetime.datetime.now() - date_time_from_xml)
196    # timestamp value should be near the current local time
197    self.assertTrue(time_delta < datetime.timedelta(seconds=600),
198                    'time_delta is %s' % time_delta)
199    actual.unlink()
200
201  def testDefaultOutputFile(self):
202    """
203    Confirms that Google Test produces an XML output file with the expected
204    default name if no name is explicitly specified.
205    """
206    output_file = os.path.join(gtest_test_utils.GetTempDir(),
207                               GTEST_DEFAULT_OUTPUT_FILE)
208    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
209        'gtest_no_test_unittest')
210    try:
211      os.remove(output_file)
212    except OSError, e:
213      if e.errno != errno.ENOENT:
214        raise
215
216    p = gtest_test_utils.Subprocess(
217        [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG],
218        working_dir=gtest_test_utils.GetTempDir())
219    self.assert_(p.exited)
220    self.assertEquals(0, p.exit_code)
221    self.assert_(os.path.isfile(output_file))
222
223  def testSuppressedXmlOutput(self):
224    """
225    Tests that no XML file is generated if the default XML listener is
226    shut down before RUN_ALL_TESTS is invoked.
227    """
228
229    xml_path = os.path.join(gtest_test_utils.GetTempDir(),
230                            GTEST_PROGRAM_NAME + 'out.xml')
231    if os.path.isfile(xml_path):
232      os.remove(xml_path)
233
234    command = [GTEST_PROGRAM_PATH,
235               '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
236               '--shut_down_xml']
237    p = gtest_test_utils.Subprocess(command)
238    if p.terminated_by_signal:
239      # p.signal is avalable only if p.terminated_by_signal is True.
240      self.assertFalse(
241          p.terminated_by_signal,
242          '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
243    else:
244      self.assert_(p.exited)
245      self.assertEquals(1, p.exit_code,
246                        "'%s' exited with code %s, which doesn't match "
247                        'the expected exit code %s.'
248                        % (command, p.exit_code, 1))
249
250    self.assert_(not os.path.isfile(xml_path))
251
252  def testFilteredTestXmlOutput(self):
253    """Verifies XML output when a filter is applied.
254
255    Runs a test program that executes only some tests and verifies that
256    non-selected tests do not show up in the XML output.
257    """
258
259    self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0,
260                        extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
261
262  def _GetXmlOutput(self, gtest_prog_name, extra_args, expected_exit_code):
263    """
264    Returns the xml output generated by running the program gtest_prog_name.
265    Furthermore, the program's exit code must be expected_exit_code.
266    """
267    xml_path = os.path.join(gtest_test_utils.GetTempDir(),
268                            gtest_prog_name + 'out.xml')
269    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
270
271    command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] +
272               extra_args)
273    p = gtest_test_utils.Subprocess(command)
274    if p.terminated_by_signal:
275      self.assert_(False,
276                   '%s was killed by signal %d' % (gtest_prog_name, p.signal))
277    else:
278      self.assert_(p.exited)
279      self.assertEquals(expected_exit_code, p.exit_code,
280                        "'%s' exited with code %s, which doesn't match "
281                        'the expected exit code %s.'
282                        % (command, p.exit_code, expected_exit_code))
283    actual = minidom.parse(xml_path)
284    return actual
285
286  def _TestXmlOutput(self, gtest_prog_name, expected_xml,
287                     expected_exit_code, extra_args=None):
288    """
289    Asserts that the XML document generated by running the program
290    gtest_prog_name matches expected_xml, a string containing another
291    XML document.  Furthermore, the program's exit code must be
292    expected_exit_code.
293    """
294
295    actual = self._GetXmlOutput(gtest_prog_name, extra_args or [],
296                                expected_exit_code)
297    expected = minidom.parseString(expected_xml)
298    self.NormalizeXml(actual.documentElement)
299    self.AssertEquivalentNodes(expected.documentElement,
300                               actual.documentElement)
301    expected.unlink()
302    actual.unlink()
303
304
305if __name__ == '__main__':
306  os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
307  gtest_test_utils.Main()
trunk/3rdparty/googletest/googletest/test/gtest_xml_output_unittest_.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// Author: eefacm@gmail.com (Sean Mcafee)
31
32// Unit test for Google Test XML output.
33//
34// A user can specify XML output in a Google Test program to run via
35// either the GTEST_OUTPUT environment variable or the --gtest_output
36// flag.  This is used for testing such functionality.
37//
38// This program will be invoked from a Python unit test.  Don't run it
39// directly.
40
41#include "gtest/gtest.h"
42
43using ::testing::InitGoogleTest;
44using ::testing::TestEventListeners;
45using ::testing::TestWithParam;
46using ::testing::UnitTest;
47using ::testing::Test;
48using ::testing::Values;
49
50class SuccessfulTest : public Test {
51};
52
53TEST_F(SuccessfulTest, Succeeds) {
54  SUCCEED() << "This is a success.";
55  ASSERT_EQ(1, 1);
56}
57
58class FailedTest : public Test {
59};
60
61TEST_F(FailedTest, Fails) {
62  ASSERT_EQ(1, 2);
63}
64
65class DisabledTest : public Test {
66};
67
68TEST_F(DisabledTest, DISABLED_test_not_run) {
69  FAIL() << "Unexpected failure: Disabled test should not be run";
70}
71
72TEST(MixedResultTest, Succeeds) {
73  EXPECT_EQ(1, 1);
74  ASSERT_EQ(1, 1);
75}
76
77TEST(MixedResultTest, Fails) {
78  EXPECT_EQ(1, 2);
79  ASSERT_EQ(2, 3);
80}
81
82TEST(MixedResultTest, DISABLED_test) {
83  FAIL() << "Unexpected failure: Disabled test should not be run";
84}
85
86TEST(XmlQuotingTest, OutputsCData) {
87  FAIL() << "XML output: "
88            "<?xml encoding=\"utf-8\"><top><![CDATA[cdata text]]></top>";
89}
90
91// Helps to test that invalid characters produced by test code do not make
92// it into the XML file.
93TEST(InvalidCharactersTest, InvalidCharactersInMessage) {
94  FAIL() << "Invalid characters in brackets [\x1\x2]";
95}
96
97class PropertyRecordingTest : public Test {
98 public:
99  static void SetUpTestCase() { RecordProperty("SetUpTestCase", "yes"); }
100  static void TearDownTestCase() { RecordProperty("TearDownTestCase", "aye"); }
101};
102
103TEST_F(PropertyRecordingTest, OneProperty) {
104  RecordProperty("key_1", "1");
105}
106
107TEST_F(PropertyRecordingTest, IntValuedProperty) {
108  RecordProperty("key_int", 1);
109}
110
111TEST_F(PropertyRecordingTest, ThreeProperties) {
112  RecordProperty("key_1", "1");
113  RecordProperty("key_2", "2");
114  RecordProperty("key_3", "3");
115}
116
117TEST_F(PropertyRecordingTest, TwoValuesForOneKeyUsesLastValue) {
118  RecordProperty("key_1", "1");
119  RecordProperty("key_1", "2");
120}
121
122TEST(NoFixtureTest, RecordProperty) {
123  RecordProperty("key", "1");
124}
125
126void ExternalUtilityThatCallsRecordProperty(const std::string& key, int value) {
127  testing::Test::RecordProperty(key, value);
128}
129
130void ExternalUtilityThatCallsRecordProperty(const std::string& key,
131                                            const std::string& value) {
132  testing::Test::RecordProperty(key, value);
133}
134
135TEST(NoFixtureTest, ExternalUtilityThatCallsRecordIntValuedProperty) {
136  ExternalUtilityThatCallsRecordProperty("key_for_utility_int", 1);
137}
138
139TEST(NoFixtureTest, ExternalUtilityThatCallsRecordStringValuedProperty) {
140  ExternalUtilityThatCallsRecordProperty("key_for_utility_string", "1");
141}
142
143// Verifies that the test parameter value is output in the 'value_param'
144// XML attribute for value-parameterized tests.
145class ValueParamTest : public TestWithParam<int> {};
146TEST_P(ValueParamTest, HasValueParamAttribute) {}
147TEST_P(ValueParamTest, AnotherTestThatHasValueParamAttribute) {}
148INSTANTIATE_TEST_CASE_P(Single, ValueParamTest, Values(33, 42));
149
150#if GTEST_HAS_TYPED_TEST
151// Verifies that the type parameter name is output in the 'type_param'
152// XML attribute for typed tests.
153template <typename T> class TypedTest : public Test {};
154typedef testing::Types<int, long> TypedTestTypes;
155TYPED_TEST_CASE(TypedTest, TypedTestTypes);
156TYPED_TEST(TypedTest, HasTypeParamAttribute) {}
157#endif
158
159#if GTEST_HAS_TYPED_TEST_P
160// Verifies that the type parameter name is output in the 'type_param'
161// XML attribute for type-parameterized tests.
162template <typename T> class TypeParameterizedTestCase : public Test {};
163TYPED_TEST_CASE_P(TypeParameterizedTestCase);
164TYPED_TEST_P(TypeParameterizedTestCase, HasTypeParamAttribute) {}
165REGISTER_TYPED_TEST_CASE_P(TypeParameterizedTestCase, HasTypeParamAttribute);
166typedef testing::Types<int, long> TypeParameterizedTestCaseTypes;
167INSTANTIATE_TYPED_TEST_CASE_P(Single,
168                              TypeParameterizedTestCase,
169                              TypeParameterizedTestCaseTypes);
170#endif
171
172int main(int argc, char** argv) {
173  InitGoogleTest(&argc, argv);
174
175  if (argc > 1 && strcmp(argv[1], "--shut_down_xml") == 0) {
176    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
177    delete listeners.Release(listeners.default_xml_generator());
178  }
179  testing::Test::RecordProperty("ad_hoc_property", "42");
180  return RUN_ALL_TESTS();
181}
trunk/3rdparty/googletest/googletest/test/gtest_xml_test_utils.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2006, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Unit test utilities for gtest_xml_output"""
33
34__author__ = 'eefacm@gmail.com (Sean Mcafee)'
35
36import re
37from xml.dom import minidom, Node
38
39import gtest_test_utils
40
41
42GTEST_OUTPUT_FLAG         = '--gtest_output'
43GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
44
45class GTestXMLTestCase(gtest_test_utils.TestCase):
46  """
47  Base class for tests of Google Test's XML output functionality.
48  """
49
50
51  def AssertEquivalentNodes(self, expected_node, actual_node):
52    """
53    Asserts that actual_node (a DOM node object) is equivalent to
54    expected_node (another DOM node object), in that either both of
55    them are CDATA nodes and have the same value, or both are DOM
56    elements and actual_node meets all of the following conditions:
57
58    *  It has the same tag name as expected_node.
59    *  It has the same set of attributes as expected_node, each with
60       the same value as the corresponding attribute of expected_node.
61       Exceptions are any attribute named "time", which needs only be
62       convertible to a floating-point number and any attribute named
63       "type_param" which only has to be non-empty.
64    *  It has an equivalent set of child nodes (including elements and
65       CDATA sections) as expected_node.  Note that we ignore the
66       order of the children as they are not guaranteed to be in any
67       particular order.
68    """
69
70    if expected_node.nodeType == Node.CDATA_SECTION_NODE:
71      self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
72      self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
73      return
74
75    self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
76    self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
77    self.assertEquals(expected_node.tagName, actual_node.tagName)
78
79    expected_attributes = expected_node.attributes
80    actual_attributes   = actual_node  .attributes
81    self.assertEquals(
82        expected_attributes.length, actual_attributes.length,
83        'attribute numbers differ in element %s:\nExpected: %r\nActual: %r' % (
84            actual_node.tagName, expected_attributes.keys(),
85            actual_attributes.keys()))
86    for i in range(expected_attributes.length):
87      expected_attr = expected_attributes.item(i)
88      actual_attr   = actual_attributes.get(expected_attr.name)
89      self.assert_(
90          actual_attr is not None,
91          'expected attribute %s not found in element %s' %
92          (expected_attr.name, actual_node.tagName))
93      self.assertEquals(
94          expected_attr.value, actual_attr.value,
95          ' values of attribute %s in element %s differ: %s vs %s' %
96          (expected_attr.name, actual_node.tagName,
97           expected_attr.value, actual_attr.value))
98
99    expected_children = self._GetChildren(expected_node)
100    actual_children = self._GetChildren(actual_node)
101    self.assertEquals(
102        len(expected_children), len(actual_children),
103        'number of child elements differ in element ' + actual_node.tagName)
104    for child_id, child in expected_children.iteritems():
105      self.assert_(child_id in actual_children,
106                   '<%s> is not in <%s> (in element %s)' %
107                   (child_id, actual_children, actual_node.tagName))
108      self.AssertEquivalentNodes(child, actual_children[child_id])
109
110  identifying_attribute = {
111    'testsuites': 'name',
112    'testsuite': 'name',
113    'testcase':  'name',
114    'failure':   'message',
115    }
116
117  def _GetChildren(self, element):
118    """
119    Fetches all of the child nodes of element, a DOM Element object.
120    Returns them as the values of a dictionary keyed by the IDs of the
121    children.  For <testsuites>, <testsuite> and <testcase> elements, the ID
122    is the value of their "name" attribute; for <failure> elements, it is
123    the value of the "message" attribute; CDATA sections and non-whitespace
124    text nodes are concatenated into a single CDATA section with ID
125    "detail".  An exception is raised if any element other than the above
126    four is encountered, if two child elements with the same identifying
127    attributes are encountered, or if any other type of node is encountered.
128    """
129
130    children = {}
131    for child in element.childNodes:
132      if child.nodeType == Node.ELEMENT_NODE:
133        self.assert_(child.tagName in self.identifying_attribute,
134                     'Encountered unknown element <%s>' % child.tagName)
135        childID = child.getAttribute(self.identifying_attribute[child.tagName])
136        self.assert_(childID not in children)
137        children[childID] = child
138      elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
139        if 'detail' not in children:
140          if (child.nodeType == Node.CDATA_SECTION_NODE or
141              not child.nodeValue.isspace()):
142            children['detail'] = child.ownerDocument.createCDATASection(
143                child.nodeValue)
144        else:
145          children['detail'].nodeValue += child.nodeValue
146      else:
147        self.fail('Encountered unexpected node type %d' % child.nodeType)
148    return children
149
150  def NormalizeXml(self, element):
151    """
152    Normalizes Google Test's XML output to eliminate references to transient
153    information that may change from run to run.
154
155    *  The "time" attribute of <testsuites>, <testsuite> and <testcase>
156       elements is replaced with a single asterisk, if it contains
157       only digit characters.
158    *  The "timestamp" attribute of <testsuites> elements is replaced with a
159       single asterisk, if it contains a valid ISO8601 datetime value.
160    *  The "type_param" attribute of <testcase> elements is replaced with a
161       single asterisk (if it sn non-empty) as it is the type name returned
162       by the compiler and is platform dependent.
163    *  The line info reported in the first line of the "message"
164       attribute and CDATA section of <failure> elements is replaced with the
165       file's basename and a single asterisk for the line number.
166    *  The directory names in file paths are removed.
167    *  The stack traces are removed.
168    """
169
170    if element.tagName == 'testsuites':
171      timestamp = element.getAttributeNode('timestamp')
172      timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$',
173                               '*', timestamp.value)
174    if element.tagName in ('testsuites', 'testsuite', 'testcase'):
175      time = element.getAttributeNode('time')
176      time.value = re.sub(r'^\d+(\.\d+)?$', '*', time.value)
177      type_param = element.getAttributeNode('type_param')
178      if type_param and type_param.value:
179        type_param.value = '*'
180    elif element.tagName == 'failure':
181      source_line_pat = r'^.*[/\\](.*:)\d+\n'
182      # Replaces the source line information with a normalized form.
183      message = element.getAttributeNode('message')
184      message.value = re.sub(source_line_pat, '\\1*\n', message.value)
185      for child in element.childNodes:
186        if child.nodeType == Node.CDATA_SECTION_NODE:
187          # Replaces the source line information with a normalized form.
188          cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue)
189          # Removes the actual stack trace.
190          child.nodeValue = re.sub(r'\nStack trace:\n(.|\n)*',
191                                   '', cdata)
192    for child in element.childNodes:
193      if child.nodeType == Node.ELEMENT_NODE:
194        self.NormalizeXml(child)
trunk/3rdparty/googletest/googletest/test/production.cc
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// This is part of the unit test for include/gtest/gtest_prod.h.
33
34#include "production.h"
35
36PrivateCode::PrivateCode() : x_(0) {}
trunk/3rdparty/googletest/googletest/test/production.h
r0r249096
1// Copyright 2006, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// This is part of the unit test for include/gtest/gtest_prod.h.
33
34#ifndef GTEST_TEST_PRODUCTION_H_
35#define GTEST_TEST_PRODUCTION_H_
36
37#include "gtest/gtest_prod.h"
38
39class PrivateCode {
40 public:
41  // Declares a friend test that does not use a fixture.
42  FRIEND_TEST(PrivateCodeTest, CanAccessPrivateMembers);
43
44  // Declares a friend test that uses a fixture.
45  FRIEND_TEST(PrivateCodeFixtureTest, CanAccessPrivateMembers);
46
47  PrivateCode();
48
49  int x() const { return x_; }
50 private:
51  void set_x(int an_x) { x_ = an_x; }
52  int x_;
53};
54
55#endif  // GTEST_TEST_PRODUCTION_H_
trunk/3rdparty/googletest/googletest/xcode/Config/DebugProject.xcconfig
r0r249096
1//
2//  DebugProject.xcconfig
3//
4//  These are Debug Configuration project settings for the gtest framework and
5//  examples. It is set in the "Based On:" dropdown in the "Project" info
6//  dialog.
7//  This file is based on the Xcode Configuration files in:
8//  http://code.google.com/p/google-toolbox-for-mac/
9//
10
11#include "General.xcconfig"
12
13// No optimization
14GCC_OPTIMIZATION_LEVEL = 0
15
16// Deployment postprocessing is what triggers Xcode to strip, turn it off
17DEPLOYMENT_POSTPROCESSING = NO
18
19// Dead code stripping off
20DEAD_CODE_STRIPPING = NO
21
22// Debug symbols should be on obviously
23GCC_GENERATE_DEBUGGING_SYMBOLS = YES
24
25// Define the DEBUG macro in all debug builds
26OTHER_CFLAGS = $(OTHER_CFLAGS) -DDEBUG=1
27
28// These are turned off to avoid STL incompatibilities with client code
29// // Turns on special C++ STL checks to "encourage" good STL use
30// GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) _GLIBCXX_DEBUG_PEDANTIC _GLIBCXX_DEBUG _GLIBCPP_CONCEPT_CHECKS
trunk/3rdparty/googletest/googletest/xcode/Config/FrameworkTarget.xcconfig
r0r249096
1//
2//  FrameworkTarget.xcconfig
3//
4//  These are Framework target settings for the gtest framework and examples. It
5//  is set in the "Based On:" dropdown in the "Target" info dialog.
6//  This file is based on the Xcode Configuration files in:
7//  http://code.google.com/p/google-toolbox-for-mac/
8//
9
10// Dynamic libs need to be position independent
11GCC_DYNAMIC_NO_PIC = NO
12
13// Dynamic libs should not have their external symbols stripped.
14STRIP_STYLE = non-global
15
16// Let the user install by specifying the $DSTROOT with xcodebuild
17SKIP_INSTALL = NO
trunk/3rdparty/googletest/googletest/xcode/Config/General.xcconfig
r0r249096
1//
2//  General.xcconfig
3//
4//  These are General configuration settings for the gtest framework and
5//  examples.
6//  This file is based on the Xcode Configuration files in:
7//  http://code.google.com/p/google-toolbox-for-mac/
8//
9
10// Build for PPC and Intel, 32- and 64-bit
11ARCHS = i386 x86_64 ppc ppc64
12
13// Zerolink prevents link warnings so turn it off
14ZERO_LINK = NO
15
16// Prebinding considered unhelpful in 10.3 and later
17PREBINDING = NO
18
19// Strictest warning policy
20WARNING_CFLAGS = -Wall -Werror -Wendif-labels -Wnewline-eof -Wno-sign-compare -Wshadow
21
22// Work around Xcode bugs by using external strip. See:
23// http://lists.apple.com/archives/Xcode-users/2006/Feb/msg00050.html
24SEPARATE_STRIP = YES
25
26// Force C99 dialect
27GCC_C_LANGUAGE_STANDARD = c99
28
29// not sure why apple defaults this on, but it's pretty risky
30ALWAYS_SEARCH_USER_PATHS = NO
31
32// Turn on position dependent code for most cases (overridden where appropriate)
33GCC_DYNAMIC_NO_PIC = YES
34
35// Default SDK and minimum OS version is 10.4
36SDKROOT = $(DEVELOPER_SDK_DIR)/MacOSX10.4u.sdk
37MACOSX_DEPLOYMENT_TARGET = 10.4
38GCC_VERSION = 4.0
39
40// VERSIONING BUILD SETTINGS (used in Info.plist)
41GTEST_VERSIONINFO_ABOUT =  © 2008 Google Inc.
trunk/3rdparty/googletest/googletest/xcode/Config/ReleaseProject.xcconfig
r0r249096
1//
2//  ReleaseProject.xcconfig
3//
4//  These are Release Configuration project settings for the gtest framework
5//  and examples. It is set in the "Based On:" dropdown in the "Project" info
6//  dialog.
7//  This file is based on the Xcode Configuration files in:
8//  http://code.google.com/p/google-toolbox-for-mac/
9//
10
11#include "General.xcconfig"
12
13// subconfig/Release.xcconfig
14
15// Optimize for space and size (Apple recommendation)
16GCC_OPTIMIZATION_LEVEL = s
17
18// Deploment postprocessing is what triggers Xcode to strip
19DEPLOYMENT_POSTPROCESSING = YES
20
21// No symbols
22GCC_GENERATE_DEBUGGING_SYMBOLS = NO
23
24// Dead code strip does not affect ObjC code but can help for C
25DEAD_CODE_STRIPPING = YES
26
27// NDEBUG is used by things like assert.h, so define it for general compat.
28// ASSERT going away in release tends to create unused vars.
29OTHER_CFLAGS = $(OTHER_CFLAGS) -DNDEBUG=1 -Wno-unused-variable
30
31// When we strip we want to strip all symbols in release, but save externals.
32STRIP_STYLE = all
trunk/3rdparty/googletest/googletest/xcode/Config/StaticLibraryTarget.xcconfig
r0r249096
1//
2//  StaticLibraryTarget.xcconfig
3//
4//  These are static library target settings for libgtest.a. It
5//  is set in the "Based On:" dropdown in the "Target" info dialog.
6//  This file is based on the Xcode Configuration files in:
7//  http://code.google.com/p/google-toolbox-for-mac/
8//
9
10// Static libs can be included in bundles so make them position independent
11GCC_DYNAMIC_NO_PIC = NO
12
13// Static libs should not have their internal globals or external symbols
14// stripped.
15STRIP_STYLE = debugging
16
17// Let the user install by specifying the $DSTROOT with xcodebuild
18SKIP_INSTALL = NO
trunk/3rdparty/googletest/googletest/xcode/Config/TestTarget.xcconfig
r0r249096
1//
2//  TestTarget.xcconfig
3//
4//  These are Test target settings for the gtest framework and examples. It
5//  is set in the "Based On:" dropdown in the "Target" info dialog.
6
7PRODUCT_NAME = $(TARGET_NAME)
8HEADER_SEARCH_PATHS = ../include
trunk/3rdparty/googletest/googletest/xcode/Resources/Info.plist
r0r249096
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3<plist version="1.0">
4<dict>
5   <key>CFBundleDevelopmentRegion</key>
6   <string>English</string>
7   <key>CFBundleExecutable</key>
8   <string>${EXECUTABLE_NAME}</string>
9   <key>CFBundleIconFile</key>
10   <string></string>
11   <key>CFBundleIdentifier</key>
12   <string>com.google.${PRODUCT_NAME}</string>
13   <key>CFBundleInfoDictionaryVersion</key>
14   <string>6.0</string>
15   <key>CFBundlePackageType</key>
16   <string>FMWK</string>
17   <key>CFBundleSignature</key>
18   <string>????</string>
19   <key>CFBundleVersion</key>
20   <string>GTEST_VERSIONINFO_LONG</string>
21   <key>CFBundleShortVersionString</key>
22   <string>GTEST_VERSIONINFO_SHORT</string>
23   <key>CFBundleGetInfoString</key>
24   <string>${PRODUCT_NAME} GTEST_VERSIONINFO_LONG, ${GTEST_VERSIONINFO_ABOUT}</string>
25   <key>NSHumanReadableCopyright</key>
26   <string>${GTEST_VERSIONINFO_ABOUT}</string>
27   <key>CSResourcesFileMapped</key>
28   <true/>
29</dict>
30</plist>
trunk/3rdparty/googletest/googletest/xcode/Samples/FrameworkSample/Info.plist
r0r249096
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3<plist version="1.0">
4<dict>
5   <key>CFBundleDevelopmentRegion</key>
6   <string>English</string>
7   <key>CFBundleExecutable</key>
8   <string>${EXECUTABLE_NAME}</string>
9   <key>CFBundleIconFile</key>
10   <string></string>
11   <key>CFBundleIdentifier</key>
12   <string>com.google.gtest.${PRODUCT_NAME:identifier}</string>
13   <key>CFBundleInfoDictionaryVersion</key>
14   <string>6.0</string>
15   <key>CFBundleName</key>
16   <string>${PRODUCT_NAME}</string>
17   <key>CFBundlePackageType</key>
18   <string>FMWK</string>
19   <key>CFBundleShortVersionString</key>
20   <string>1.0</string>
21   <key>CFBundleSignature</key>
22   <string>????</string>
23   <key>CFBundleVersion</key>
24   <string>1.0</string>
25   <key>CSResourcesFileMapped</key>
26   <true/>
27</dict>
28</plist>
trunk/3rdparty/googletest/googletest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj
r0r249096
1// !$*UTF8*$!
2{
3   archiveVersion = 1;
4   classes = {
5   };
6   objectVersion = 42;
7   objects = {
8
9/* Begin PBXAggregateTarget section */
10      4024D162113D7D2400C7059E /* Test */ = {
11         isa = PBXAggregateTarget;
12         buildConfigurationList = 4024D169113D7D4600C7059E /* Build configuration list for PBXAggregateTarget "Test" */;
13         buildPhases = (
14            4024D161113D7D2400C7059E /* ShellScript */,
15         );
16         dependencies = (
17            4024D166113D7D3100C7059E /* PBXTargetDependency */,
18         );
19         name = Test;
20         productName = TestAndBuild;
21      };
22      4024D1E9113D83FF00C7059E /* TestAndBuild */ = {
23         isa = PBXAggregateTarget;
24         buildConfigurationList = 4024D1F0113D842B00C7059E /* Build configuration list for PBXAggregateTarget "TestAndBuild" */;
25         buildPhases = (
26         );
27         dependencies = (
28            4024D1ED113D840900C7059E /* PBXTargetDependency */,
29            4024D1EF113D840D00C7059E /* PBXTargetDependency */,
30         );
31         name = TestAndBuild;
32         productName = TestAndBuild;
33      };
34/* End PBXAggregateTarget section */
35
36/* Begin PBXBuildFile section */
37      3B7EB1250E5AEE3500C7F239 /* widget.cc in Sources */ = {isa = PBXBuildFile; fileRef = 3B7EB1230E5AEE3500C7F239 /* widget.cc */; };
38      3B7EB1260E5AEE3500C7F239 /* widget.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B7EB1240E5AEE3500C7F239 /* widget.h */; settings = {ATTRIBUTES = (Public, ); }; };
39      3B7EB1280E5AEE4600C7F239 /* widget_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 3B7EB1270E5AEE4600C7F239 /* widget_test.cc */; };
40      3B7EB1480E5AF3B400C7F239 /* Widget.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D07F2C80486CC7A007CD1D0 /* Widget.framework */; };
41      4024D188113D7D7800C7059E /* libgtest.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4024D185113D7D5500C7059E /* libgtest.a */; };
42      4024D189113D7D7A00C7059E /* libgtest_main.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4024D183113D7D5500C7059E /* libgtest_main.a */; };
43/* End PBXBuildFile section */
44
45/* Begin PBXContainerItemProxy section */
46      3B07BDF00E3F3FAE00647869 /* PBXContainerItemProxy */ = {
47         isa = PBXContainerItemProxy;
48         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
49         proxyType = 1;
50         remoteGlobalIDString = 8D07F2BC0486CC7A007CD1D0;
51         remoteInfo = gTestExample;
52      };
53      4024D165113D7D3100C7059E /* PBXContainerItemProxy */ = {
54         isa = PBXContainerItemProxy;
55         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
56         proxyType = 1;
57         remoteGlobalIDString = 3B07BDE90E3F3F9E00647869;
58         remoteInfo = WidgetFrameworkTest;
59      };
60      4024D1EC113D840900C7059E /* PBXContainerItemProxy */ = {
61         isa = PBXContainerItemProxy;
62         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
63         proxyType = 1;
64         remoteGlobalIDString = 8D07F2BC0486CC7A007CD1D0;
65         remoteInfo = WidgetFramework;
66      };
67      4024D1EE113D840D00C7059E /* PBXContainerItemProxy */ = {
68         isa = PBXContainerItemProxy;
69         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
70         proxyType = 1;
71         remoteGlobalIDString = 4024D162113D7D2400C7059E;
72         remoteInfo = Test;
73      };
74/* End PBXContainerItemProxy section */
75
76/* Begin PBXFileReference section */
77      3B07BDEA0E3F3F9E00647869 /* WidgetFrameworkTest */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = WidgetFrameworkTest; sourceTree = BUILT_PRODUCTS_DIR; };
78      3B7EB1230E5AEE3500C7F239 /* widget.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = widget.cc; sourceTree = "<group>"; };
79      3B7EB1240E5AEE3500C7F239 /* widget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = widget.h; sourceTree = "<group>"; };
80      3B7EB1270E5AEE4600C7F239 /* widget_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = widget_test.cc; sourceTree = "<group>"; };
81      4024D183113D7D5500C7059E /* libgtest_main.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libgtest_main.a; path = /usr/local/lib/libgtest_main.a; sourceTree = "<absolute>"; };
82      4024D185113D7D5500C7059E /* libgtest.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libgtest.a; path = /usr/local/lib/libgtest.a; sourceTree = "<absolute>"; };
83      4024D1E2113D838200C7059E /* runtests.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; path = runtests.sh; sourceTree = "<group>"; };
84      8D07F2C70486CC7A007CD1D0 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
85      8D07F2C80486CC7A007CD1D0 /* Widget.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Widget.framework; sourceTree = BUILT_PRODUCTS_DIR; };
86/* End PBXFileReference section */
87
88/* Begin PBXFrameworksBuildPhase section */
89      3B07BDE80E3F3F9E00647869 /* Frameworks */ = {
90         isa = PBXFrameworksBuildPhase;
91         buildActionMask = 2147483647;
92         files = (
93            4024D189113D7D7A00C7059E /* libgtest_main.a in Frameworks */,
94            4024D188113D7D7800C7059E /* libgtest.a in Frameworks */,
95            3B7EB1480E5AF3B400C7F239 /* Widget.framework in Frameworks */,
96         );
97         runOnlyForDeploymentPostprocessing = 0;
98      };
99      8D07F2C30486CC7A007CD1D0 /* Frameworks */ = {
100         isa = PBXFrameworksBuildPhase;
101         buildActionMask = 2147483647;
102         files = (
103         );
104         runOnlyForDeploymentPostprocessing = 0;
105      };
106/* End PBXFrameworksBuildPhase section */
107
108/* Begin PBXGroup section */
109      034768DDFF38A45A11DB9C8B /* Products */ = {
110         isa = PBXGroup;
111         children = (
112            8D07F2C80486CC7A007CD1D0 /* Widget.framework */,
113            3B07BDEA0E3F3F9E00647869 /* WidgetFrameworkTest */,
114         );
115         name = Products;
116         sourceTree = "<group>";
117      };
118      0867D691FE84028FC02AAC07 /* gTestExample */ = {
119         isa = PBXGroup;
120         children = (
121            4024D1E1113D836C00C7059E /* Scripts */,
122            08FB77ACFE841707C02AAC07 /* Source */,
123            089C1665FE841158C02AAC07 /* Resources */,
124            3B07BE350E4094E400647869 /* Test */,
125            0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */,
126            034768DDFF38A45A11DB9C8B /* Products */,
127         );
128         name = gTestExample;
129         sourceTree = "<group>";
130      };
131      0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */ = {
132         isa = PBXGroup;
133         children = (
134            4024D183113D7D5500C7059E /* libgtest_main.a */,
135            4024D185113D7D5500C7059E /* libgtest.a */,
136         );
137         name = "External Frameworks and Libraries";
138         sourceTree = "<group>";
139      };
140      089C1665FE841158C02AAC07 /* Resources */ = {
141         isa = PBXGroup;
142         children = (
143            8D07F2C70486CC7A007CD1D0 /* Info.plist */,
144         );
145         name = Resources;
146         sourceTree = "<group>";
147      };
148      08FB77ACFE841707C02AAC07 /* Source */ = {
149         isa = PBXGroup;
150         children = (
151            3B7EB1230E5AEE3500C7F239 /* widget.cc */,
152            3B7EB1240E5AEE3500C7F239 /* widget.h */,
153         );
154         name = Source;
155         sourceTree = "<group>";
156      };
157      3B07BE350E4094E400647869 /* Test */ = {
158         isa = PBXGroup;
159         children = (
160            3B7EB1270E5AEE4600C7F239 /* widget_test.cc */,
161         );
162         name = Test;
163         sourceTree = "<group>";
164      };
165      4024D1E1113D836C00C7059E /* Scripts */ = {
166         isa = PBXGroup;
167         children = (
168            4024D1E2113D838200C7059E /* runtests.sh */,
169         );
170         name = Scripts;
171         sourceTree = "<group>";
172      };
173/* End PBXGroup section */
174
175/* Begin PBXHeadersBuildPhase section */
176      8D07F2BD0486CC7A007CD1D0 /* Headers */ = {
177         isa = PBXHeadersBuildPhase;
178         buildActionMask = 2147483647;
179         files = (
180            3B7EB1260E5AEE3500C7F239 /* widget.h in Headers */,
181         );
182         runOnlyForDeploymentPostprocessing = 0;
183      };
184/* End PBXHeadersBuildPhase section */
185
186/* Begin PBXNativeTarget section */
187      3B07BDE90E3F3F9E00647869 /* WidgetFrameworkTest */ = {
188         isa = PBXNativeTarget;
189         buildConfigurationList = 3B07BDF40E3F3FB600647869 /* Build configuration list for PBXNativeTarget "WidgetFrameworkTest" */;
190         buildPhases = (
191            3B07BDE70E3F3F9E00647869 /* Sources */,
192            3B07BDE80E3F3F9E00647869 /* Frameworks */,
193         );
194         buildRules = (
195         );
196         dependencies = (
197            3B07BDF10E3F3FAE00647869 /* PBXTargetDependency */,
198         );
199         name = WidgetFrameworkTest;
200         productName = gTestExampleTest;
201         productReference = 3B07BDEA0E3F3F9E00647869 /* WidgetFrameworkTest */;
202         productType = "com.apple.product-type.tool";
203      };
204      8D07F2BC0486CC7A007CD1D0 /* WidgetFramework */ = {
205         isa = PBXNativeTarget;
206         buildConfigurationList = 4FADC24208B4156D00ABE55E /* Build configuration list for PBXNativeTarget "WidgetFramework" */;
207         buildPhases = (
208            8D07F2C10486CC7A007CD1D0 /* Sources */,
209            8D07F2C30486CC7A007CD1D0 /* Frameworks */,
210            8D07F2BD0486CC7A007CD1D0 /* Headers */,
211            8D07F2BF0486CC7A007CD1D0 /* Resources */,
212            8D07F2C50486CC7A007CD1D0 /* Rez */,
213         );
214         buildRules = (
215         );
216         dependencies = (
217         );
218         name = WidgetFramework;
219         productInstallPath = "$(HOME)/Library/Frameworks";
220         productName = gTestExample;
221         productReference = 8D07F2C80486CC7A007CD1D0 /* Widget.framework */;
222         productType = "com.apple.product-type.framework";
223      };
224/* End PBXNativeTarget section */
225
226/* Begin PBXProject section */
227      0867D690FE84028FC02AAC07 /* Project object */ = {
228         isa = PBXProject;
229         buildConfigurationList = 4FADC24608B4156D00ABE55E /* Build configuration list for PBXProject "WidgetFramework" */;
230         compatibilityVersion = "Xcode 2.4";
231         hasScannedForEncodings = 1;
232         mainGroup = 0867D691FE84028FC02AAC07 /* gTestExample */;
233         productRefGroup = 034768DDFF38A45A11DB9C8B /* Products */;
234         projectDirPath = "";
235         projectRoot = "";
236         targets = (
237            8D07F2BC0486CC7A007CD1D0 /* WidgetFramework */,
238            3B07BDE90E3F3F9E00647869 /* WidgetFrameworkTest */,
239            4024D162113D7D2400C7059E /* Test */,
240            4024D1E9113D83FF00C7059E /* TestAndBuild */,
241         );
242      };
243/* End PBXProject section */
244
245/* Begin PBXResourcesBuildPhase section */
246      8D07F2BF0486CC7A007CD1D0 /* Resources */ = {
247         isa = PBXResourcesBuildPhase;
248         buildActionMask = 2147483647;
249         files = (
250         );
251         runOnlyForDeploymentPostprocessing = 0;
252      };
253/* End PBXResourcesBuildPhase section */
254
255/* Begin PBXRezBuildPhase section */
256      8D07F2C50486CC7A007CD1D0 /* Rez */ = {
257         isa = PBXRezBuildPhase;
258         buildActionMask = 2147483647;
259         files = (
260         );
261         runOnlyForDeploymentPostprocessing = 0;
262      };
263/* End PBXRezBuildPhase section */
264
265/* Begin PBXShellScriptBuildPhase section */
266      4024D161113D7D2400C7059E /* ShellScript */ = {
267         isa = PBXShellScriptBuildPhase;
268         buildActionMask = 2147483647;
269         files = (
270         );
271         inputPaths = (
272         );
273         outputPaths = (
274         );
275         runOnlyForDeploymentPostprocessing = 0;
276         shellPath = /bin/sh;
277         shellScript = "/bin/bash $SRCROOT/runtests.sh $BUILT_PRODUCTS_DIR/WidgetFrameworkTest\n";
278      };
279/* End PBXShellScriptBuildPhase section */
280
281/* Begin PBXSourcesBuildPhase section */
282      3B07BDE70E3F3F9E00647869 /* Sources */ = {
283         isa = PBXSourcesBuildPhase;
284         buildActionMask = 2147483647;
285         files = (
286            3B7EB1280E5AEE4600C7F239 /* widget_test.cc in Sources */,
287         );
288         runOnlyForDeploymentPostprocessing = 0;
289      };
290      8D07F2C10486CC7A007CD1D0 /* Sources */ = {
291         isa = PBXSourcesBuildPhase;
292         buildActionMask = 2147483647;
293         files = (
294            3B7EB1250E5AEE3500C7F239 /* widget.cc in Sources */,
295         );
296         runOnlyForDeploymentPostprocessing = 0;
297      };
298/* End PBXSourcesBuildPhase section */
299
300/* Begin PBXTargetDependency section */
301      3B07BDF10E3F3FAE00647869 /* PBXTargetDependency */ = {
302         isa = PBXTargetDependency;
303         target = 8D07F2BC0486CC7A007CD1D0 /* WidgetFramework */;
304         targetProxy = 3B07BDF00E3F3FAE00647869 /* PBXContainerItemProxy */;
305      };
306      4024D166113D7D3100C7059E /* PBXTargetDependency */ = {
307         isa = PBXTargetDependency;
308         target = 3B07BDE90E3F3F9E00647869 /* WidgetFrameworkTest */;
309         targetProxy = 4024D165113D7D3100C7059E /* PBXContainerItemProxy */;
310      };
311      4024D1ED113D840900C7059E /* PBXTargetDependency */ = {
312         isa = PBXTargetDependency;
313         target = 8D07F2BC0486CC7A007CD1D0 /* WidgetFramework */;
314         targetProxy = 4024D1EC113D840900C7059E /* PBXContainerItemProxy */;
315      };
316      4024D1EF113D840D00C7059E /* PBXTargetDependency */ = {
317         isa = PBXTargetDependency;
318         target = 4024D162113D7D2400C7059E /* Test */;
319         targetProxy = 4024D1EE113D840D00C7059E /* PBXContainerItemProxy */;
320      };
321/* End PBXTargetDependency section */
322
323/* Begin XCBuildConfiguration section */
324      3B07BDEC0E3F3F9F00647869 /* Debug */ = {
325         isa = XCBuildConfiguration;
326         buildSettings = {
327            PRODUCT_NAME = WidgetFrameworkTest;
328         };
329         name = Debug;
330      };
331      3B07BDED0E3F3F9F00647869 /* Release */ = {
332         isa = XCBuildConfiguration;
333         buildSettings = {
334            PRODUCT_NAME = WidgetFrameworkTest;
335         };
336         name = Release;
337      };
338      4024D163113D7D2400C7059E /* Debug */ = {
339         isa = XCBuildConfiguration;
340         buildSettings = {
341            PRODUCT_NAME = TestAndBuild;
342         };
343         name = Debug;
344      };
345      4024D164113D7D2400C7059E /* Release */ = {
346         isa = XCBuildConfiguration;
347         buildSettings = {
348            PRODUCT_NAME = TestAndBuild;
349         };
350         name = Release;
351      };
352      4024D1EA113D83FF00C7059E /* Debug */ = {
353         isa = XCBuildConfiguration;
354         buildSettings = {
355            PRODUCT_NAME = TestAndBuild;
356         };
357         name = Debug;
358      };
359      4024D1EB113D83FF00C7059E /* Release */ = {
360         isa = XCBuildConfiguration;
361         buildSettings = {
362            PRODUCT_NAME = TestAndBuild;
363         };
364         name = Release;
365      };
366      4FADC24308B4156D00ABE55E /* Debug */ = {
367         isa = XCBuildConfiguration;
368         buildSettings = {
369            DYLIB_COMPATIBILITY_VERSION = 1;
370            DYLIB_CURRENT_VERSION = 1;
371            FRAMEWORK_VERSION = A;
372            INFOPLIST_FILE = Info.plist;
373            INSTALL_PATH = "@loader_path/../Frameworks";
374            PRODUCT_NAME = Widget;
375         };
376         name = Debug;
377      };
378      4FADC24408B4156D00ABE55E /* Release */ = {
379         isa = XCBuildConfiguration;
380         buildSettings = {
381            DYLIB_COMPATIBILITY_VERSION = 1;
382            DYLIB_CURRENT_VERSION = 1;
383            FRAMEWORK_VERSION = A;
384            INFOPLIST_FILE = Info.plist;
385            INSTALL_PATH = "@loader_path/../Frameworks";
386            PRODUCT_NAME = Widget;
387         };
388         name = Release;
389      };
390      4FADC24708B4156D00ABE55E /* Debug */ = {
391         isa = XCBuildConfiguration;
392         buildSettings = {
393            GCC_VERSION = 4.0;
394            SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
395         };
396         name = Debug;
397      };
398      4FADC24808B4156D00ABE55E /* Release */ = {
399         isa = XCBuildConfiguration;
400         buildSettings = {
401            GCC_VERSION = 4.0;
402            SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
403         };
404         name = Release;
405      };
406/* End XCBuildConfiguration section */
407
408/* Begin XCConfigurationList section */
409      3B07BDF40E3F3FB600647869 /* Build configuration list for PBXNativeTarget "WidgetFrameworkTest" */ = {
410         isa = XCConfigurationList;
411         buildConfigurations = (
412            3B07BDEC0E3F3F9F00647869 /* Debug */,
413            3B07BDED0E3F3F9F00647869 /* Release */,
414         );
415         defaultConfigurationIsVisible = 0;
416         defaultConfigurationName = Release;
417      };
418      4024D169113D7D4600C7059E /* Build configuration list for PBXAggregateTarget "Test" */ = {
419         isa = XCConfigurationList;
420         buildConfigurations = (
421            4024D163113D7D2400C7059E /* Debug */,
422            4024D164113D7D2400C7059E /* Release */,
423         );
424         defaultConfigurationIsVisible = 0;
425         defaultConfigurationName = Release;
426      };
427      4024D1F0113D842B00C7059E /* Build configuration list for PBXAggregateTarget "TestAndBuild" */ = {
428         isa = XCConfigurationList;
429         buildConfigurations = (
430            4024D1EA113D83FF00C7059E /* Debug */,
431            4024D1EB113D83FF00C7059E /* Release */,
432         );
433         defaultConfigurationIsVisible = 0;
434         defaultConfigurationName = Release;
435      };
436      4FADC24208B4156D00ABE55E /* Build configuration list for PBXNativeTarget "WidgetFramework" */ = {
437         isa = XCConfigurationList;
438         buildConfigurations = (
439            4FADC24308B4156D00ABE55E /* Debug */,
440            4FADC24408B4156D00ABE55E /* Release */,
441         );
442         defaultConfigurationIsVisible = 0;
443         defaultConfigurationName = Release;
444      };
445      4FADC24608B4156D00ABE55E /* Build configuration list for PBXProject "WidgetFramework" */ = {
446         isa = XCConfigurationList;
447         buildConfigurations = (
448            4FADC24708B4156D00ABE55E /* Debug */,
449            4FADC24808B4156D00ABE55E /* Release */,
450         );
451         defaultConfigurationIsVisible = 0;
452         defaultConfigurationName = Release;
453      };
454/* End XCConfigurationList section */
455   };
456   rootObject = 0867D690FE84028FC02AAC07 /* Project object */;
457}
trunk/3rdparty/googletest/googletest/xcode/Samples/FrameworkSample/runtests.sh
r0r249096
1#!/bin/bash
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32# Executes the samples and tests for the Google Test Framework.
33
34# Help the dynamic linker find the path to the libraries.
35export DYLD_FRAMEWORK_PATH=$BUILT_PRODUCTS_DIR
36export DYLD_LIBRARY_PATH=$BUILT_PRODUCTS_DIR
37
38# Create some executables.
39test_executables=$@
40
41# Now execute each one in turn keeping track of how many succeeded and failed.
42succeeded=0
43failed=0
44failed_list=()
45for test in ${test_executables[*]}; do
46  "$test"
47  result=$?
48  if [ $result -eq 0 ]; then
49    succeeded=$(( $succeeded + 1 ))
50  else
51    failed=$(( failed + 1 ))
52    failed_list="$failed_list $test"
53  fi
54done
55
56# Report the successes and failures to the console.
57echo "Tests complete with $succeeded successes and $failed failures."
58if [ $failed -ne 0 ]; then
59  echo "The following tests failed:"
60  echo $failed_list
61fi
62exit $failed
trunk/3rdparty/googletest/googletest/xcode/Samples/FrameworkSample/widget.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: preston.a.jackson@gmail.com (Preston Jackson)
31//
32// Google Test - FrameworkSample
33// widget.cc
34//
35
36// Widget is a very simple class used for demonstrating the use of gtest
37
38#include "widget.h"
39
40Widget::Widget(int number, const std::string& name)
41    : number_(number),
42      name_(name) {}
43
44Widget::~Widget() {}
45
46float Widget::GetFloatValue() const {
47  return number_;
48}
49
50int Widget::GetIntValue() const {
51  return static_cast<int>(number_);
52}
53
54std::string Widget::GetStringValue() const {
55  return name_;
56}
57
58void Widget::GetCharPtrValue(char* buffer, size_t max_size) const {
59  // Copy the char* representation of name_ into buffer, up to max_size.
60  strncpy(buffer, name_.c_str(), max_size-1);
61  buffer[max_size-1] = '\0';
62  return;
63}
trunk/3rdparty/googletest/googletest/xcode/Samples/FrameworkSample/widget.h
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: preston.a.jackson@gmail.com (Preston Jackson)
31//
32// Google Test - FrameworkSample
33// widget.h
34//
35
36// Widget is a very simple class used for demonstrating the use of gtest. It
37// simply stores two values a string and an integer, which are returned via
38// public accessors in multiple forms.
39
40#import <string>
41
42class Widget {
43 public:
44  Widget(int number, const std::string& name);
45  ~Widget();
46
47  // Public accessors to number data
48  float GetFloatValue() const;
49  int GetIntValue() const;
50
51  // Public accessors to the string data
52  std::string GetStringValue() const;
53  void GetCharPtrValue(char* buffer, size_t max_size) const;
54
55 private:
56  // Data members
57  float number_;
58  std::string name_;
59};
trunk/3rdparty/googletest/googletest/xcode/Samples/FrameworkSample/widget_test.cc
r0r249096
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: preston.a.jackson@gmail.com (Preston Jackson)
31//
32// Google Test - FrameworkSample
33// widget_test.cc
34//
35
36// This is a simple test file for the Widget class in the Widget.framework
37
38#include <string>
39#include "gtest/gtest.h"
40
41#include <Widget/widget.h>
42
43// This test verifies that the constructor sets the internal state of the
44// Widget class correctly.
45TEST(WidgetInitializerTest, TestConstructor) {
46  Widget widget(1.0f, "name");
47  EXPECT_FLOAT_EQ(1.0f, widget.GetFloatValue());
48  EXPECT_EQ(std::string("name"), widget.GetStringValue());
49}
50
51// This test verifies the conversion of the float and string values to int and
52// char*, respectively.
53TEST(WidgetInitializerTest, TestConversion) {
54  Widget widget(1.0f, "name");
55  EXPECT_EQ(1, widget.GetIntValue());
56
57  size_t max_size = 128;
58  char buffer[max_size];
59  widget.GetCharPtrValue(buffer, max_size);
60  EXPECT_STREQ("name", buffer);
61}
62
63// Use the Google Test main that is linked into the framework. It does something
64// like this:
65// int main(int argc, char** argv) {
66//   testing::InitGoogleTest(&argc, argv);
67//   return RUN_ALL_TESTS();
68// }
trunk/3rdparty/googletest/googletest/xcode/Scripts/runtests.sh
r0r249096
1#!/bin/bash
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32# Executes the samples and tests for the Google Test Framework.
33
34# Help the dynamic linker find the path to the libraries.
35export DYLD_FRAMEWORK_PATH=$BUILT_PRODUCTS_DIR
36export DYLD_LIBRARY_PATH=$BUILT_PRODUCTS_DIR
37
38# Create some executables.
39test_executables=("$BUILT_PRODUCTS_DIR/gtest_unittest-framework"
40                  "$BUILT_PRODUCTS_DIR/gtest_unittest"
41                  "$BUILT_PRODUCTS_DIR/sample1_unittest-framework"
42                  "$BUILT_PRODUCTS_DIR/sample1_unittest-static")
43
44# Now execute each one in turn keeping track of how many succeeded and failed.
45succeeded=0
46failed=0
47failed_list=()
48for test in ${test_executables[*]}; do
49  "$test"
50  result=$?
51  if [ $result -eq 0 ]; then
52    succeeded=$(( $succeeded + 1 ))
53  else
54    failed=$(( failed + 1 ))
55    failed_list="$failed_list $test"
56  fi
57done
58
59# Report the successes and failures to the console.
60echo "Tests complete with $succeeded successes and $failed failures."
61if [ $failed -ne 0 ]; then
62  echo "The following tests failed:"
63  echo $failed_list
64fi
65exit $failed
trunk/3rdparty/googletest/googletest/xcode/Scripts/versiongenerate.py
r0r249096
1#!/usr/bin/env python
2#
3# Copyright 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#     * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#     * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#     * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""A script to prepare version informtion for use the gtest Info.plist file.
33
34  This script extracts the version information from the configure.ac file and
35  uses it to generate a header file containing the same information. The
36  #defines in this header file will be included in during the generation of
37  the Info.plist of the framework, giving the correct value to the version
38  shown in the Finder.
39
40  This script makes the following assumptions (these are faults of the script,
41  not problems with the Autoconf):
42    1. The AC_INIT macro will be contained within the first 1024 characters
43       of configure.ac
44    2. The version string will be 3 integers separated by periods and will be
45       surrounded by squre brackets, "[" and "]" (e.g. [1.0.1]). The first
46       segment represents the major version, the second represents the minor
47       version and the third represents the fix version.
48    3. No ")" character exists between the opening "(" and closing ")" of
49       AC_INIT, including in comments and character strings.
50"""
51
52import sys
53import re
54
55# Read the command line argument (the output directory for Version.h)
56if (len(sys.argv) < 3):
57  print "Usage: versiongenerate.py input_dir output_dir"
58  sys.exit(1)
59else:
60  input_dir = sys.argv[1]
61  output_dir = sys.argv[2]
62
63# Read the first 1024 characters of the configure.ac file
64config_file = open("%s/configure.ac" % input_dir, 'r')
65buffer_size = 1024
66opening_string = config_file.read(buffer_size)
67config_file.close()
68
69# Extract the version string from the AC_INIT macro
70#   The following init_expression means:
71#     Extract three integers separated by periods and surrounded by squre
72#     brackets(e.g. "[1.0.1]") between "AC_INIT(" and ")". Do not be greedy
73#     (*? is the non-greedy flag) since that would pull in everything between
74#     the first "(" and the last ")" in the file.
75version_expression = re.compile(r"AC_INIT\(.*?\[(\d+)\.(\d+)\.(\d+)\].*?\)",
76                                re.DOTALL)
77version_values = version_expression.search(opening_string)
78major_version = version_values.group(1)
79minor_version = version_values.group(2)
80fix_version = version_values.group(3)
81
82# Write the version information to a header file to be included in the
83# Info.plist file.
84file_data = """//
85// DO NOT MODIFY THIS FILE (but you can delete it)
86//
87// This file is autogenerated by the versiongenerate.py script. This script
88// is executed in a "Run Script" build phase when creating gtest.framework. This
89// header file is not used during compilation of C-source. Rather, it simply
90// defines some version strings for substitution in the Info.plist. Because of
91// this, we are not not restricted to C-syntax nor are we using include guards.
92//
93
94#define GTEST_VERSIONINFO_SHORT %s.%s
95#define GTEST_VERSIONINFO_LONG %s.%s.%s
96
97""" % (major_version, minor_version, major_version, minor_version, fix_version)
98version_file = open("%s/Version.h" % output_dir, 'w')
99version_file.write(file_data)
100version_file.close()
trunk/3rdparty/googletest/googletest/xcode/gtest.xcodeproj/project.pbxproj
r0r249096
1// !$*UTF8*$!
2{
3   archiveVersion = 1;
4   classes = {
5   };
6   objectVersion = 46;
7   objects = {
8
9/* Begin PBXAggregateTarget section */
10      3B238F5F0E828B5400846E11 /* Check */ = {
11         isa = PBXAggregateTarget;
12         buildConfigurationList = 3B238FA30E828BB600846E11 /* Build configuration list for PBXAggregateTarget "Check" */;
13         buildPhases = (
14            3B238F5E0E828B5400846E11 /* ShellScript */,
15         );
16         dependencies = (
17            40899F9D0FFA740F000B29AE /* PBXTargetDependency */,
18            40C849F7101A43440083642A /* PBXTargetDependency */,
19            4089A0980FFAD34A000B29AE /* PBXTargetDependency */,
20            40C849F9101A43490083642A /* PBXTargetDependency */,
21         );
22         name = Check;
23         productName = Check;
24      };
25      40C44ADC0E3798F4008FCC51 /* Version Info */ = {
26         isa = PBXAggregateTarget;
27         buildConfigurationList = 40C44AE40E379905008FCC51 /* Build configuration list for PBXAggregateTarget "Version Info" */;
28         buildPhases = (
29            40C44ADB0E3798F4008FCC51 /* Generate Version.h */,
30         );
31         comments = "The generation of Version.h must be performed in its own target. Since the Info.plist is preprocessed before any of the other build phases in gtest, the Version.h file would not be ready if included as a build phase of that target.";
32         dependencies = (
33         );
34         name = "Version Info";
35         productName = Version.h;
36      };
37/* End PBXAggregateTarget section */
38
39/* Begin PBXBuildFile section */
40      224A12A30E9EADCC00BD17FD /* gtest-test-part.h in Headers */ = {isa = PBXBuildFile; fileRef = 224A12A20E9EADCC00BD17FD /* gtest-test-part.h */; settings = {ATTRIBUTES = (Public, ); }; };
41      3BF6F2A00E79B5AD000F2EEE /* gtest-type-util.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 3BF6F29F0E79B5AD000F2EEE /* gtest-type-util.h */; };
42      3BF6F2A50E79B616000F2EEE /* gtest-typed-test.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BF6F2A40E79B616000F2EEE /* gtest-typed-test.h */; settings = {ATTRIBUTES = (Public, ); }; };
43      404884380E2F799B00CF7658 /* gtest-death-test.h in Headers */ = {isa = PBXBuildFile; fileRef = 404883DB0E2F799B00CF7658 /* gtest-death-test.h */; settings = {ATTRIBUTES = (Public, ); }; };
44      404884390E2F799B00CF7658 /* gtest-message.h in Headers */ = {isa = PBXBuildFile; fileRef = 404883DC0E2F799B00CF7658 /* gtest-message.h */; settings = {ATTRIBUTES = (Public, ); }; };
45      4048843A0E2F799B00CF7658 /* gtest-spi.h in Headers */ = {isa = PBXBuildFile; fileRef = 404883DD0E2F799B00CF7658 /* gtest-spi.h */; settings = {ATTRIBUTES = (Public, ); }; };
46      4048843B0E2F799B00CF7658 /* gtest.h in Headers */ = {isa = PBXBuildFile; fileRef = 404883DE0E2F799B00CF7658 /* gtest.h */; settings = {ATTRIBUTES = (Public, ); }; };
47      4048843C0E2F799B00CF7658 /* gtest_pred_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 404883DF0E2F799B00CF7658 /* gtest_pred_impl.h */; settings = {ATTRIBUTES = (Public, ); }; };
48      4048843D0E2F799B00CF7658 /* gtest_prod.h in Headers */ = {isa = PBXBuildFile; fileRef = 404883E00E2F799B00CF7658 /* gtest_prod.h */; settings = {ATTRIBUTES = (Public, ); }; };
49      404884500E2F799B00CF7658 /* README.md in Resources */ = {isa = PBXBuildFile; fileRef = 404883F60E2F799B00CF7658 /* README.md */; };
50      404884A00E2F7BE600CF7658 /* gtest-death-test-internal.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E20E2F799B00CF7658 /* gtest-death-test-internal.h */; };
51      404884A10E2F7BE600CF7658 /* gtest-filepath.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E30E2F799B00CF7658 /* gtest-filepath.h */; };
52      404884A20E2F7BE600CF7658 /* gtest-internal.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E40E2F799B00CF7658 /* gtest-internal.h */; };
53      404884A30E2F7BE600CF7658 /* gtest-port.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E50E2F799B00CF7658 /* gtest-port.h */; };
54      404884A40E2F7BE600CF7658 /* gtest-string.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E60E2F799B00CF7658 /* gtest-string.h */; };
55      404884AC0E2F7CD900CF7658 /* CHANGES in Resources */ = {isa = PBXBuildFile; fileRef = 404884A90E2F7CD900CF7658 /* CHANGES */; };
56      404884AD0E2F7CD900CF7658 /* CONTRIBUTORS in Resources */ = {isa = PBXBuildFile; fileRef = 404884AA0E2F7CD900CF7658 /* CONTRIBUTORS */; };
57      404884AE0E2F7CD900CF7658 /* LICENSE in Resources */ = {isa = PBXBuildFile; fileRef = 404884AB0E2F7CD900CF7658 /* LICENSE */; };
58      40899F3A0FFA70D4000B29AE /* gtest-all.cc in Sources */ = {isa = PBXBuildFile; fileRef = 224A12A10E9EADA700BD17FD /* gtest-all.cc */; };
59      40899F500FFA7281000B29AE /* gtest-tuple.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 40899F4D0FFA7271000B29AE /* gtest-tuple.h */; };
60      40899F530FFA72A0000B29AE /* gtest_unittest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 3B238C120E7FE13C00846E11 /* gtest_unittest.cc */; };
61      4089A0440FFAD1BE000B29AE /* sample1.cc in Sources */ = {isa = PBXBuildFile; fileRef = 4089A02C0FFACF7F000B29AE /* sample1.cc */; };
62      4089A0460FFAD1BE000B29AE /* sample1_unittest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 4089A02E0FFACF7F000B29AE /* sample1_unittest.cc */; };
63      40C848FF101A21150083642A /* gtest-all.cc in Sources */ = {isa = PBXBuildFile; fileRef = 224A12A10E9EADA700BD17FD /* gtest-all.cc */; };
64      40C84915101A21DF0083642A /* gtest_main.cc in Sources */ = {isa = PBXBuildFile; fileRef = 4048840D0E2F799B00CF7658 /* gtest_main.cc */; };
65      40C84916101A235B0083642A /* libgtest_main.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 40C8490B101A217E0083642A /* libgtest_main.a */; };
66      40C84921101A23AD0083642A /* libgtest_main.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 40C8490B101A217E0083642A /* libgtest_main.a */; };
67      40C84978101A36540083642A /* libgtest_main.a in Resources */ = {isa = PBXBuildFile; fileRef = 40C8490B101A217E0083642A /* libgtest_main.a */; };
68      40C84980101A36850083642A /* gtest_unittest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 3B238C120E7FE13C00846E11 /* gtest_unittest.cc */; };
69      40C84982101A36850083642A /* libgtest.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 40C848FA101A209C0083642A /* libgtest.a */; };
70      40C84983101A36850083642A /* libgtest_main.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 40C8490B101A217E0083642A /* libgtest_main.a */; };
71      40C8498F101A36A60083642A /* sample1.cc in Sources */ = {isa = PBXBuildFile; fileRef = 4089A02C0FFACF7F000B29AE /* sample1.cc */; };
72      40C84990101A36A60083642A /* sample1_unittest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 4089A02E0FFACF7F000B29AE /* sample1_unittest.cc */; };
73      40C84992101A36A60083642A /* libgtest.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 40C848FA101A209C0083642A /* libgtest.a */; };
74      40C84993101A36A60083642A /* libgtest_main.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 40C8490B101A217E0083642A /* libgtest_main.a */; };
75      40C849A2101A37050083642A /* gtest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4539C8FF0EC27F6400A70F4C /* gtest.framework */; };
76      40C849A4101A37150083642A /* gtest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4539C8FF0EC27F6400A70F4C /* gtest.framework */; };
77      4539C9340EC280AE00A70F4C /* gtest-param-test.h in Headers */ = {isa = PBXBuildFile; fileRef = 4539C9330EC280AE00A70F4C /* gtest-param-test.h */; settings = {ATTRIBUTES = (Public, ); }; };
78      4539C9380EC280E200A70F4C /* gtest-linked_ptr.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 4539C9350EC280E200A70F4C /* gtest-linked_ptr.h */; };
79      4539C9390EC280E200A70F4C /* gtest-param-util-generated.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 4539C9360EC280E200A70F4C /* gtest-param-util-generated.h */; };
80      4539C93A0EC280E200A70F4C /* gtest-param-util.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 4539C9370EC280E200A70F4C /* gtest-param-util.h */; };
81      4567C8181264FF71007740BE /* gtest-printers.h in Headers */ = {isa = PBXBuildFile; fileRef = 4567C8171264FF71007740BE /* gtest-printers.h */; settings = {ATTRIBUTES = (Public, ); }; };
82/* End PBXBuildFile section */
83
84/* Begin PBXContainerItemProxy section */
85      40899F9C0FFA740F000B29AE /* PBXContainerItemProxy */ = {
86         isa = PBXContainerItemProxy;
87         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
88         proxyType = 1;
89         remoteGlobalIDString = 40899F420FFA7184000B29AE;
90         remoteInfo = gtest_unittest;
91      };
92      4089A0970FFAD34A000B29AE /* PBXContainerItemProxy */ = {
93         isa = PBXContainerItemProxy;
94         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
95         proxyType = 1;
96         remoteGlobalIDString = 4089A0120FFACEFC000B29AE;
97         remoteInfo = sample1_unittest;
98      };
99      408BEC0F1046CFE900DEF522 /* PBXContainerItemProxy */ = {
100         isa = PBXContainerItemProxy;
101         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
102         proxyType = 1;
103         remoteGlobalIDString = 40C848F9101A209C0083642A;
104         remoteInfo = "gtest-static";
105      };
106      40C44AE50E379922008FCC51 /* PBXContainerItemProxy */ = {
107         isa = PBXContainerItemProxy;
108         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
109         proxyType = 1;
110         remoteGlobalIDString = 40C44ADC0E3798F4008FCC51;
111         remoteInfo = Version.h;
112      };
113      40C8497C101A36850083642A /* PBXContainerItemProxy */ = {
114         isa = PBXContainerItemProxy;
115         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
116         proxyType = 1;
117         remoteGlobalIDString = 40C848F9101A209C0083642A;
118         remoteInfo = "gtest-static";
119      };
120      40C8497E101A36850083642A /* PBXContainerItemProxy */ = {
121         isa = PBXContainerItemProxy;
122         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
123         proxyType = 1;
124         remoteGlobalIDString = 40C8490A101A217E0083642A;
125         remoteInfo = "gtest_main-static";
126      };
127      40C8498B101A36A60083642A /* PBXContainerItemProxy */ = {
128         isa = PBXContainerItemProxy;
129         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
130         proxyType = 1;
131         remoteGlobalIDString = 40C848F9101A209C0083642A;
132         remoteInfo = "gtest-static";
133      };
134      40C8498D101A36A60083642A /* PBXContainerItemProxy */ = {
135         isa = PBXContainerItemProxy;
136         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
137         proxyType = 1;
138         remoteGlobalIDString = 40C8490A101A217E0083642A;
139         remoteInfo = "gtest_main-static";
140      };
141      40C8499B101A36DC0083642A /* PBXContainerItemProxy */ = {
142         isa = PBXContainerItemProxy;
143         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
144         proxyType = 1;
145         remoteGlobalIDString = 40C8490A101A217E0083642A;
146         remoteInfo = "gtest_main-static";
147      };
148      40C8499D101A36E50083642A /* PBXContainerItemProxy */ = {
149         isa = PBXContainerItemProxy;
150         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
151         proxyType = 1;
152         remoteGlobalIDString = 8D07F2BC0486CC7A007CD1D0;
153         remoteInfo = "gtest-framework";
154      };
155      40C8499F101A36F10083642A /* PBXContainerItemProxy */ = {
156         isa = PBXContainerItemProxy;
157         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
158         proxyType = 1;
159         remoteGlobalIDString = 8D07F2BC0486CC7A007CD1D0;
160         remoteInfo = "gtest-framework";
161      };
162      40C849F6101A43440083642A /* PBXContainerItemProxy */ = {
163         isa = PBXContainerItemProxy;
164         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
165         proxyType = 1;
166         remoteGlobalIDString = 40C8497A101A36850083642A;
167         remoteInfo = "gtest_unittest-static";
168      };
169      40C849F8101A43490083642A /* PBXContainerItemProxy */ = {
170         isa = PBXContainerItemProxy;
171         containerPortal = 0867D690FE84028FC02AAC07 /* Project object */;
172         proxyType = 1;
173         remoteGlobalIDString = 40C84989101A36A60083642A;
174         remoteInfo = "sample1_unittest-static";
175      };
176/* End PBXContainerItemProxy section */
177
178/* Begin PBXCopyFilesBuildPhase section */
179      404884A50E2F7C0400CF7658 /* Copy Headers Internal */ = {
180         isa = PBXCopyFilesBuildPhase;
181         buildActionMask = 2147483647;
182         dstPath = Headers/internal;
183         dstSubfolderSpec = 6;
184         files = (
185            404884A00E2F7BE600CF7658 /* gtest-death-test-internal.h in Copy Headers Internal */,
186            404884A10E2F7BE600CF7658 /* gtest-filepath.h in Copy Headers Internal */,
187            404884A20E2F7BE600CF7658 /* gtest-internal.h in Copy Headers Internal */,
188            4539C9380EC280E200A70F4C /* gtest-linked_ptr.h in Copy Headers Internal */,
189            4539C9390EC280E200A70F4C /* gtest-param-util-generated.h in Copy Headers Internal */,
190            4539C93A0EC280E200A70F4C /* gtest-param-util.h in Copy Headers Internal */,
191            404884A30E2F7BE600CF7658 /* gtest-port.h in Copy Headers Internal */,
192            404884A40E2F7BE600CF7658 /* gtest-string.h in Copy Headers Internal */,
193            40899F500FFA7281000B29AE /* gtest-tuple.h in Copy Headers Internal */,
194            3BF6F2A00E79B5AD000F2EEE /* gtest-type-util.h in Copy Headers Internal */,
195         );
196         name = "Copy Headers Internal";
197         runOnlyForDeploymentPostprocessing = 0;
198      };
199/* End PBXCopyFilesBuildPhase section */
200
201/* Begin PBXFileReference section */
202      224A12A10E9EADA700BD17FD /* gtest-all.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = "gtest-all.cc"; sourceTree = "<group>"; };
203      224A12A20E9EADCC00BD17FD /* gtest-test-part.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = "gtest-test-part.h"; sourceTree = "<group>"; };
204      3B238C120E7FE13C00846E11 /* gtest_unittest.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = gtest_unittest.cc; sourceTree = "<group>"; };
205      3B87D2100E96B92E000D1852 /* runtests.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; path = runtests.sh; sourceTree = "<group>"; };
206      3BF6F29F0E79B5AD000F2EEE /* gtest-type-util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-type-util.h"; sourceTree = "<group>"; };
207      3BF6F2A40E79B616000F2EEE /* gtest-typed-test.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-typed-test.h"; sourceTree = "<group>"; };
208      403EE37C0E377822004BD1E2 /* versiongenerate.py */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.python; path = versiongenerate.py; sourceTree = "<group>"; };
209      404883DB0E2F799B00CF7658 /* gtest-death-test.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-death-test.h"; sourceTree = "<group>"; };
210      404883DC0E2F799B00CF7658 /* gtest-message.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-message.h"; sourceTree = "<group>"; };
211      404883DD0E2F799B00CF7658 /* gtest-spi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-spi.h"; sourceTree = "<group>"; };
212      404883DE0E2F799B00CF7658 /* gtest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = gtest.h; sourceTree = "<group>"; };
213      404883DF0E2F799B00CF7658 /* gtest_pred_impl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = gtest_pred_impl.h; sourceTree = "<group>"; };
214      404883E00E2F799B00CF7658 /* gtest_prod.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = gtest_prod.h; sourceTree = "<group>"; };
215      404883E20E2F799B00CF7658 /* gtest-death-test-internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-death-test-internal.h"; sourceTree = "<group>"; };
216      404883E30E2F799B00CF7658 /* gtest-filepath.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-filepath.h"; sourceTree = "<group>"; };
217      404883E40E2F799B00CF7658 /* gtest-internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-internal.h"; sourceTree = "<group>"; };
218      404883E50E2F799B00CF7658 /* gtest-port.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-port.h"; sourceTree = "<group>"; };
219      404883E60E2F799B00CF7658 /* gtest-string.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-string.h"; sourceTree = "<group>"; };
220      404883F60E2F799B00CF7658 /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = README.md; path = ../README.md; sourceTree = SOURCE_ROOT; };
221      4048840D0E2F799B00CF7658 /* gtest_main.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = gtest_main.cc; sourceTree = "<group>"; };
222      404884A90E2F7CD900CF7658 /* CHANGES */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CHANGES; path = ../CHANGES; sourceTree = SOURCE_ROOT; };
223      404884AA0E2F7CD900CF7658 /* CONTRIBUTORS */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CONTRIBUTORS; path = ../CONTRIBUTORS; sourceTree = SOURCE_ROOT; };
224      404884AB0E2F7CD900CF7658 /* LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = LICENSE; path = ../LICENSE; sourceTree = SOURCE_ROOT; };
225      40899F430FFA7184000B29AE /* gtest_unittest-framework */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "gtest_unittest-framework"; sourceTree = BUILT_PRODUCTS_DIR; };
226      40899F4D0FFA7271000B29AE /* gtest-tuple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-tuple.h"; sourceTree = "<group>"; };
227      40899FB30FFA7567000B29AE /* StaticLibraryTarget.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = StaticLibraryTarget.xcconfig; sourceTree = "<group>"; };
228      4089A0130FFACEFC000B29AE /* sample1_unittest-framework */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "sample1_unittest-framework"; sourceTree = BUILT_PRODUCTS_DIR; };
229      4089A02C0FFACF7F000B29AE /* sample1.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = sample1.cc; sourceTree = "<group>"; };
230      4089A02D0FFACF7F000B29AE /* sample1.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sample1.h; sourceTree = "<group>"; };
231      4089A02E0FFACF7F000B29AE /* sample1_unittest.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = sample1_unittest.cc; sourceTree = "<group>"; };
232      40C848FA101A209C0083642A /* libgtest.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libgtest.a; sourceTree = BUILT_PRODUCTS_DIR; };
233      40C8490B101A217E0083642A /* libgtest_main.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libgtest_main.a; sourceTree = BUILT_PRODUCTS_DIR; };
234      40C84987101A36850083642A /* gtest_unittest */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = gtest_unittest; sourceTree = BUILT_PRODUCTS_DIR; };
235      40C84997101A36A60083642A /* sample1_unittest-static */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "sample1_unittest-static"; sourceTree = BUILT_PRODUCTS_DIR; };
236      40D4CDF10E30E07400294801 /* DebugProject.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = DebugProject.xcconfig; sourceTree = "<group>"; };
237      40D4CDF20E30E07400294801 /* FrameworkTarget.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = FrameworkTarget.xcconfig; sourceTree = "<group>"; };
238      40D4CDF30E30E07400294801 /* General.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = General.xcconfig; sourceTree = "<group>"; };
239      40D4CDF40E30E07400294801 /* ReleaseProject.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ReleaseProject.xcconfig; sourceTree = "<group>"; };
240      40D4CF510E30F5E200294801 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
241      4539C8FF0EC27F6400A70F4C /* gtest.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = gtest.framework; sourceTree = BUILT_PRODUCTS_DIR; };
242      4539C9330EC280AE00A70F4C /* gtest-param-test.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-param-test.h"; sourceTree = "<group>"; };
243      4539C9350EC280E200A70F4C /* gtest-linked_ptr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-linked_ptr.h"; sourceTree = "<group>"; };
244      4539C9360EC280E200A70F4C /* gtest-param-util-generated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-param-util-generated.h"; sourceTree = "<group>"; };
245      4539C9370EC280E200A70F4C /* gtest-param-util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-param-util.h"; sourceTree = "<group>"; };
246      4567C8171264FF71007740BE /* gtest-printers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-printers.h"; sourceTree = "<group>"; };
247/* End PBXFileReference section */
248
249/* Begin PBXFrameworksBuildPhase section */
250      40899F410FFA7184000B29AE /* Frameworks */ = {
251         isa = PBXFrameworksBuildPhase;
252         buildActionMask = 2147483647;
253         files = (
254            40C849A4101A37150083642A /* gtest.framework in Frameworks */,
255            40C84916101A235B0083642A /* libgtest_main.a in Frameworks */,
256         );
257         runOnlyForDeploymentPostprocessing = 0;
258      };
259      4089A0110FFACEFC000B29AE /* Frameworks */ = {
260         isa = PBXFrameworksBuildPhase;
261         buildActionMask = 2147483647;
262         files = (
263            40C849A2101A37050083642A /* gtest.framework in Frameworks */,
264            40C84921101A23AD0083642A /* libgtest_main.a in Frameworks */,
265         );
266         runOnlyForDeploymentPostprocessing = 0;
267      };
268      40C84981101A36850083642A /* Frameworks */ = {
269         isa = PBXFrameworksBuildPhase;
270         buildActionMask = 2147483647;
271         files = (
272            40C84982101A36850083642A /* libgtest.a in Frameworks */,
273            40C84983101A36850083642A /* libgtest_main.a in Frameworks */,
274         );
275         runOnlyForDeploymentPostprocessing = 0;
276      };
277      40C84991101A36A60083642A /* Frameworks */ = {
278         isa = PBXFrameworksBuildPhase;
279         buildActionMask = 2147483647;
280         files = (
281            40C84992101A36A60083642A /* libgtest.a in Frameworks */,
282            40C84993101A36A60083642A /* libgtest_main.a in Frameworks */,
283         );
284         runOnlyForDeploymentPostprocessing = 0;
285      };
286/* End PBXFrameworksBuildPhase section */
287
288/* Begin PBXGroup section */
289      034768DDFF38A45A11DB9C8B /* Products */ = {
290         isa = PBXGroup;
291         children = (
292            4539C8FF0EC27F6400A70F4C /* gtest.framework */,
293            40C848FA101A209C0083642A /* libgtest.a */,
294            40C8490B101A217E0083642A /* libgtest_main.a */,
295            40899F430FFA7184000B29AE /* gtest_unittest-framework */,
296            40C84987101A36850083642A /* gtest_unittest */,
297            4089A0130FFACEFC000B29AE /* sample1_unittest-framework */,
298            40C84997101A36A60083642A /* sample1_unittest-static */,
299         );
300         name = Products;
301         sourceTree = "<group>";
302      };
303      0867D691FE84028FC02AAC07 /* gtest */ = {
304         isa = PBXGroup;
305         children = (
306            40D4CDF00E30E07400294801 /* Config */,
307            08FB77ACFE841707C02AAC07 /* Source */,
308            40D4CF4E0E30F5E200294801 /* Resources */,
309            403EE37B0E377822004BD1E2 /* Scripts */,
310            034768DDFF38A45A11DB9C8B /* Products */,
311         );
312         name = gtest;
313         sourceTree = "<group>";
314      };
315      08FB77ACFE841707C02AAC07 /* Source */ = {
316         isa = PBXGroup;
317         children = (
318            404884A90E2F7CD900CF7658 /* CHANGES */,
319            404884AA0E2F7CD900CF7658 /* CONTRIBUTORS */,
320            404884AB0E2F7CD900CF7658 /* LICENSE */,
321            404883F60E2F799B00CF7658 /* README.md */,
322            404883D90E2F799B00CF7658 /* include */,
323            4089A02F0FFACF84000B29AE /* samples */,
324            404884070E2F799B00CF7658 /* src */,
325            3B238BF00E7FE13B00846E11 /* test */,
326         );
327         name = Source;
328         sourceTree = "<group>";
329      };
330      3B238BF00E7FE13B00846E11 /* test */ = {
331         isa = PBXGroup;
332         children = (
333            3B238C120E7FE13C00846E11 /* gtest_unittest.cc */,
334         );
335         name = test;
336         path = ../test;
337         sourceTree = SOURCE_ROOT;
338      };
339      403EE37B0E377822004BD1E2 /* Scripts */ = {
340         isa = PBXGroup;
341         children = (
342            403EE37C0E377822004BD1E2 /* versiongenerate.py */,
343            3B87D2100E96B92E000D1852 /* runtests.sh */,
344         );
345         path = Scripts;
346         sourceTree = "<group>";
347      };
348      404883D90E2F799B00CF7658 /* include */ = {
349         isa = PBXGroup;
350         children = (
351            404883DA0E2F799B00CF7658 /* gtest */,
352         );
353         name = include;
354         path = ../include;
355         sourceTree = SOURCE_ROOT;
356      };
357      404883DA0E2F799B00CF7658 /* gtest */ = {
358         isa = PBXGroup;
359         children = (
360            404883E10E2F799B00CF7658 /* internal */,
361            224A12A20E9EADCC00BD17FD /* gtest-test-part.h */,
362            404883DB0E2F799B00CF7658 /* gtest-death-test.h */,
363            404883DC0E2F799B00CF7658 /* gtest-message.h */,
364            4539C9330EC280AE00A70F4C /* gtest-param-test.h */,
365            4567C8171264FF71007740BE /* gtest-printers.h */,
366            404883DD0E2F799B00CF7658 /* gtest-spi.h */,
367            404883DE0E2F799B00CF7658 /* gtest.h */,
368            404883DF0E2F799B00CF7658 /* gtest_pred_impl.h */,
369            404883E00E2F799B00CF7658 /* gtest_prod.h */,
370            3BF6F2A40E79B616000F2EEE /* gtest-typed-test.h */,
371         );
372         path = gtest;
373         sourceTree = "<group>";
374      };
375      404883E10E2F799B00CF7658 /* internal */ = {
376         isa = PBXGroup;
377         children = (
378            404883E20E2F799B00CF7658 /* gtest-death-test-internal.h */,
379            404883E30E2F799B00CF7658 /* gtest-filepath.h */,
380            404883E40E2F799B00CF7658 /* gtest-internal.h */,
381            4539C9350EC280E200A70F4C /* gtest-linked_ptr.h */,
382            4539C9360EC280E200A70F4C /* gtest-param-util-generated.h */,
383            4539C9370EC280E200A70F4C /* gtest-param-util.h */,
384            404883E50E2F799B00CF7658 /* gtest-port.h */,
385            404883E60E2F799B00CF7658 /* gtest-string.h */,
386            40899F4D0FFA7271000B29AE /* gtest-tuple.h */,
387            3BF6F29F0E79B5AD000F2EEE /* gtest-type-util.h */,
388         );
389         path = internal;
390         sourceTree = "<group>";
391      };
392      404884070E2F799B00CF7658 /* src */ = {
393         isa = PBXGroup;
394         children = (
395            224A12A10E9EADA700BD17FD /* gtest-all.cc */,
396            4048840D0E2F799B00CF7658 /* gtest_main.cc */,
397         );
398         name = src;
399         path = ../src;
400         sourceTree = SOURCE_ROOT;
401      };
402      4089A02F0FFACF84000B29AE /* samples */ = {
403         isa = PBXGroup;
404         children = (
405            4089A02C0FFACF7F000B29AE /* sample1.cc */,
406            4089A02D0FFACF7F000B29AE /* sample1.h */,
407            4089A02E0FFACF7F000B29AE /* sample1_unittest.cc */,
408         );
409         name = samples;
410         path = ../samples;
411         sourceTree = SOURCE_ROOT;
412      };
413      40D4CDF00E30E07400294801 /* Config */ = {
414         isa = PBXGroup;
415         children = (
416            40D4CDF10E30E07400294801 /* DebugProject.xcconfig */,
417            40D4CDF20E30E07400294801 /* FrameworkTarget.xcconfig */,
418            40D4CDF30E30E07400294801 /* General.xcconfig */,
419            40D4CDF40E30E07400294801 /* ReleaseProject.xcconfig */,
420            40899FB30FFA7567000B29AE /* StaticLibraryTarget.xcconfig */,
421         );
422         path = Config;
423         sourceTree = "<group>";
424      };
425      40D4CF4E0E30F5E200294801 /* Resources */ = {
426         isa = PBXGroup;
427         children = (
428            40D4CF510E30F5E200294801 /* Info.plist */,
429         );
430         path = Resources;
431         sourceTree = "<group>";
432      };
433/* End PBXGroup section */
434
435/* Begin PBXHeadersBuildPhase section */
436      8D07F2BD0486CC7A007CD1D0 /* Headers */ = {
437         isa = PBXHeadersBuildPhase;
438         buildActionMask = 2147483647;
439         files = (
440            404884380E2F799B00CF7658 /* gtest-death-test.h in Headers */,
441            404884390E2F799B00CF7658 /* gtest-message.h in Headers */,
442            4539C9340EC280AE00A70F4C /* gtest-param-test.h in Headers */,
443            4567C8181264FF71007740BE /* gtest-printers.h in Headers */,
444            3BF6F2A50E79B616000F2EEE /* gtest-typed-test.h in Headers */,
445            4048843A0E2F799B00CF7658 /* gtest-spi.h in Headers */,
446            4048843B0E2F799B00CF7658 /* gtest.h in Headers */,
447            4048843C0E2F799B00CF7658 /* gtest_pred_impl.h in Headers */,
448            4048843D0E2F799B00CF7658 /* gtest_prod.h in Headers */,
449            224A12A30E9EADCC00BD17FD /* gtest-test-part.h in Headers */,
450         );
451         runOnlyForDeploymentPostprocessing = 0;
452      };
453/* End PBXHeadersBuildPhase section */
454
455/* Begin PBXNativeTarget section */
456      40899F420FFA7184000B29AE /* gtest_unittest-framework */ = {
457         isa = PBXNativeTarget;
458         buildConfigurationList = 40899F4A0FFA71BC000B29AE /* Build configuration list for PBXNativeTarget "gtest_unittest-framework" */;
459         buildPhases = (
460            40899F400FFA7184000B29AE /* Sources */,
461            40899F410FFA7184000B29AE /* Frameworks */,
462         );
463         buildRules = (
464         );
465         dependencies = (
466            40C849A0101A36F10083642A /* PBXTargetDependency */,
467         );
468         name = "gtest_unittest-framework";
469         productName = gtest_unittest;
470         productReference = 40899F430FFA7184000B29AE /* gtest_unittest-framework */;
471         productType = "com.apple.product-type.tool";
472      };
473      4089A0120FFACEFC000B29AE /* sample1_unittest-framework */ = {
474         isa = PBXNativeTarget;
475         buildConfigurationList = 4089A0240FFACF01000B29AE /* Build configuration list for PBXNativeTarget "sample1_unittest-framework" */;
476         buildPhases = (
477            4089A0100FFACEFC000B29AE /* Sources */,
478            4089A0110FFACEFC000B29AE /* Frameworks */,
479         );
480         buildRules = (
481         );
482         dependencies = (
483            40C8499E101A36E50083642A /* PBXTargetDependency */,
484         );
485         name = "sample1_unittest-framework";
486         productName = sample1_unittest;
487         productReference = 4089A0130FFACEFC000B29AE /* sample1_unittest-framework */;
488         productType = "com.apple.product-type.tool";
489      };
490      40C848F9101A209C0083642A /* gtest-static */ = {
491         isa = PBXNativeTarget;
492         buildConfigurationList = 40C84902101A212E0083642A /* Build configuration list for PBXNativeTarget "gtest-static" */;
493         buildPhases = (
494            40C848F7101A209C0083642A /* Sources */,
495         );
496         buildRules = (
497         );
498         dependencies = (
499         );
500         name = "gtest-static";
501         productName = "gtest-static";
502         productReference = 40C848FA101A209C0083642A /* libgtest.a */;
503         productType = "com.apple.product-type.library.static";
504      };
505      40C8490A101A217E0083642A /* gtest_main-static */ = {
506         isa = PBXNativeTarget;
507         buildConfigurationList = 40C84912101A21D20083642A /* Build configuration list for PBXNativeTarget "gtest_main-static" */;
508         buildPhases = (
509            40C84908101A217E0083642A /* Sources */,
510         );
511         buildRules = (
512         );
513         dependencies = (
514         );
515         name = "gtest_main-static";
516         productName = "gtest_main-static";
517         productReference = 40C8490B101A217E0083642A /* libgtest_main.a */;
518         productType = "com.apple.product-type.library.static";
519      };
520      40C8497A101A36850083642A /* gtest_unittest-static */ = {
521         isa = PBXNativeTarget;
522         buildConfigurationList = 40C84984101A36850083642A /* Build configuration list for PBXNativeTarget "gtest_unittest-static" */;
523         buildPhases = (
524            40C8497F101A36850083642A /* Sources */,
525            40C84981101A36850083642A /* Frameworks */,
526         );
527         buildRules = (
528         );
529         dependencies = (
530            40C8497B101A36850083642A /* PBXTargetDependency */,
531            40C8497D101A36850083642A /* PBXTargetDependency */,
532         );
533         name = "gtest_unittest-static";
534         productName = gtest_unittest;
535         productReference = 40C84987101A36850083642A /* gtest_unittest */;
536         productType = "com.apple.product-type.tool";
537      };
538      40C84989101A36A60083642A /* sample1_unittest-static */ = {
539         isa = PBXNativeTarget;
540         buildConfigurationList = 40C84994101A36A60083642A /* Build configuration list for PBXNativeTarget "sample1_unittest-static" */;
541         buildPhases = (
542            40C8498E101A36A60083642A /* Sources */,
543            40C84991101A36A60083642A /* Frameworks */,
544         );
545         buildRules = (
546         );
547         dependencies = (
548            40C8498A101A36A60083642A /* PBXTargetDependency */,
549            40C8498C101A36A60083642A /* PBXTargetDependency */,
550         );
551         name = "sample1_unittest-static";
552         productName = sample1_unittest;
553         productReference = 40C84997101A36A60083642A /* sample1_unittest-static */;
554         productType = "com.apple.product-type.tool";
555      };
556      8D07F2BC0486CC7A007CD1D0 /* gtest-framework */ = {
557         isa = PBXNativeTarget;
558         buildConfigurationList = 4FADC24208B4156D00ABE55E /* Build configuration list for PBXNativeTarget "gtest-framework" */;
559         buildPhases = (
560            8D07F2C10486CC7A007CD1D0 /* Sources */,
561            8D07F2BD0486CC7A007CD1D0 /* Headers */,
562            404884A50E2F7C0400CF7658 /* Copy Headers Internal */,
563            8D07F2BF0486CC7A007CD1D0 /* Resources */,
564         );
565         buildRules = (
566         );
567         dependencies = (
568            40C44AE60E379922008FCC51 /* PBXTargetDependency */,
569            408BEC101046CFE900DEF522 /* PBXTargetDependency */,
570            40C8499C101A36DC0083642A /* PBXTargetDependency */,
571         );
572         name = "gtest-framework";
573         productInstallPath = "$(HOME)/Library/Frameworks";
574         productName = gtest;
575         productReference = 4539C8FF0EC27F6400A70F4C /* gtest.framework */;
576         productType = "com.apple.product-type.framework";
577      };
578/* End PBXNativeTarget section */
579
580/* Begin PBXProject section */
581      0867D690FE84028FC02AAC07 /* Project object */ = {
582         isa = PBXProject;
583         attributes = {
584            LastUpgradeCheck = 0460;
585         };
586         buildConfigurationList = 4FADC24608B4156D00ABE55E /* Build configuration list for PBXProject "gtest" */;
587         compatibilityVersion = "Xcode 3.2";
588         developmentRegion = English;
589         hasScannedForEncodings = 1;
590         knownRegions = (
591            English,
592            Japanese,
593            French,
594            German,
595            en,
596         );
597         mainGroup = 0867D691FE84028FC02AAC07 /* gtest */;
598         productRefGroup = 034768DDFF38A45A11DB9C8B /* Products */;
599         projectDirPath = "";
600         projectRoot = "";
601         targets = (
602            8D07F2BC0486CC7A007CD1D0 /* gtest-framework */,
603            40C848F9101A209C0083642A /* gtest-static */,
604            40C8490A101A217E0083642A /* gtest_main-static */,
605            40899F420FFA7184000B29AE /* gtest_unittest-framework */,
606            40C8497A101A36850083642A /* gtest_unittest-static */,
607            4089A0120FFACEFC000B29AE /* sample1_unittest-framework */,
608            40C84989101A36A60083642A /* sample1_unittest-static */,
609            3B238F5F0E828B5400846E11 /* Check */,
610            40C44ADC0E3798F4008FCC51 /* Version Info */,
611         );
612      };
613/* End PBXProject section */
614
615/* Begin PBXResourcesBuildPhase section */
616      8D07F2BF0486CC7A007CD1D0 /* Resources */ = {
617         isa = PBXResourcesBuildPhase;
618         buildActionMask = 2147483647;
619         files = (
620            404884500E2F799B00CF7658 /* README.md in Resources */,
621            404884AC0E2F7CD900CF7658 /* CHANGES in Resources */,
622            404884AD0E2F7CD900CF7658 /* CONTRIBUTORS in Resources */,
623            404884AE0E2F7CD900CF7658 /* LICENSE in Resources */,
624            40C84978101A36540083642A /* libgtest_main.a in Resources */,
625         );
626         runOnlyForDeploymentPostprocessing = 0;
627      };
628/* End PBXResourcesBuildPhase section */
629
630/* Begin PBXShellScriptBuildPhase section */
631      3B238F5E0E828B5400846E11 /* ShellScript */ = {
632         isa = PBXShellScriptBuildPhase;
633         buildActionMask = 2147483647;
634         files = (
635         );
636         inputPaths = (
637         );
638         outputPaths = (
639         );
640         runOnlyForDeploymentPostprocessing = 0;
641         shellPath = /bin/sh;
642         shellScript = "# Remember, this \"Run Script\" build phase will be executed from $SRCROOT\n/bin/bash Scripts/runtests.sh";
643      };
644      40C44ADB0E3798F4008FCC51 /* Generate Version.h */ = {
645         isa = PBXShellScriptBuildPhase;
646         buildActionMask = 2147483647;
647         files = (
648         );
649         inputPaths = (
650            "$(SRCROOT)/Scripts/versiongenerate.py",
651            "$(SRCROOT)/../configure.ac",
652         );
653         name = "Generate Version.h";
654         outputPaths = (
655            "$(PROJECT_TEMP_DIR)/Version.h",
656         );
657         runOnlyForDeploymentPostprocessing = 0;
658         shellPath = /bin/sh;
659         shellScript = "# Remember, this \"Run Script\" build phase will be executed from $SRCROOT\n/usr/bin/python Scripts/versiongenerate.py ../ $PROJECT_TEMP_DIR";
660      };
661/* End PBXShellScriptBuildPhase section */
662
663/* Begin PBXSourcesBuildPhase section */
664      40899F400FFA7184000B29AE /* Sources */ = {
665         isa = PBXSourcesBuildPhase;
666         buildActionMask = 2147483647;
667         files = (
668            40899F530FFA72A0000B29AE /* gtest_unittest.cc in Sources */,
669         );
670         runOnlyForDeploymentPostprocessing = 0;
671      };
672      4089A0100FFACEFC000B29AE /* Sources */ = {
673         isa = PBXSourcesBuildPhase;
674         buildActionMask = 2147483647;
675         files = (
676            4089A0440FFAD1BE000B29AE /* sample1.cc in Sources */,
677            4089A0460FFAD1BE000B29AE /* sample1_unittest.cc in Sources */,
678         );
679         runOnlyForDeploymentPostprocessing = 0;
680      };
681      40C848F7101A209C0083642A /* Sources */ = {
682         isa = PBXSourcesBuildPhase;
683         buildActionMask = 2147483647;
684         files = (
685            40C848FF101A21150083642A /* gtest-all.cc in Sources */,
686         );
687         runOnlyForDeploymentPostprocessing = 0;
688      };
689      40C84908101A217E0083642A /* Sources */ = {
690         isa = PBXSourcesBuildPhase;
691         buildActionMask = 2147483647;
692         files = (
693            40C84915101A21DF0083642A /* gtest_main.cc in Sources */,
694         );
695         runOnlyForDeploymentPostprocessing = 0;
696      };
697      40C8497F101A36850083642A /* Sources */ = {
698         isa = PBXSourcesBuildPhase;
699         buildActionMask = 2147483647;
700         files = (
701            40C84980101A36850083642A /* gtest_unittest.cc in Sources */,
702         );
703         runOnlyForDeploymentPostprocessing = 0;
704      };
705      40C8498E101A36A60083642A /* Sources */ = {
706         isa = PBXSourcesBuildPhase;
707         buildActionMask = 2147483647;
708         files = (
709            40C8498F101A36A60083642A /* sample1.cc in Sources */,
710            40C84990101A36A60083642A /* sample1_unittest.cc in Sources */,
711         );
712         runOnlyForDeploymentPostprocessing = 0;
713      };
714      8D07F2C10486CC7A007CD1D0 /* Sources */ = {
715         isa = PBXSourcesBuildPhase;
716         buildActionMask = 2147483647;
717         files = (
718            40899F3A0FFA70D4000B29AE /* gtest-all.cc in Sources */,
719         );
720         runOnlyForDeploymentPostprocessing = 0;
721      };
722/* End PBXSourcesBuildPhase section */
723
724/* Begin PBXTargetDependency section */
725      40899F9D0FFA740F000B29AE /* PBXTargetDependency */ = {
726         isa = PBXTargetDependency;
727         target = 40899F420FFA7184000B29AE /* gtest_unittest-framework */;
728         targetProxy = 40899F9C0FFA740F000B29AE /* PBXContainerItemProxy */;
729      };
730      4089A0980FFAD34A000B29AE /* PBXTargetDependency */ = {
731         isa = PBXTargetDependency;
732         target = 4089A0120FFACEFC000B29AE /* sample1_unittest-framework */;
733         targetProxy = 4089A0970FFAD34A000B29AE /* PBXContainerItemProxy */;
734      };
735      408BEC101046CFE900DEF522 /* PBXTargetDependency */ = {
736         isa = PBXTargetDependency;
737         target = 40C848F9101A209C0083642A /* gtest-static */;
738         targetProxy = 408BEC0F1046CFE900DEF522 /* PBXContainerItemProxy */;
739      };
740      40C44AE60E379922008FCC51 /* PBXTargetDependency */ = {
741         isa = PBXTargetDependency;
742         target = 40C44ADC0E3798F4008FCC51 /* Version Info */;
743         targetProxy = 40C44AE50E379922008FCC51 /* PBXContainerItemProxy */;
744      };
745      40C8497B101A36850083642A /* PBXTargetDependency */ = {
746         isa = PBXTargetDependency;
747         target = 40C848F9101A209C0083642A /* gtest-static */;
748         targetProxy = 40C8497C101A36850083642A /* PBXContainerItemProxy */;
749      };
750      40C8497D101A36850083642A /* PBXTargetDependency */ = {
751         isa = PBXTargetDependency;
752         target = 40C8490A101A217E0083642A /* gtest_main-static */;
753         targetProxy = 40C8497E101A36850083642A /* PBXContainerItemProxy */;
754      };
755      40C8498A101A36A60083642A /* PBXTargetDependency */ = {
756         isa = PBXTargetDependency;
757         target = 40C848F9101A209C0083642A /* gtest-static */;
758         targetProxy = 40C8498B101A36A60083642A /* PBXContainerItemProxy */;
759      };
760      40C8498C101A36A60083642A /* PBXTargetDependency */ = {
761         isa = PBXTargetDependency;
762         target = 40C8490A101A217E0083642A /* gtest_main-static */;
763         targetProxy = 40C8498D101A36A60083642A /* PBXContainerItemProxy */;
764      };
765      40C8499C101A36DC0083642A /* PBXTargetDependency */ = {
766         isa = PBXTargetDependency;
767         target = 40C8490A101A217E0083642A /* gtest_main-static */;
768         targetProxy = 40C8499B101A36DC0083642A /* PBXContainerItemProxy */;
769      };
770      40C8499E101A36E50083642A /* PBXTargetDependency */ = {
771         isa = PBXTargetDependency;
772         target = 8D07F2BC0486CC7A007CD1D0 /* gtest-framework */;
773         targetProxy = 40C8499D101A36E50083642A /* PBXContainerItemProxy */;
774      };
775      40C849A0101A36F10083642A /* PBXTargetDependency */ = {
776         isa = PBXTargetDependency;
777         target = 8D07F2BC0486CC7A007CD1D0 /* gtest-framework */;
778         targetProxy = 40C8499F101A36F10083642A /* PBXContainerItemProxy */;
779      };
780      40C849F7101A43440083642A /* PBXTargetDependency */ = {
781         isa = PBXTargetDependency;
782         target = 40C8497A101A36850083642A /* gtest_unittest-static */;
783         targetProxy = 40C849F6101A43440083642A /* PBXContainerItemProxy */;
784      };
785      40C849F9101A43490083642A /* PBXTargetDependency */ = {
786         isa = PBXTargetDependency;
787         target = 40C84989101A36A60083642A /* sample1_unittest-static */;
788         targetProxy = 40C849F8101A43490083642A /* PBXContainerItemProxy */;
789      };
790/* End PBXTargetDependency section */
791
792/* Begin XCBuildConfiguration section */
793      3B238F600E828B5400846E11 /* Debug */ = {
794         isa = XCBuildConfiguration;
795         buildSettings = {
796            COMBINE_HIDPI_IMAGES = YES;
797            COPY_PHASE_STRIP = NO;
798            GCC_DYNAMIC_NO_PIC = NO;
799            GCC_OPTIMIZATION_LEVEL = 0;
800            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
801            PRODUCT_NAME = Check;
802            SDKROOT = macosx;
803         };
804         name = Debug;
805      };
806      3B238F610E828B5400846E11 /* Release */ = {
807         isa = XCBuildConfiguration;
808         buildSettings = {
809            COMBINE_HIDPI_IMAGES = YES;
810            COPY_PHASE_STRIP = YES;
811            DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
812            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
813            PRODUCT_NAME = Check;
814            SDKROOT = macosx;
815            ZERO_LINK = NO;
816         };
817         name = Release;
818      };
819      40899F450FFA7185000B29AE /* Debug */ = {
820         isa = XCBuildConfiguration;
821         buildSettings = {
822            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
823            HEADER_SEARCH_PATHS = ../;
824            PRODUCT_NAME = "gtest_unittest-framework";
825            SDKROOT = macosx;
826         };
827         name = Debug;
828      };
829      40899F460FFA7185000B29AE /* Release */ = {
830         isa = XCBuildConfiguration;
831         buildSettings = {
832            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
833            HEADER_SEARCH_PATHS = ../;
834            PRODUCT_NAME = "gtest_unittest-framework";
835            SDKROOT = macosx;
836         };
837         name = Release;
838      };
839      4089A0150FFACEFD000B29AE /* Debug */ = {
840         isa = XCBuildConfiguration;
841         buildSettings = {
842            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
843            PRODUCT_NAME = "sample1_unittest-framework";
844            SDKROOT = macosx;
845         };
846         name = Debug;
847      };
848      4089A0160FFACEFD000B29AE /* Release */ = {
849         isa = XCBuildConfiguration;
850         buildSettings = {
851            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
852            PRODUCT_NAME = "sample1_unittest-framework";
853            SDKROOT = macosx;
854         };
855         name = Release;
856      };
857      40C44ADF0E3798F4008FCC51 /* Debug */ = {
858         isa = XCBuildConfiguration;
859         buildSettings = {
860            COMBINE_HIDPI_IMAGES = YES;
861            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
862            MACOSX_DEPLOYMENT_TARGET = 10.7;
863            PRODUCT_NAME = gtest;
864            SDKROOT = macosx;
865            TARGET_NAME = gtest;
866         };
867         name = Debug;
868      };
869      40C44AE00E3798F4008FCC51 /* Release */ = {
870         isa = XCBuildConfiguration;
871         buildSettings = {
872            COMBINE_HIDPI_IMAGES = YES;
873            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
874            MACOSX_DEPLOYMENT_TARGET = 10.7;
875            PRODUCT_NAME = gtest;
876            SDKROOT = macosx;
877            TARGET_NAME = gtest;
878         };
879         name = Release;
880      };
881      40C848FB101A209D0083642A /* Debug */ = {
882         isa = XCBuildConfiguration;
883         baseConfigurationReference = 40899FB30FFA7567000B29AE /* StaticLibraryTarget.xcconfig */;
884         buildSettings = {
885            COMBINE_HIDPI_IMAGES = YES;
886            GCC_INLINES_ARE_PRIVATE_EXTERN = YES;
887            GCC_SYMBOLS_PRIVATE_EXTERN = YES;
888            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
889            HEADER_SEARCH_PATHS = (
890               ../,
891               ../include/,
892            );
893            PRODUCT_NAME = gtest;
894            SDKROOT = macosx;
895         };
896         name = Debug;
897      };
898      40C848FC101A209D0083642A /* Release */ = {
899         isa = XCBuildConfiguration;
900         baseConfigurationReference = 40899FB30FFA7567000B29AE /* StaticLibraryTarget.xcconfig */;
901         buildSettings = {
902            COMBINE_HIDPI_IMAGES = YES;
903            GCC_INLINES_ARE_PRIVATE_EXTERN = YES;
904            GCC_SYMBOLS_PRIVATE_EXTERN = YES;
905            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
906            HEADER_SEARCH_PATHS = (
907               ../,
908               ../include/,
909            );
910            PRODUCT_NAME = gtest;
911            SDKROOT = macosx;
912         };
913         name = Release;
914      };
915      40C8490E101A217F0083642A /* Debug */ = {
916         isa = XCBuildConfiguration;
917         baseConfigurationReference = 40899FB30FFA7567000B29AE /* StaticLibraryTarget.xcconfig */;
918         buildSettings = {
919            COMBINE_HIDPI_IMAGES = YES;
920            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
921            HEADER_SEARCH_PATHS = (
922               ../,
923               ../include/,
924            );
925            PRODUCT_NAME = gtest_main;
926            SDKROOT = macosx;
927         };
928         name = Debug;
929      };
930      40C8490F101A217F0083642A /* Release */ = {
931         isa = XCBuildConfiguration;
932         baseConfigurationReference = 40899FB30FFA7567000B29AE /* StaticLibraryTarget.xcconfig */;
933         buildSettings = {
934            COMBINE_HIDPI_IMAGES = YES;
935            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
936            HEADER_SEARCH_PATHS = (
937               ../,
938               ../include/,
939            );
940            PRODUCT_NAME = gtest_main;
941            SDKROOT = macosx;
942         };
943         name = Release;
944      };
945      40C84985101A36850083642A /* Debug */ = {
946         isa = XCBuildConfiguration;
947         buildSettings = {
948            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
949            HEADER_SEARCH_PATHS = ../;
950            PRODUCT_NAME = gtest_unittest;
951            SDKROOT = macosx;
952         };
953         name = Debug;
954      };
955      40C84986101A36850083642A /* Release */ = {
956         isa = XCBuildConfiguration;
957         buildSettings = {
958            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
959            HEADER_SEARCH_PATHS = ../;
960            PRODUCT_NAME = gtest_unittest;
961            SDKROOT = macosx;
962         };
963         name = Release;
964      };
965      40C84995101A36A60083642A /* Debug */ = {
966         isa = XCBuildConfiguration;
967         buildSettings = {
968            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
969            PRODUCT_NAME = "sample1_unittest-static";
970            SDKROOT = macosx;
971         };
972         name = Debug;
973      };
974      40C84996101A36A60083642A /* Release */ = {
975         isa = XCBuildConfiguration;
976         buildSettings = {
977            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
978            PRODUCT_NAME = "sample1_unittest-static";
979            SDKROOT = macosx;
980         };
981         name = Release;
982      };
983      4FADC24308B4156D00ABE55E /* Debug */ = {
984         isa = XCBuildConfiguration;
985         baseConfigurationReference = 40D4CDF20E30E07400294801 /* FrameworkTarget.xcconfig */;
986         buildSettings = {
987            COMBINE_HIDPI_IMAGES = YES;
988            DYLIB_COMPATIBILITY_VERSION = 1;
989            DYLIB_CURRENT_VERSION = 1;
990            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
991            HEADER_SEARCH_PATHS = (
992               ../,
993               ../include/,
994            );
995            INFOPLIST_FILE = Resources/Info.plist;
996            INFOPLIST_PREFIX_HEADER = "$(PROJECT_TEMP_DIR)/Version.h";
997            INFOPLIST_PREPROCESS = YES;
998            PRODUCT_NAME = gtest;
999            SDKROOT = macosx;
1000            VERSIONING_SYSTEM = "apple-generic";
1001         };
1002         name = Debug;
1003      };
1004      4FADC24408B4156D00ABE55E /* Release */ = {
1005         isa = XCBuildConfiguration;
1006         baseConfigurationReference = 40D4CDF20E30E07400294801 /* FrameworkTarget.xcconfig */;
1007         buildSettings = {
1008            COMBINE_HIDPI_IMAGES = YES;
1009            DYLIB_COMPATIBILITY_VERSION = 1;
1010            DYLIB_CURRENT_VERSION = 1;
1011            GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
1012            HEADER_SEARCH_PATHS = (
1013               ../,
1014               ../include/,
1015            );
1016            INFOPLIST_FILE = Resources/Info.plist;
1017            INFOPLIST_PREFIX_HEADER = "$(PROJECT_TEMP_DIR)/Version.h";
1018            INFOPLIST_PREPROCESS = YES;
1019            PRODUCT_NAME = gtest;
1020            SDKROOT = macosx;
1021            VERSIONING_SYSTEM = "apple-generic";
1022         };
1023         name = Release;
1024      };
1025      4FADC24708B4156D00ABE55E /* Debug */ = {
1026         isa = XCBuildConfiguration;
1027         baseConfigurationReference = 40D4CDF10E30E07400294801 /* DebugProject.xcconfig */;
1028         buildSettings = {
1029         };
1030         name = Debug;
1031      };
1032      4FADC24808B4156D00ABE55E /* Release */ = {
1033         isa = XCBuildConfiguration;
1034         baseConfigurationReference = 40D4CDF40E30E07400294801 /* ReleaseProject.xcconfig */;
1035         buildSettings = {
1036         };
1037         name = Release;
1038      };
1039/* End XCBuildConfiguration section */
1040
1041/* Begin XCConfigurationList section */
1042      3B238FA30E828BB600846E11 /* Build configuration list for PBXAggregateTarget "Check" */ = {
1043         isa = XCConfigurationList;
1044         buildConfigurations = (
1045            3B238F600E828B5400846E11 /* Debug */,
1046            3B238F610E828B5400846E11 /* Release */,
1047         );
1048         defaultConfigurationIsVisible = 0;
1049         defaultConfigurationName = Release;
1050      };
1051      40899F4A0FFA71BC000B29AE /* Build configuration list for PBXNativeTarget "gtest_unittest-framework" */ = {
1052         isa = XCConfigurationList;
1053         buildConfigurations = (
1054            40899F450FFA7185000B29AE /* Debug */,
1055            40899F460FFA7185000B29AE /* Release */,
1056         );
1057         defaultConfigurationIsVisible = 0;
1058         defaultConfigurationName = Release;
1059      };
1060      4089A0240FFACF01000B29AE /* Build configuration list for PBXNativeTarget "sample1_unittest-framework" */ = {
1061         isa = XCConfigurationList;
1062         buildConfigurations = (
1063            4089A0150FFACEFD000B29AE /* Debug */,
1064            4089A0160FFACEFD000B29AE /* Release */,
1065         );
1066         defaultConfigurationIsVisible = 0;
1067         defaultConfigurationName = Release;
1068      };
1069      40C44AE40E379905008FCC51 /* Build configuration list for PBXAggregateTarget "Version Info" */ = {
1070         isa = XCConfigurationList;
1071         buildConfigurations = (
1072            40C44ADF0E3798F4008FCC51 /* Debug */,
1073            40C44AE00E3798F4008FCC51 /* Release */,
1074         );
1075         defaultConfigurationIsVisible = 0;
1076         defaultConfigurationName = Release;
1077      };
1078      40C84902101A212E0083642A /* Build configuration list for PBXNativeTarget "gtest-static" */ = {
1079         isa = XCConfigurationList;
1080         buildConfigurations = (
1081            40C848FB101A209D0083642A /* Debug */,
1082            40C848FC101A209D0083642A /* Release */,
1083         );
1084         defaultConfigurationIsVisible = 0;
1085         defaultConfigurationName = Release;
1086      };
1087      40C84912101A21D20083642A /* Build configuration list for PBXNativeTarget "gtest_main-static" */ = {
1088         isa = XCConfigurationList;
1089         buildConfigurations = (
1090            40C8490E101A217F0083642A /* Debug */,
1091            40C8490F101A217F0083642A /* Release */,
1092         );
1093         defaultConfigurationIsVisible = 0;
1094         defaultConfigurationName = Release;
1095      };
1096      40C84984101A36850083642A /* Build configuration list for PBXNativeTarget "gtest_unittest-static" */ = {
1097         isa = XCConfigurationList;
1098         buildConfigurations = (
1099            40C84985101A36850083642A /* Debug */,
1100            40C84986101A36850083642A /* Release */,
1101         );
1102         defaultConfigurationIsVisible = 0;
1103         defaultConfigurationName = Release;
1104      };
1105      40C84994101A36A60083642A /* Build configuration list for PBXNativeTarget "sample1_unittest-static" */ = {
1106         isa = XCConfigurationList;
1107         buildConfigurations = (
1108            40C84995101A36A60083642A /* Debug */,
1109            40C84996101A36A60083642A /* Release */,
1110         );
1111         defaultConfigurationIsVisible = 0;
1112         defaultConfigurationName = Release;
1113      };
1114      4FADC24208B4156D00ABE55E /* Build configuration list for PBXNativeTarget "gtest-framework" */ = {
1115         isa = XCConfigurationList;
1116         buildConfigurations = (
1117            4FADC24308B4156D00ABE55E /* Debug */,
1118            4FADC24408B4156D00ABE55E /* Release */,
1119         );
1120         defaultConfigurationIsVisible = 0;
1121         defaultConfigurationName = Release;
1122      };
1123      4FADC24608B4156D00ABE55E /* Build configuration list for PBXProject "gtest" */ = {
1124         isa = XCConfigurationList;
1125         buildConfigurations = (
1126            4FADC24708B4156D00ABE55E /* Debug */,
1127            4FADC24808B4156D00ABE55E /* Release */,
1128         );
1129         defaultConfigurationIsVisible = 0;
1130         defaultConfigurationName = Release;
1131      };
1132/* End XCConfigurationList section */
1133   };
1134   rootObject = 0867D690FE84028FC02AAC07 /* Project object */;
1135}
trunk/3rdparty/googletest/travis.sh
r0r249096
1#!/usr/bin/env sh
2set -evx
3env | sort
4
5mkdir build || true
6mkdir build/$GTEST_TARGET || true
7cd build/$GTEST_TARGET
8cmake -Dgtest_build_samples=ON \
9      -Dgmock_build_samples=ON \
10      -Dgtest_build_tests=ON \
11      -Dgmock_build_tests=ON \
12      ../../$GTEST_TARGET
13make
14make test
trunk/hash/a800_flop.xml
r249095r249096
2424      </part>
2525   </software>
2626
27   <software name="elktrgld">
28      <!-- Flippy disk, c64 version on side A -->
29      <description>Elektra Glide</description>
30      <year>1986</year>
31      <publisher>Mastertronic</publisher>
32      <info name="serial" value="64712" />
2733
34      <part name="flop1" interface="floppy_5_25">
35         <dataarea name="flop" size="92160">
36            <rom name="elektraglide.xfd" size="92160" crc="96185b1c" sha1="fb9825a432b83a2a7e623a2f617d0fa11de08158" offset="0" />
37         </dataarea>
38      </part>
39   </software>
40
41   <software name="koalapnt">
42      <!-- Flippy disk, c64 version on side A -->
43      <description>KoalaPainter (Light Pen)</description>
44      <year>1984</year>
45      <publisher>Koala Technologies</publisher>
46      <info name="serial" value="00626-001" />
47
48      <part name="flop1" interface="floppy_5_25">
49         <dataarea name="flop" size="92160">
50            <rom name="koalapainter.xfd" size="92160" crc="f1447be4" sha1="834d906748f9f4f089912289ab592cf091456d49" offset="0" />
51         </dataarea>
52      </part>
53   </software>
54
2855</softwarelist>
trunk/hash/c64_flop.xml
r249095r249096
602602      </part>
603603   </software>
604604
605   <software name="elktrgld">
606      <!-- Flippy disk, a800 version on side B -->
607      <description>Elektra Glide</description>
608      <year>1986</year>
609      <publisher>Mastertronic</publisher>
610      <info name="serial" value="64712" />
611
612      <part name="flop1" interface="floppy_5_25">
613         <dataarea name="flop" size="287512">
614            <rom name="elektraglide.g64" size="287512" crc="ccb7b7c1" sha1="699bc6111a0f3c26d61c63f7b23eeb7462649461" offset="0" />
615         </dataarea>
616      </part>
617   </software>
618
619   <software name="koalapnt">
620      <!-- Flippy disk, a800 version on side B -->
621      <description>KoalaPainter (Light Pen)</description>
622      <year>1984</year>
623      <publisher>Koala Technologies</publisher>
624      <info name="serial" value="00626-001" />
625
626      <part name="flop1" interface="floppy_5_25">
627         <dataarea name="flop" size="287512">
628            <rom name="koalapainter.g64" size="287512" crc="56f06305" sha1="a4bb43f8f46c3e733e4a2ab7f6cdfa8483159df5" offset="0" />
629         </dataarea>
630      </part>
631   </software>
632
605633   <!-- Test/Demo disks -->
606634
607635   <software name="1541demo">
trunk/hash/megadriv.xml
r249095r249096
1620416204      <info name="release" value="19920710"/>
1620516205      <info name="alt_title" value="炎の闘球児 ドッジ弾平"/>
1620616206      <part name="cart" interface="megadriv_cart">
16207         <feature name="slot" value="rom_eeprom"/>
1620716208         <dataarea name="rom" width="16" endianness="big" size="524288">
1620816209            <rom name="mpr-14856.bin" size="524288" crc="630f07c6" sha1="ebdf20fd8aaeb3c7ec97302089b3330265118cf0" offset="0x000000"/>
1620916210         </dataarea>
r249095r249096
1827018271      <info name="release" value="19941021"/>
1827118272      <info name="alt_title" value="ロックマン メガワールド"/>
1827218273      <part name="cart" interface="megadriv_cart">
18274         <feature name="slot" value="rom_sram"/>
1827318275         <dataarea name="rom" width="16" endianness="big" size="2097152">
1827418276            <rom name="rockman mega world (jpn) (alt).bin" size="2097152" crc="85c956ef" sha1="a435ac53589a29dbb655662c942daab425d3f6bd" offset="0x000000"/>
1827518277         </dataarea>
18278         <dataarea name="sram" size="16384">
18279         </dataarea>
1827618280      </part>
1827718281   </software>
1827818282
r249095r249096
2036220366      <info name="release" value="19911205"/>
2036320367      <info name="alt_title" value="忍者武雷伝説"/>
2036420368      <part name="cart" interface="megadriv_cart">
20369         <feature name="slot" value="rom_eeprom"/>
2036520370         <dataarea name="rom" width="16" endianness="big" size="1048576">
2036620371            <rom name="ninja burai densetsu (jpn).bin" size="1048576" crc="a8d828a0" sha1="9cc3419ca7ecaf0d106aa896ffc0266c7145fff7" offset="0x000000"/>
2036720372         </dataarea>
trunk/hash/x1_cass.xml
r249095r249096
1212
1313<softwarelist name="x1_cass" description="Sharp X1 cassettes">
1414
15   <software name="alamein">
16      <description>El Alamein</description>
17      <year>1983</year>
18      <publisher>ポニカ (Pony Canyon)</publisher>
19      <info name="alt_title" value="エル・アラメイン"/>
20      <info name="usage" value="In BASIC, type LOAD and then RUN"/>
21      <sharedfeat name="requirement" value="x1_flop:tapbas"/>
22      <part name="cass" interface="x1_cass">
23         <dataarea name="side1" size="12742140">
24            <rom name="alamein.wav" size="12742140" crc="04e00f60" sha1="42f3ef356fdb67ddd0fbdb57e473c23d267f9bf4" offset="0" />
25         </dataarea>
26      </part>
27   </software>
28   
1529   <software name="blckonyx" supported="no">
1630      <description>The Black Onyx</description>
1731      <year>1985</year>
r249095r249096
7690         </dataarea>
7791      </part>
7892   </software>
93   
94   <software name="cball">
95      <description>Cannon Ball</description>
96      <year>1983</year>
97      <publisher>ハドソン (Hudson Soft)</publisher>
98      <info name="alt_title" value="キャノンボール"/>
99      <part name="cass" interface="x1_cass">
100         <dataarea name="side1" size="4857558">
101            <rom name="cball.wav" size="4857558" crc="4405cf21" sha1="769a43d97f69b5d72347ca8b72547e464b9d059b" offset="0" />
102         </dataarea>
103      </part>
104   </software>
79105
80106   <software name="cprowsp">
81107      <description>Champion ProWres Special</description>
r249095r249096
296322         </dataarea>
297323      </part>
298324   </software>
325   
326   <software name="machgjoe">
327      <description>Ginkou Goutou - Machinegun Joe vs. the Mafia</description>
328      <year>1983</year>
329      <publisher>ハドソン (Hudson Soft)</publisher>
330      <info name="alt_title" value="銀行強盗 マシンガンジョー VS ザ・マフィア"/>
331      <part name="cass" interface="x1_cass">
332         <dataarea name="side1" size="15591932">
333            <rom name="machgjoe.wav" size="15591932" crc="3769199a" sha1="81614c317f432055f2c5fdcce51438de9fbdad7f" offset="0" />
334         </dataarea>
335      </part>
336   </software>
299337
300338   <software name="mappy">
301339      <description>Mappy</description>
trunk/scripts/genie.lua
r249095r249096
10611061      "-std=gnu++98",
10621062   }
10631063   archivesplit_size "20"
1064   if os.getenv("EMSCRIPTEN") then
1065      includedirs {
1066         os.getenv("EMSCRIPTEN") .. "/system/lib/libcxxabi/include"
1067      }
1068   end
10641069
10651070configuration { "android*" }
10661071   buildoptions {
trunk/scripts/src/3rdparty.lua
r249095r249096
795795end
796796     
797797--------------------------------------------------
798-- UnitTest++ library objects
798-- GoogleTest library objects
799799--------------------------------------------------
800800
801project "unittest-cpp"
802   uuid "717d39e5-b6ff-4507-a092-c27c05b60ab5"
801project "gtest"
802   uuid "fa306a8d-fb10-4d4a-9d2e-fdb9076407b4"
803803   kind "StaticLib"
804804
805   files {     
806      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/AssertException.cpp",
807      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/AssertException.h",
808      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/CheckMacros.h",
809      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Checks.cpp",
810      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Checks.h",
811      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/CompositeTestReporter.cpp",
812      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/CompositeTestReporter.h",
813      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Config.h",
814      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/CurrentTest.cpp",
815      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/CurrentTest.h",
816      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/DeferredTestReporter.cpp",
817      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/DeferredTestReporter.h",
818      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/DeferredTestResult.cpp",
819      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/DeferredTestResult.h",
820      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/ExceptionMacros.h",
821      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/ExecuteTest.h",
822      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/HelperMacros.h",
823      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/MemoryOutStream.cpp",
824      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/MemoryOutStream.h",
825      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/ReportAssert.cpp",
826      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/ReportAssert.h",
827      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/ReportAssertImpl.h",
828      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Test.cpp",
829      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Test.h",
830      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestDetails.cpp",
831      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestDetails.h",
832      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestList.cpp",
833      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestList.h",
834      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestMacros.h",
835      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestReporter.cpp",
836      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestReporter.h",
837      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestReporterStdout.cpp",
838      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestReporterStdout.h",
839      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestResults.cpp",
840      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestResults.h",
841      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestRunner.cpp",
842      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestRunner.h",
843      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TestSuite.h",
844      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TimeConstraint.cpp",
845      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TimeConstraint.h",
846      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/TimeHelpers.h",
847      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/UnitTest++.h",
848      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/UnitTestPP.h",
849      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/XmlTestReporter.cpp",
850      MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/XmlTestReporter.h",
851   }
852
853   if _OPTIONS["targetos"]~="windows" then
854      files {
855         MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Posix/SignalTranslator.cpp",
856         MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Posix/SignalTranslator.h",
857         MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Posix/TimeHelpers.cpp",
858         MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Posix/TimeHelpers.h",
805   configuration { "gmake" }
806      buildoptions {
807         "-Wno-undef",
808         "-Wno-unused-variable",
859809      }
860   end
861810
862   if _OPTIONS["targetos"]=="windows" then
863      files {
864         MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Win32/TimeHelpers.cpp",
865         MAME_DIR .. "3rdparty/unittest-cpp/UnitTest++/Win32/TimeHelpers.h",
866      }
867   end
811   configuration { }
812
813   includedirs {
814      MAME_DIR .. "3rdparty/googletest/googletest/include",
815      MAME_DIR .. "3rdparty/googletest/googletest",
816   }   
817   files {     
818      MAME_DIR .. "3rdparty/googletest/googletest/src/gtest-all.cc",
819   }
trunk/scripts/src/tests.lua
r249095r249096
2121   targetdir(MAME_DIR)
2222end
2323
24configuration { "gmake" }
25   buildoptions {
26      "-Wno-undef",
27   }
28
29configuration { }
30
2431links {
25   "unittest-cpp",
32   "gtest",
2633   "utils",
2734   "expat",
2835   "zlib",
r249095r249096
3037}
3138
3239includedirs {
33   MAME_DIR .. "3rdparty/unittest-cpp",
40   MAME_DIR .. "3rdparty/googletest/googletest/include",
3441   MAME_DIR .. "src/osd",
3542   MAME_DIR .. "src/lib/util",
3643}
trunk/scripts/target/mame/mess.lua
r249095r249096
12331233}
12341234
12351235createMESSProjects(_target, _subtarget, "canon")
1236files {
1237   MAME_DIR .. "src/mess/drivers/cat.c",
1238   MAME_DIR .. "src/mess/drivers/x07.c",
1236files {             
1237   MAME_DIR .. "src/mess/drivers/cat.c",       
1238   MAME_DIR .. "src/mess/drivers/x07.c",       
1239   MAME_DIR .. "src/mess/drivers/canon_s80.c",
12391240}
12401241
12411242createMESSProjects(_target, _subtarget, "cantab")
r249095r249096
14431444   MAME_DIR .. "src/mess/drivers/bk.c",
14441445   MAME_DIR .. "src/mess/machine/bk.c",
14451446   MAME_DIR .. "src/mess/video/bk.c",
1447   MAME_DIR .. "src/mess/drivers/dvk_kcgd.c",
14461448   MAME_DIR .. "src/mess/drivers/dvk_ksm.c",
14471449   MAME_DIR .. "src/mess/machine/ms7004.c",
14481450   MAME_DIR .. "src/mess/drivers/mk85.c",
trunk/src/emu/bus/centronics/printer.c
r249095r249096
9999   output_busy(m_busy);
100100   output_fault(1);
101101   output_ack(1);
102   output_select(1);
102103}
103104
104105/*-------------------------------------------------
trunk/src/emu/bus/pc_kbd/iskr1030.c
r249095r249096
4242
4343ROM_START( iskr_1030_keyboard )
4444   ROM_REGION( 0x800, I8048_TAG, 0 )
45   // XXX add P/N etc
4645   ROM_LOAD( "i1030.bin", 0x000, 0x800, CRC(7cac9c4b) SHA1(03959d3350e012ebfe61cee9c062b6c1fdd8766e) )
4746ROM_END
4847
r249095r249096
6261//-------------------------------------------------
6362
6463static ADDRESS_MAP_START( iskr_1030_keyboard_io, AS_IO, 8, iskr_1030_keyboard_device )
65   AM_RANGE(0x00, 0xFF) AM_RAM
64   AM_RANGE(0x00, 0xFF) AM_READWRITE(ram_r, ram_w)
6665   AM_RANGE(MCS48_PORT_P1, MCS48_PORT_P1) AM_READWRITE(p1_r, p1_w)
6766   AM_RANGE(MCS48_PORT_P2, MCS48_PORT_P2) AM_WRITE(p2_w)
68//  AM_RANGE(MCS48_PORT_T0, MCS48_PORT_T0) AM_READ(t0_r)
6967   AM_RANGE(MCS48_PORT_T1, MCS48_PORT_T1) AM_READ(t1_r)
7068ADDRESS_MAP_END
7169
r249095r249096
7573//-------------------------------------------------
7674
7775static MACHINE_CONFIG_FRAGMENT( iskr_1030_keyboard )
78   // XXX check
79   MCFG_CPU_ADD(I8048_TAG, I8048, MCS48_LC_CLOCK(IND_U(47), CAP_P(20.7)))
76   MCFG_CPU_ADD(I8048_TAG, I8048, XTAL_5MHz)
8077   MCFG_CPU_IO_MAP(iskr_1030_keyboard_io)
8178MACHINE_CONFIG_END
8279
r249095r249096
9895
9996INPUT_PORTS_START( iskr_1030_keyboard )
10097   PORT_START("MD00")
101   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
102   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_TAB) PORT_CHAR(UCHAR_MAMEKEY(TAB))
103   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('a') PORT_CHAR('A')
104   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('z') PORT_CHAR('Z')
105   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("?59?") // 0x59 = Inf
106   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_MINUS_PAD) PORT_CHAR(UCHAR_MAMEKEY(MINUS_PAD))
107   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
108   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
98   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
99   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
100   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
101   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
109102
110103   PORT_START("MD01")
111   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
112   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('q') PORT_CHAR('Q')
113   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_S) PORT_CHAR('s') PORT_CHAR('S')
114   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('x') PORT_CHAR('X')
115   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
116   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 7 Home") PORT_CODE(KEYCODE_7_PAD) PORT_CHAR(UCHAR_MAMEKEY(7_PAD))
117   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
118   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
104   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
105   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
106   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
107   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
119108
120109   PORT_START("MD02")
121   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
122   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('w') PORT_CHAR('W')
123   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('d') PORT_CHAR('D')
124   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('c') PORT_CHAR('C')
125   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_RCONTROL) // 0x5a = R/L (R)
126   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 8 " UTF8_UP) PORT_CODE(KEYCODE_8_PAD) PORT_CHAR(UCHAR_MAMEKEY(8_PAD))
127   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
128   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
110   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
111   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
112   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
113   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
129114
130115   PORT_START("MD03")
131   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('@')
132   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('e') PORT_CHAR('E')
133   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('f') PORT_CHAR('F')
134   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_V) PORT_CHAR('v') PORT_CHAR('V')
135   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F12) PORT_CHAR(UCHAR_MAMEKEY(F12)) // 0x5b = Rus
136   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 9 PgUp") PORT_CODE(KEYCODE_9_PAD) PORT_CHAR(UCHAR_MAMEKEY(9_PAD))
137   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
138   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
116   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
117   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
118   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
119   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
139120
140121   PORT_START("MD04")
141   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
142   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_R) PORT_CHAR('r') PORT_CHAR('R')
143   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('g') PORT_CHAR('G')
144   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('b') PORT_CHAR('B')
145   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F1) PORT_CHAR(UCHAR_MAMEKEY(F1))
146   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 4 " UTF8_LEFT) PORT_CODE(KEYCODE_4_PAD) PORT_CHAR(UCHAR_MAMEKEY(4_PAD))
147   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
148   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
122   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
123   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
124   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
125   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
149126
150127   PORT_START("MD05")
151   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
152   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('t') PORT_CHAR('T')
153   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('h') PORT_CHAR('H')
154   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('n') PORT_CHAR('N')
155   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F2) PORT_CHAR(UCHAR_MAMEKEY(F2))
156   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5_PAD) PORT_CHAR(UCHAR_MAMEKEY(5_PAD))
157   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
158   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
128   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
129   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
130   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
131   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
159132
160133   PORT_START("MD06")
161   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
162   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Y) PORT_CHAR('y') PORT_CHAR('Y')
163   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('j') PORT_CHAR('J')
164   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('m') PORT_CHAR('M')
165   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F3) PORT_CHAR(UCHAR_MAMEKEY(F3))
166   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 6 " UTF8_RIGHT) PORT_CODE(KEYCODE_6_PAD) PORT_CHAR(UCHAR_MAMEKEY(6_PAD))
167   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
168   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
134   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
135   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
136   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
137   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
169138
170139   PORT_START("MD07")
171   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('^')
172   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_U) PORT_CHAR('u') PORT_CHAR('U')
173   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('k') PORT_CHAR('K')
174   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_TILDE) PORT_CHAR('`') PORT_CHAR('~')
175   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F4) PORT_CHAR(UCHAR_MAMEKEY(F4))
176   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 1 End") PORT_CODE(KEYCODE_1_PAD) PORT_CHAR(UCHAR_MAMEKEY(1_PAD))
177   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
178   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
140   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
141   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
142   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
143   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
179144
180145   PORT_START("MD08")
181   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('&')
182   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('i') PORT_CHAR('I')
183   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('l') PORT_CHAR('L')
184   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("?2a?")
185   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F5) PORT_CHAR(UCHAR_MAMEKEY(F5))
186   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 2 " UTF8_DOWN) PORT_CODE(KEYCODE_2_PAD) PORT_CHAR(UCHAR_MAMEKEY(2_PAD))
187   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
188   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
146   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
147   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
148   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
149   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
189150
190151   PORT_START("MD09")
191   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('*')
192   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('o') PORT_CHAR('O')
193   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('[') PORT_CHAR('{')
194   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("?5c?") // 0x5c = YO
195   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F6) PORT_CHAR(UCHAR_MAMEKEY(F6))
196   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 3 PgDn") PORT_CODE(KEYCODE_3_PAD) PORT_CHAR(UCHAR_MAMEKEY(3_PAD))
197   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
198   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
152   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
153   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
154   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
155   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
199156
200157   PORT_START("MD10")
201   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR('(')
202   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('p') PORT_CHAR('P')
203   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR(']') PORT_CHAR('}')
204   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
205   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F7) PORT_CHAR(UCHAR_MAMEKEY(F7))
206   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad 0 Ins") PORT_CODE(KEYCODE_0_PAD) PORT_CHAR(UCHAR_MAMEKEY(0_PAD))
207   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
208   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
158   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
159   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
160   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
161   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
209162
210163   PORT_START("MD11")
211   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR(')')
212   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("?36?")
213   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR(':')
214   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>')
215   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F8) PORT_CHAR(UCHAR_MAMEKEY(F8))
216   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Keypad . Del") PORT_CODE(KEYCODE_DEL_PAD) PORT_CHAR(UCHAR_MAMEKEY(DEL_PAD))
217   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
218   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
164   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
165   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
166   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
167   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
219168
220169   PORT_START("MD12")
221   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_CHAR('_')
222   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("?3a?")
223   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR('\'') PORT_CHAR('"')
224   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1) // 0x55
225   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F9) PORT_CHAR(UCHAR_MAMEKEY(F9))
226   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_PLUS_PAD) PORT_CHAR(UCHAR_MAMEKEY(PLUS_PAD))
227   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
228   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
170   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
171   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
172   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
173   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
229174
230175   PORT_START("MD13")
231   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('+')
232   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?')
233   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
234   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_CAPSLOCK) PORT_CHAR(UCHAR_MAMEKEY(CAPSLOCK)) // 0x56
235   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F10) PORT_CHAR(UCHAR_MAMEKEY(F10))
236   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
237   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
238   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
176   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
177   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
178   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
179   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
239180
240181   PORT_START("MD14")
241   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR('\\') PORT_CHAR('|')
242   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_PRTSCR)
243   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_LALT) PORT_CHAR(UCHAR_MAMEKEY(LALT))
244   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F11) PORT_CHAR(UCHAR_MAMEKEY(F11)) // 0x57 = Lat
245   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_NUMLOCK) PORT_CHAR(UCHAR_MAMEKEY(NUMLOCK))
246   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
247   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
248   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
182   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
183   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
184   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
185   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
249186
250187   PORT_START("MD15")
251   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
252   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_LCONTROL) PORT_CHAR(UCHAR_SHIFT_2)
253   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_LSHIFT) PORT_CHAR(UCHAR_SHIFT_1) // 0x54
254   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_RALT) // 0x58 = R/L (L)
255   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("Scroll Lock Break") PORT_CODE(KEYCODE_SCRLOCK) PORT_CHAR(UCHAR_MAMEKEY(SCRLOCK))
256   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
257   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
258   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
188   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
189   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
190   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
191   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
192
193   PORT_START("MD16")
194   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
195   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
196   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
197   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
198
199   PORT_START("MD17")
200   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
201   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
202   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
203   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
204
205   PORT_START("MD18")
206   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
207   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
208   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
209   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
210
211   PORT_START("MD19")
212   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
213   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
214   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
215   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
216
217   PORT_START("MD20")
218   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
219   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
220   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
221   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
222
223   PORT_START("MD21")
224   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
225   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
226   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
227   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
228
229   PORT_START("MD22")
230   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
231   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
232   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
233   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
234
235   PORT_START("MD23")
236   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD )
237   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD )
238   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD )
239   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD )
259240INPUT_PORTS_END
260241
261242
r249095r249096
298279      m_md13(*this, "MD13"),
299280      m_md14(*this, "MD14"),
300281      m_md15(*this, "MD15"),
282      m_md16(*this, "MD16"),
283      m_md17(*this, "MD17"),
284      m_md18(*this, "MD18"),
285      m_md19(*this, "MD19"),
286      m_md20(*this, "MD20"),
287      m_md21(*this, "MD21"),
288      m_md22(*this, "MD22"),
289      m_md23(*this, "MD23"),
301290      m_p1(0),
302291      m_p2(0),
303292      m_q(0)
r249095r249096
313302{
314303   set_pc_kbdc_device();
315304
316   // state saving
305   m_ram.resize(0x100);
306   save_item(NAME(m_ram));
307
308   save_item(NAME(m_bus));
317309   save_item(NAME(m_p1));
318310   save_item(NAME(m_p2));
319311   save_item(NAME(m_q));
r249095r249096
351343
352344
353345//-------------------------------------------------
354//  t0_r - XXX ENT0 CLK
346//  t1_r -
355347//-------------------------------------------------
356348
357READ8_MEMBER( iskr_1030_keyboard_device::t0_r )
349READ8_MEMBER( iskr_1030_keyboard_device::t1_r )
358350{
359   return 0;
360//  return clock_signal();
351   UINT8 data = data_signal();
352   UINT8 bias = m_p1 & 15;
353
354   if (!BIT(m_p1, 7)) {
355      DBG_LOG(2,0,( "%s: t1_r (l) %d\n", tag(), data));
356      return data;
357   }
358
359   if (bias) {
360      DBG_LOG(2,0,( "%s: t1_r (b) %d\n", tag(), bias));
361      return 1;
362   }
363
364   data = 0;
365   switch (m_bus >> 2)
366   {
367   case  0<<1: data = m_md00->read(); break;
368   case  1<<1: data = m_md01->read(); break;
369   case  2<<1: data = m_md02->read(); break;
370   case  3<<1: data = m_md03->read(); break;
371   case  4<<1: data = m_md04->read(); break;
372   case  5<<1: data = m_md05->read(); break;
373   case  6<<1: data = m_md06->read(); break;
374   case  7<<1: data = m_md07->read(); break;
375   case  8<<1: data = m_md08->read(); break;
376   case  9<<1: data = m_md09->read(); break;
377   case 10<<1: data = m_md10->read(); break;
378   case 11<<1: data = m_md11->read(); break;
379   case  (0<<1)+1: data = m_md12->read(); break;
380   case  (1<<1)+1: data = m_md13->read(); break;
381   case  (2<<1)+1: data = m_md14->read(); break;
382   case  (3<<1)+1: data = m_md15->read(); break;
383   case  (4<<1)+1: data = m_md16->read(); break;
384   case  (5<<1)+1: data = m_md17->read(); break;
385   case  (6<<1)+1: data = m_md18->read(); break;
386   case  (7<<1)+1: data = m_md19->read(); break;
387   case  (8<<1)+1: data = m_md20->read(); break;
388   case  (9<<1)+1: data = m_md21->read(); break;
389   case (10<<1)+1: data = m_md22->read(); break;
390   case (11<<1)+1: data = m_md23->read(); break;
391   }
392   data = BIT(data, m_bus&3);
393
394   DBG_LOG(2,0,( "%s: t1_r (k r%d c%d) %d\n", tag(), m_bus&3, m_bus>>2, data));
395   return data;
361396}
362397
363398
364399//-------------------------------------------------
365//  t1_r - OK
400//  ram_w -
366401//-------------------------------------------------
367402
368READ8_MEMBER( iskr_1030_keyboard_device::t1_r )
403WRITE8_MEMBER( iskr_1030_keyboard_device::ram_w )
369404{
370   UINT8 data = data_signal();
405   DBG_LOG(2,0,( "%s: ram_w[%02x] <- %02x\n", tag(), offset, data));
371406
372   DBG_LOG(2,0,( "%s: t1_r %d\n", tag(), data));
407   m_bus = offset;
408   m_ram[offset] = data;
409}
373410
374   return data;
411
412//-------------------------------------------------
413//  ram_r -
414//-------------------------------------------------
415
416READ8_MEMBER( iskr_1030_keyboard_device::ram_r )
417{
418   DBG_LOG(2,0,( "%s: ram_r[%02x] = %02x\n", tag(), offset, m_ram[offset]));
419   
420   return m_ram[offset];
375421}
376422
377423
r249095r249096
382428READ8_MEMBER( iskr_1030_keyboard_device::p1_r )
383429{
384430   /*
385
386431       bit     description
387432
388433       0       -REQ IN
r249095r249096
393438       5
394439       6
395440       7
396
397441   */
398442
399443   UINT8 data = 0;
r249095r249096
413457   /*
414458       bit     description
415459
416       0
417       1
418       2
419       3
420       4
421       5       LED XXX
422       6       LED XXX
423       7       LED XXX
460       0       ...
461       1       ...
462       2       ...
463       3       (not connected)
464       4       SPEAKER
465       5       LED RUS/LAT
466       6       LED NLK
467       7       LED CLK
424468   */
425469   DBG_LOG(1,0,( "%s: p2_w %02x\n", tag(), data));
426470
427   m_p1 = data;
471   m_p2 = data;
428472}
429473
430474
r249095r249096
442486       2       XXX
443487       3       XXX
444488       4       CLOCK out
445       5       DATA out (inverted!)
489       5       DATA out
446490       6       XXX
447       7       XXX
491       7       POLL GATE
448492   */
449   DBG_LOG(1,0,( "%s: p1_w %02x (clk %d data %d)\n", tag(), data, BIT(data, 4), BIT(data, 5)));
450493
494   m_p1 = data;
495
496   DBG_LOG(1,0,( "%s: p1_w %02x (c %d d %d bias %d)\n", tag(), data, BIT(data, 4), BIT(data, 5), data&15));
497
451498   m_pc_kbdc->data_write_from_kb(BIT(data, 5));
452499   m_pc_kbdc->clock_write_from_kb(BIT(data, 4));
453500}
trunk/src/emu/bus/pc_kbd/iskr1030.h
r249095r249096
3636   virtual machine_config_constructor device_mconfig_additions() const;
3737   virtual ioport_constructor device_input_ports() const;
3838
39   DECLARE_READ8_MEMBER( ram_r );
40   DECLARE_WRITE8_MEMBER( ram_w );
3941   DECLARE_READ8_MEMBER( p1_r );
4042   DECLARE_WRITE8_MEMBER( p1_w );
4143   DECLARE_WRITE8_MEMBER( p2_w );
42   DECLARE_READ8_MEMBER( t0_r );
4344   DECLARE_READ8_MEMBER( t1_r );
4445
4546protected:
r249095r249096
6970   required_ioport m_md13;
7071   required_ioport m_md14;
7172   required_ioport m_md15;
73   required_ioport m_md16;
74   required_ioport m_md17;
75   required_ioport m_md18;
76   required_ioport m_md19;
77   required_ioport m_md20;
78   required_ioport m_md21;
79   required_ioport m_md22;
80   required_ioport m_md23;
7281
82   dynamic_buffer m_ram;
83   UINT8 m_bus;
7384   UINT8 m_p1;
7485   UINT8 m_p2;
7586   int m_q;
trunk/src/emu/cpu/t11/t11.c
r249095r249096
3636
3737
3838const device_type T11 = &device_creator<t11_device>;
39const device_type K1801VM2 = &device_creator<k1801vm2_device>;
3940
4041
42k1801vm2_device::k1801vm2_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
43   : t11_device(mconfig, K1801VM2, "K1801VM2", tag, owner, clock, "k1801vm2", __FILE__)
44{
45}
46
47t11_device::t11_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source)
48   : cpu_device(mconfig, type, name, tag, owner, clock, shortname, source)
49   , m_program_config("program", ENDIANNESS_LITTLE, 16, 16, 0)
50   , c_initial_mode(0)
51{
52   m_is_octal = true;
53   memset(m_reg, 0x00, sizeof(m_reg));
54   memset(&m_psw, 0x00, sizeof(m_psw));
55}
56
4157t11_device::t11_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
4258   : cpu_device(mconfig, T11, "T11", tag, owner, clock, "t11", __FILE__)
4359   , m_program_config("program", ENDIANNESS_LITTLE, 16, 16, 0)
r249095r249096
294310   }
295311}
296312
313void k1801vm2_device::state_string_export(const device_state_entry &entry, std::string &str)
314{
315   switch (entry.index())
316   {
317      case STATE_GENFLAGS:
318         strprintf(str, "%c%c%c%c%c%c%c%c%c",
319            m_psw.b.l & 0x100 ? 'H':'.',
320            m_psw.b.l & 0x80 ? 'P':'.',
321            m_psw.b.l & 0x40 ? '?':'.',
322            m_psw.b.l & 0x20 ? '?':'.',
323            m_psw.b.l & 0x10 ? 'T':'.',
324            m_psw.b.l & 0x08 ? 'N':'.',
325            m_psw.b.l & 0x04 ? 'Z':'.',
326            m_psw.b.l & 0x02 ? 'V':'.',
327            m_psw.b.l & 0x01 ? 'C':'.'
328         );
329         break;
330   }
331}
297332
333
298334/*************************************
299335 *
300336 *  CPU reset
r249095r249096
326362   m_wait_state = 0;
327363}
328364
365void k1801vm2_device::device_reset()
366{
367   t11_device::device_reset();
368   
369   PC = RWORD(c_initial_mode);
370   PSW = RWORD(c_initial_mode+2);
371}
329372
330373
331374/*************************************
trunk/src/emu/cpu/t11/t11.h
r249095r249096
3737public:
3838   // construction/destruction
3939   t11_device(const machine_config &mconfig, const char *_tag, device_t *_owner, UINT32 _clock);
40   t11_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source);
4041
4142   // static configuration helpers
4243   static void set_initial_mode(device_t &device, const UINT16 mode) { downcast<t11_device &>(device).c_initial_mode = mode; }
r249095r249096
6566   virtual UINT32 disasm_max_opcode_bytes() const { return 6; }
6667   virtual offs_t disasm_disassemble(char *buffer, offs_t pc, const UINT8 *oprom, const UINT8 *opram, UINT32 options);
6768
68private:
69protected:
6970   address_space_config m_program_config;
7071
7172   UINT16 c_initial_mode;
r249095r249096
11331134   void sub_ixd_ixd(UINT16 op);
11341135};
11351136
1137class k1801vm2_device : public t11_device
1138{
1139public:
1140   // construction/destruction
1141   k1801vm2_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
11361142
1143protected:
1144   // device-level overrides
1145   virtual void device_reset();
1146
1147   // device_state_interface overrides
1148   void state_string_export(const device_state_entry &entry, std::string &str);
1149};
1150
1151
11371152extern const device_type T11;
1153extern const device_type K1801VM2;
11381154
11391155
11401156#endif /* __T11_H__ */
trunk/src/emu/drivers/emudummy.c
r249095r249096
3333ROM_END
3434
3535
36GAME( 1900, __dummy, 0, __dummy, 0, driver_device, 0, ROT0, "(none)", "Dummy", GAME_NO_SOUND )
36GAME( 1900, __dummy, 0, __dummy, 0, driver_device, 0, ROT0, "(none)", "Dummy", MACHINE_NO_SOUND )
trunk/src/emu/machine/68230pit.c
r249095r249096
11// license:BSD-3-Clause
22// copyright-holders:Joakim Larsson Edstr??m
33/**********************************************************************
4*
5*   Motorola MC68230 PI/T Parallell Interface and Timer
6*
7*  Revisions
8*  2015-07-15 JLE initial
9*
10*  Todo
11*  - Add clock and timers
12*  - Add all missing registers
13*  - Add configuration
14**********************************************************************/
415
5    Motorola MC68230 PI/T Parallell Interface and Timer
16#include "68230pit.h"
617
7Revisions
8 2015-07-15 JLE initial
18#define LOG(x) /* x */
919
10Todo
11 - Add clock and timers
12 - Add all missing registers
13 - Add configuration
14**********************************************************************/
20//**************************************************************************
21//  DEVICE TYPE DEFINITIONS
22//**************************************************************************
1523
16/*
17Force CPU-1 init sequence
180801EA 0E0000 W 0000 PGCR  data_w: 0000 -> 0000 & 00ff
190801EA 0E0002 W 0000 PSRR  data_w: 0000 -> 0001 & 00ff
200801EA 0E0004 W FFFF PADDR data_w: 00ff -> 0002 & 00ff
210801EA 0E0006 W 0000 PBDDR data_w: 0000 -> 0003 & 00ff
220801F0 0E000C W 6060 PACR  data_w: 0060 -> 0006 & 00ff
230801F6 0E000E W A0A0 PBCR  data_w: 00a0 -> 0007 & 00ff
240801FC 0E0000 W 3030 PGCR  data_w: 0030 -> 0000 & 00ff
25080202 0E000E W A8A8 PBCR  data_w: 00a8 -> 0007 & 00ff
26080210 0E000E W A0A0 PBCR  data_w: 00a0 -> 0007 & 00ff
24const device_type PIT68230 = &device_creator<pit68230_device>;
2725
28Force CPU-1 after one keypress in terminal
29081DC0 0E000C W 6868 PACR
30081DC8 0E000C W 6060 PACR
31*/
26//-------------------------------------------------
27//  pit68230_device - constructors
28//-------------------------------------------------
29pit68230_device::pit68230_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, UINT32 variant, const char *shortname, const char *source)
30        : device_t (mconfig, type, name, tag, owner, clock, shortname, source),
31        device_execute_interface (mconfig, *this)
32        , m_icount (0)
33        , m_write_pa (*this)
34        , m_write_h2 (*this)
35{
36}
3237
3338
34#include "emu.h"
35#include "68230pit.h"
39pit68230_device::pit68230_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
40        : device_t (mconfig, PIT68230, "PIT68230", tag, owner, clock, "pit68230", __FILE__),
41        device_execute_interface (mconfig, *this)
42        , m_icount (0)
43        , m_write_pa (*this)
44        , m_write_h2 (*this)
45{
46}
3647
37/***************************************************************************
38    IMPLEMENTATION
39***************************************************************************/
48//-------------------------------------------------
49//  device_start - device-specific startup
50//-------------------------------------------------
51void pit68230_device::device_start ()
52{
53        LOG (logerror ("PIT68230 device started\n"));
54        m_icountptr = &m_icount;
4055
41// device type definition
42const device_type PIT68230 = &device_creator<pit68230_device>;
56        // resolve callbacks
57        m_write_pa.resolve_safe ();
58        m_write_h2.resolve_safe ();
59}
4360
4461//-------------------------------------------------
45//  pit68230_device - constructor
62//  device_reset - device-specific reset
4663//-------------------------------------------------
47
48pit68230_device::pit68230_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
49      : device_t(mconfig, PIT68230, "Motorola 68230 PI/T", tag, owner, clock, "pit68230", __FILE__)
64void pit68230_device::device_reset ()
5065{
66        LOG (logerror ("PIT68230 device reseted\n"));
67        m_pgcr = 0;
68        m_psrr = 0;
69        m_paddr = 0;
70        m_pbddr = 0;
71        m_pcddr = 0;
72        m_pacr = 0; m_write_h2 (m_pacr);
73        m_pbcr = 0;
74        m_padr = 0; m_write_pa ((offs_t)0, m_padr); // TODO: check PADDR
75        m_pbdr = 0;
76        m_psr = 0;
5177}
5278
53void pit68230_device::device_start()
79//-------------------------------------------------
80//  device_timer - handler timer events
81//-------------------------------------------------
82void pit68230_device::device_timer (emu_timer &timer, device_timer_id id, INT32 param, void *ptr)
5483{
55   printf("PIT68230 device started\n");
5684}
5785
58void pit68230_device::device_reset()
86void pit68230_device::h1_set (UINT8 state)
5987{
60   printf("PIT68230 device reseted\n");
61   m_pgcr = 0;
62   m_psrr = 0;
63   m_paddr = 0;
64   m_pbddr = 0;
65   m_pcddr = 0;
66   m_pacr = 0;
67   m_pbcr = 0;
68   m_padr = 0;
69   m_pbdr = 0;
70   m_psr = 0;
88        LOG (logerror ("h1_set %d @ m_psr %2x => ", state, m_psr));
89        if (state) m_psr |= 1; else m_psr &= ~1;
90        LOG (logerror ("%02x %lld\n", m_psr, machine ().firstcpu->total_cycles ()));
7191}
7292
73WRITE8_MEMBER( pit68230_device::data_w )
93void pit68230_device::portb_setbit (UINT8 bit, UINT8 state)
7494{
75   printf("data_w: %04x -> ", data);
76   switch (offset)
77   {
78   case PIT_68230_PGCR:
79   printf("PGCR");
80   m_pgcr = data;
81   break;
82   case PIT_68230_PSRR:
83   printf("PSRR");
84   m_psrr = data;
85   break;
86   case PIT_68230_PADDR:
87   printf("PADDR");
88   m_paddr = data;
89   break;
90   case PIT_68230_PBDDR:
91   printf("PBDDR");
92   m_pbddr = data;
93   break;
94   case PIT_68230_PACR:
95   printf("PACR");
96   m_pacr = data;
97   break;
98   case PIT_68230_PBCR:
99   printf("PBCR");
100   m_pbcr = data;
101   break;
102   case PIT_68230_PADR:
103   printf("PADR");
104   m_padr = data;
105   break;
106   case PIT_68230_PSR:
107   printf("PSR");
108   m_padr = data;
109   break;
110   default:
111   printf("unhandled register %02x", offset);
112   }
113   printf("\n");
95        LOG (logerror ("portb_setbit %d/%d @ m_pbdr %2x => ", bit, state, m_pbdr));
96        if (state) m_pbdr |= (1 << bit); else m_pbdr &= ~(1 << bit);
97        LOG (logerror ("%02x %lld\n", m_pbdr, machine ().firstcpu->total_cycles ()));
11498}
11599
116READ8_MEMBER( pit68230_device::data_r )
100//-------------------------------------------------
101//  execute_run -
102//-------------------------------------------------
103void pit68230_device::execute_run ()
117104{
118   UINT8 data = 0;
105        do {
106                synchronize ();
119107
120   printf("data_r: ");
121   switch (offset)
122   {
123   case PIT_68230_PGCR:
124   printf("PGCR");
125   data = m_pgcr;
126   break;
127   case PIT_68230_PSRR:
128   printf("PSRR");
129   data = m_psrr;
130   break;
131   case PIT_68230_PADDR:
132   printf("PADDR");
133   data = m_paddr;
134   break;
135   case PIT_68230_PBDDR:
136   printf("PBDDR");
137   data = m_pbddr;
138   break;
139   case PIT_68230_PACR:
140   printf("PACR");
141   data = m_pacr;
142   break;
143   case PIT_68230_PBCR:
144   printf("PBCR");
145   data = m_pbcr;
146   break;
147   case PIT_68230_PADR:
148   printf("PADR");
149   data = m_padr;
150   break;
151   case PIT_68230_PBDR:
152   /* 4.6.2. PORT B DATA REGISTER (PBDR). The port B data register is a holding register for moving data
153to and from port B pins. The port B data direction register determines whether each pin is an input (zero)
154or an output (one). This register is readable and writable at all times. Depending on the chosen mode/submode,
155reading or writing may affect the double-buffered handshake mechanism. The port B data register is not affected
156by the assertion of the RESET pin. PB0-PB7 sits on pins 17-24 on a 48 pin DIP package */
157   printf("PBDR");
158   data = m_pbdr;
159   //    data = (m_pbdr & 0xfc) | 1; // CPU-1 centronics interface expects to see 2 lowest bits equal 1 for printer
160   break;
161   case PIT_68230_PSR:
162   printf("PSR");
163   data = m_psr;
164   //    data = m_psr | 1; // CPU-1 centronics interface expects status to be non zero
165   break;
166   default:
167   printf("unhandled register %02x", offset);
168   data = 0;
169   }
170   printf("\n");
108                m_icount--;
109        } while (m_icount > 0);
110}
171111
172   return data;
112LOG (static INT32 ow_cnt = 0);
113LOG (static INT32 ow_data = 0);
114LOG (static INT32 ow_ofs = 0);
115
116WRITE8_MEMBER (pit68230_device::write){
117        switch (offset) {
118        case PIT_68230_PGCR:
119                m_pgcr = data;
120                break;
121
122        case PIT_68230_PSRR:
123                m_psrr = data;
124                break;
125
126        case PIT_68230_PADDR:
127                m_paddr = data;
128                break;
129
130        case PIT_68230_PBDDR:
131                m_pbddr = data;
132                break;
133
134        case PIT_68230_PCDDR:
135                m_pcddr = data;
136                break;
137
138        case PIT_68230_PACR:
139                m_pacr = data;
140                // callbacks
141                /*PACR in Mode 0
142                 * 5 43  H2 Control in Submode 00 && 01
143                 * ------------------------------------
144                 * 0 XX  Input pin  - edge-sensitive status input, H2S is set on an asserted edge.
145                 * 1 00  Output pin - negated, H2S is always clear.
146                 * 1 01  Output pin - asserted, H2S is always clear.
147                 * 1 10  Output pin - interlocked input handshake protocol, H2S is always clear.
148                 * 1 11  Output pin - pulsed input handshake protocol, H2S is always clear.
149                 *
150                 * 5 43  H2 Control in Submode 1x
151                 * ------------------------------------
152                 * 0 XX  Input pin  - edge-sensitive status input, H2S is set on an asserted edge.
153                 * 1 X0  Output pin - negated, H2S is always cleared.
154                 * 1 X1  Output pin - asserted, H2S is always cleared.
155                 */
156                m_write_h2 (m_pacr & 0x08 ? 1 : 0); // TODO: Check mode and submodes
157                break;
158
159        case PIT_68230_PBCR:
160                m_pbcr = data;
161                break;
162
163        case PIT_68230_PADR:
164                m_padr = data;
165                // callbacks
166                m_write_pa ((offs_t)0, m_padr); // TODO: check PADDR
167                break;
168
169        case PIT_68230_PSR:
170                m_psr = data;
171                break;
172
173        default:
174                LOG (logerror ("unhandled register %02x", offset));
175        }
176
177        LOG (if (offset != ow_ofs || data != ow_data || ow_cnt >= 1000) {
178                logerror ("\npit68230_device::write: previous identical operation performed %02x times\n", ow_cnt);
179                ow_cnt = 0;
180                ow_data = data;
181                ow_ofs = offset;
182                logerror ("pit68230_device::write: offset=%02x data=%02x %lld\n", ow_ofs, ow_data, machine ().firstcpu->total_cycles ());
183        }
184                else
185                        ow_cnt++; )
173186}
187
188LOG (static INT32 or_cnt = 0);
189LOG (static INT32 or_data = 0);
190LOG (static INT32 or_ofs = 0);
191
192READ8_MEMBER (pit68230_device::read){
193        UINT8 data = 0;
194
195        switch (offset) {
196        case PIT_68230_PGCR:
197                data = m_pgcr;
198                break;
199
200        case PIT_68230_PSRR:
201                data = m_psrr;
202                break;
203
204        case PIT_68230_PADDR:
205                data = m_paddr;
206                break;
207
208        case PIT_68230_PBDDR:
209                data = m_pbddr;
210                break;
211
212        case PIT_68230_PCDDR:
213                data = m_pcddr;
214                break;
215
216        case PIT_68230_PACR:
217                data = m_pacr;
218                break;
219
220        case PIT_68230_PBCR:
221                data = m_pbcr;
222                break;
223
224        case PIT_68230_PADR:
225                data = m_padr;
226                break;
227
228        case PIT_68230_PBDR:
229                /* 4.6.2. PORT B DATA REGISTER (PBDR). The port B data register is a holding
230                 * register for moving data to and from port B pins. The port B data direction
231                 * register determines whether each pin is an input (zero) or an output (one).
232                 * This register is readable and writable at all times. Depending on the chosen
233                 * mode/submode, reading or writing may affect the double-buffered handshake
234                 * mechanism. The port B data register is not affected by the assertion of the
235                 * RESET pin. PB0-PB7 sits on pins 17-24 on a 48 pin DIP package */
236                data = m_pbdr;
237                break;
238
239        case PIT_68230_PSR:
240                /* 4.8. PORT STATUS REGISTER (PSR) The port status register contains information about
241                 * handshake pin activity. Bits 7-4 show the instantaneous level of the respective handshake
242                 * pin, and are independent of the handshake pin sense bits in the port general control
243                 * register. Bits 3-0 are the respective status bits referred to throughout this document.
244                 * Their interpretation depends on the programmed mode/submode of the PI/T. For bits
245                 * 3-0 a one is the active or asserted state. */
246                data = m_psr;
247                break;
248
249        default:
250                LOG (logerror ("unhandled register %02x", offset));
251                data = 0;
252        }
253
254        LOG (if (offset != or_ofs || data != or_data || or_cnt >= 1000) {
255                logerror ("\npit68230_device::read: previous identical operation performed %02x times\n", or_cnt);
256                or_cnt = 0;
257                or_data = data;
258                or_ofs = offset;
259                logerror ("pit68230_device::read: offset=%02x data=%02x %lld\n", or_ofs, or_data, machine ().firstcpu->total_cycles ());
260        }
261                else
262                        or_cnt++; )
263
264        return data;
265}
trunk/src/emu/machine/68230pit.h
r249095r249096
11// license:BSD-3-Clause
22// copyright-holders:Joakim Larsson Edstr??m
33/**********************************************************************
4*
5*   Motorola MC68230 PI/T Parallell Interface and Timer
6*
7*                           _____   _____
8*                   D5   1 |*    \_/     | 48  D4
9*                   D6   2 |             | 47  D3
10*                   D7   3 |             | 46  D2
11*                  PA0   4 |             | 45  D1
12*                  PA1   5 |             | 44  D0
13*                  PA2   6 |             | 43  R/W*
14*                  PA3   7 |             | 42  DTACK*
15*                  PA4   8 |             | 41  CS*
16*                  PA5   9 |             | 40  CLK
17*                  PA6  10 |             | 39  RESET*
18*                  PA7  11 |             | 38  VSS
19*                  Vcc  12 |   TS68230   | 37  PC7/TIACK*
20*                   H1  13 |   SC87845   | 36  PC6/PIACK*
21*                   H2  14 |             | 35  PC5/PIRQ*
22*                   H3  15 |             | 34  PC4/DMAREQ*
23*                   H4  16 |             | 33  PC3/TOUT
24*                  PB0  17 |             | 32  PC2/TIN
25*                  PB1  18 |             | 31  PC1
26*                  PB2  19 |             | 30  PC0
27*                  PB3  20 |             | 29  RS1
28*                  PB4  21 |             | 28  RS2
29*                  PB5  22 |             | 27  RS3
30*                  PB6  23 |             | 26  RS4
31*                  PB7  24 |_____________| 25  RS5
32*
33**********************************************************************/
434
5    Motorola MC68230 PI/T Parallell Interface and Timer
6
7**********************************************************************/
835#pragma once
936
1037#ifndef __68230PIT_H__
r249095r249096
1239
1340#include "emu.h"
1441
42//**************************************************************************
43//  INTERFACE CONFIGURATION MACROS
44//**************************************************************************
45
46#define MCFG_PIT68230_PA_OUTPUT_CALLBACK(_write) \
47        devcb = &pit68230_device::set_pa_wr_callback (*device, DEVCB_ ## _write);
48
49#define MCFG_PIT68230_PB_OUTPUT_CALLBACK(_write) \
50        devcb = &pit68230_device::set_pb_wr_callback (*device, DEVCB_ ## _write);
51
52#define MCFG_PIT68230_H2_CALLBACK(_write) \
53        devcb = &pit68230_device::set_h2_wr_callback (*device, DEVCB_ ## _write);
54
1555/*-----------------------------------------------------------------------
16  Registers                RS1-RS5   R/W Description
17-------------------------------------------------------------------------*/
56 * Registers                RS1-RS5   R/W Description
57 * -------------------------------------------------------------------------*/
1858#define PIT_68230_PGCR        0x00 /* RW Port General Control register   */
1959#define PIT_68230_PSRR        0x01 /* RW Port Service Request register   */
2060#define PIT_68230_PADDR       0x02 /* RW Port A Data Direction register  */
r249095r249096
4282//**************************************************************************
4383//  TYPE DEFINITIONS
4484//**************************************************************************
45class pit68230_device :  public device_t
85class pit68230_device :  public device_t, public device_execute_interface
4686{
4787public:
48   // construction/destruction
49   pit68230_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
50   DECLARE_WRITE8_MEMBER( data_w );
51   DECLARE_READ8_MEMBER( data_r );
88// construction/destruction
89pit68230_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, UINT32 variant, const char *shortname, const char *source);
90pit68230_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
91template<class _Object> static devcb_base &set_pa_wr_callback (device_t &device, _Object object)
92{
93        return downcast<pit68230_device &>(device).m_write_pa.set_callback (object);
94}
95template<class _Object> static devcb_base &set_h2_wr_callback (device_t &device, _Object object)
96{
97        return downcast<pit68230_device &>(device).m_write_h2.set_callback (object);
98}
5299
100DECLARE_WRITE8_MEMBER (write);
101DECLARE_READ8_MEMBER (read);
102
103void h1_set (UINT8 state);
104void portb_setbit (UINT8 bit, UINT8 state);
105
53106protected:
54   // device-level overrides
55   virtual void device_start();
56   virtual void device_reset();
107// device-level overrides
108virtual void device_start ();
109virtual void device_reset ();
110virtual void device_timer (emu_timer &timer, device_timer_id id, int param, void *ptr);
111virtual void execute_run ();
112int m_icount;
113devcb_write8 m_write_pa;
114devcb_write_line m_write_h2;
57115
58private:
59      UINT8  m_pgcr;  // Port General Control register
60   UINT8  m_psrr;  // Port Service Request register
61   UINT8  m_paddr; // Port A Data Direction register
62   UINT8  m_pbddr; // Port B Data Direction register
63   UINT8  m_pcddr; // Port C Data Direction register
64   UINT8  m_pacr;  // Port A Control register
65   UINT8  m_pbcr;  // Port B Control register
66   UINT8  m_padr;  // Port A Data register
67   UINT8  m_pbdr;  // Port B Data register
68   UINT8  m_psr;   // Port Status Register
116// peripheral ports
117UINT8 m_pgcr;           // Port General Control register
118UINT8 m_psrr;           // Port Service Request register
119UINT8 m_paddr;          // Port A Data Direction register
120UINT8 m_pbddr;          // Port B Data Direction register
121UINT8 m_pcddr;          // Port C Data Direction register
122UINT8 m_pacr;           // Port A Control register
123UINT8 m_pbcr;           // Port B Control register
124UINT8 m_padr;           // Port A Data register
125UINT8 m_pbdr;           // Port B Data register
126UINT8 m_psr;            // Port Status Register
69127};
70128
71
72129// device type definition
73130extern const device_type PIT68230;
74
75#endif // __68230PIT__
131#endif /* __68230PIT_H__ */
trunk/src/emu/machine/at_keybc.c
r249095r249096
2424   AM_RANGE(MCS48_PORT_P1, MCS48_PORT_P1) AM_READ( p1_r)
2525   AM_RANGE(MCS48_PORT_P2, MCS48_PORT_P2) AM_READWRITE(p2_r, p2_w)
2626ADDRESS_MAP_END
27
28static INPUT_PORTS_START( at_keybc )
29   PORT_START("DSW")
30   PORT_BIT(     0xbf, 0xbf, IPT_UNUSED )
31   PORT_DIPNAME( 0x40, 0x40, "Display switch")
32   PORT_DIPSETTING(    0x40, "Monochrome adapter" )
33   PORT_DIPSETTING(    0x00, "Color/Graphics adapter" )
34INPUT_PORTS_END
35
2736// machine fragment
2837static MACHINE_CONFIG_FRAGMENT( at_keybc )
2938   MCFG_CPU_ADD("at_keybc", I8042, DERIVED_CLOCK(1,1))
r249095r249096
7281}
7382
7483//-------------------------------------------------
84//  input_ports - device-specific input ports
85//-------------------------------------------------
86
87ioport_constructor at_keyboard_controller_device::device_input_ports() const
88{
89   return INPUT_PORTS_NAME( at_keybc );
90}
91
92//-------------------------------------------------
7593//  machine_config_additions - return a pointer to
7694//  the device's machine fragment
7795//-------------------------------------------------
r249095r249096
139157*/
140158READ8_MEMBER( at_keyboard_controller_device::p1_r )
141159{
142   return 0xbf;
160   return ioport("DSW")->read();
143161}
144162
145163READ8_MEMBER( at_keyboard_controller_device::p2_r )
trunk/src/emu/machine/at_keybc.h
r249095r249096
7979   virtual void device_reset();
8080
8181   virtual const rom_entry *device_rom_region() const;
82   virtual ioport_constructor device_input_ports() const;
8283   virtual machine_config_constructor device_mconfig_additions() const;
8384
8485private:
trunk/src/emu/netlist/nl_base.h
r249095r249096
12331233      pnamedlist_t<core_device_t *> m_started_devices;
12341234   #endif
12351235
1236   ATTR_COLD plog_base<NL_DEBUG> &log() { return m_log; }
12361237   ATTR_COLD const plog_base<NL_DEBUG> &log() const { return m_log; }
12371238
12381239   protected:
trunk/src/emu/netlist/nl_setup.h
r249095r249096
198198
199199      void model_parse(const pstring &model, model_map_t &map);
200200
201      plog_base<NL_DEBUG> &log() { return netlist().log(); }
201202      const plog_base<NL_DEBUG> &log() const { return netlist().log(); }
202203
203204   protected:
trunk/src/emu/netlist/plib/pstring.c
r249095r249096
1414
1515#include "pstring.h"
1616#include "palloc.h"
17#include "plists.h"
1718
1819template<>
1920pstr_t pstring_t<putf8_traits>::m_zero = pstr_t(0);
r249095r249096
305306// static stuff ...
306307// ----------------------------------------------------------------------------------------
307308
309/*
310 * Cached allocation of string memory
311 *
312 * This improves startup performance by 30%.
313 */
314
315#if 1
316
317static pstack_t<pstr_t *> *stk = NULL;
318
319static inline unsigned countleadbits(unsigned x)
320{
321#ifndef count_leading_zeros
322   unsigned msk;
323   unsigned ret;
324   if (x < 0x100)
325   {
326      msk = 0x80;
327      ret = 24;
328   }
329   else if (x < 0x10000)
330   {
331      msk = 0x8000;
332      ret = 16;
333   }
334   else if (x < 0x1000000)
335   {
336      msk = 0x800000;
337      ret = 8;
338   }
339   else
340   {
341      msk = 0x80000000;
342      ret = 0;
343   }
344   while ((msk & x) == 0 && ret < 31)
345   {
346      msk = msk >> 1;
347      ret++;
348   }
349   return ret;
350#else
351   return count_leading_zeros(x);
352#endif
353}
354
308355template<typename F>
309356void pstring_t<F>::sfree(pstr_t *s)
310357{
311358   s->m_ref_count--;
312359   if (s->m_ref_count == 0 && s != &m_zero)
313360   {
361      if (stk != NULL)
362      {
363         unsigned sn= ((32 - countleadbits(s->len())) + 1) / 2;
364         stk[sn].push(s);
365      }
366      else
367         pfree_array(((char *)s));
368      //_mm_free(((char *)s));
369   }
370}
371
372template<typename F>
373pstr_t *pstring_t<F>::salloc(int n)
374{
375   if (stk == NULL)
376      stk = palloc_array(pstack_t<pstr_t *>, 17);
377   pstr_t *p;
378   unsigned sn= ((32 - countleadbits(n)) + 1) / 2;
379   unsigned size = sizeof(pstr_t) + (1<<(sn * 2)) + 1;
380   if (stk[sn].empty())
381      p = (pstr_t *) palloc_array(char, size);
382   else
383   {
384      //printf("%u %u\n", sn, (unsigned) stk[sn].count());
385      p = stk[sn].pop();
386   }
387
388   //  str_t *p = (str_t *) _mm_malloc(size, 8);
389   p->init(n);
390   return p;
391}
392template<typename F>
393void pstring_t<F>::resetmem()
394{
395   if (stk != NULL)
396   {
397      for (unsigned i=0; i<=16; i++)
398      {
399         for (; stk[i].count() > 0; )
400            pfree_array(stk[i].pop());
401      }
402      pfree_array(stk);
403      stk = NULL;
404   }
405}
406
407
408#else
409template<typename F>
410void pstring_t<F>::sfree(pstr_t *s)
411{
412   s->m_ref_count--;
413   if (s->m_ref_count == 0 && s != &m_zero)
414   {
314415      pfree_array(((char *)s));
315416      //_mm_free(((char *)s));
316417   }
r249095r249096
331432{
332433   // Release the 0 string
333434}
435#endif
334436
437
335438// ----------------------------------------------------------------------------------------
336439// pstring ...
337440// ----------------------------------------------------------------------------------------
trunk/src/emu/netlist/plib/pstring.h
r249095r249096
2222   struct pstr_t
2323   {
2424      //str_t() : m_ref_count(1), m_len(0) { m_str[0] = 0; }
25      pstr_t(const int alen)
25      pstr_t(const unsigned alen)
2626      {
2727         init(alen);
2828      }
29      void init(const int alen)
29      void init(const unsigned alen)
3030      {
3131            m_ref_count = 1;
3232            m_len = alen;
3333            m_str[0] = 0;
3434      }
3535      char *str() { return &m_str[0]; }
36      int len() const  { return m_len; }
36      unsigned len() const  { return m_len; }
3737      int m_ref_count;
3838   private:
39      int m_len;
39      unsigned m_len;
4040      char m_str[1];
4141   };
4242
r249095r249096
548548class pfmt_writer_t
549549{
550550public:
551   pfmt_writer_t()  { }
551   pfmt_writer_t() : m_enabled(true) { }
552552   virtual ~pfmt_writer_t() { }
553553
554554   ATTR_COLD void operator ()(const char *fmt) const
555555   {
556      if (build_enabled) vdowrite(fmt);
556      if (build_enabled && m_enabled) vdowrite(fmt);
557557   }
558558
559559   template<typename T1>
560560   ATTR_COLD void operator ()(const char *fmt, const T1 &v1) const
561561   {
562      if (build_enabled) vdowrite(pfmt(fmt)(v1));
562      if (build_enabled && m_enabled) vdowrite(pfmt(fmt)(v1));
563563   }
564564
565565   template<typename T1, typename T2>
566566   ATTR_COLD void operator ()(const char *fmt, const T1 &v1, const T2 &v2) const
567567   {
568      if (build_enabled) vdowrite(pfmt(fmt)(v1)(v2));
568      if (build_enabled && m_enabled) vdowrite(pfmt(fmt)(v1)(v2));
569569   }
570570
571571   template<typename T1, typename T2, typename T3>
572572   ATTR_COLD void operator ()(const char *fmt, const T1 &v1, const T2 &v2, const T3 &v3) const
573573   {
574      if (build_enabled) vdowrite(pfmt(fmt)(v1)(v2)(v3));
574      if (build_enabled && m_enabled) vdowrite(pfmt(fmt)(v1)(v2)(v3));
575575   }
576576
577577   template<typename T1, typename T2, typename T3, typename T4>
578578   ATTR_COLD void operator ()(const char *fmt, const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4) const
579579   {
580      if (build_enabled) vdowrite(pfmt(fmt)(v1)(v2)(v3)(v4));
580      if (build_enabled && m_enabled) vdowrite(pfmt(fmt)(v1)(v2)(v3)(v4));
581581   }
582582
583583   template<typename T1, typename T2, typename T3, typename T4, typename T5>
584584   ATTR_COLD void operator ()(const char *fmt, const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5) const
585585   {
586      if (build_enabled) vdowrite(pfmt(fmt)(v1)(v2)(v3)(v4)(v5));
586      if (build_enabled && m_enabled) vdowrite(pfmt(fmt)(v1)(v2)(v3)(v4)(v5));
587587   }
588588
589   void set_enabled(const bool v)
590   {
591      m_enabled = v;
592   }
593
594   bool is_enabled() const { return m_enabled; }
595
589596protected:
590597   virtual void vdowrite(const pstring &ls) const {}
591598
599private:
600   bool m_enabled;
601
592602};
593603
594604template <plog_level L, bool build_enabled = true>
trunk/src/emu/netlist/solver/nld_solver.h
r249095r249096
135135   ATTR_COLD int get_net_idx(net_t *net);
136136
137137   inline eSolverType type() const { return m_type; }
138   const plog_base<NL_DEBUG> &log() const { return netlist().log(); }
138   plog_base<NL_DEBUG> &log() { return netlist().log(); }
139139
140140   virtual void log_stats();
141141
trunk/src/emu/sound/c352.c
r249095r249096
1313    Supports 8-bit linear and 8-bit muLaw samples
1414    Output: digital, 16 bit, 4 channels
1515    Output sample rate is the input clock / (288 * 2).
16   
17    superctr: The clock divider appears to be configurable for each system.
18    Below is a list of the divider values followed by the systems that use it.
19   
20    * 228: System 11.
21    * 288: System 22, Super 22, NB-1/2, ND-1, FL.
22    * 296: System 23, Super 23.
23    * 332: System 12.
1624 */
1725
1826#include "emu.h"
r249095r249096
468476
469477void c352_device::device_start()
470478{
471   int i, divider;
479   int i;
472480   double x_max = 32752.0;
473481   double y_max = 127.0;
474482   double u = 10.0;
r249095r249096
476484   // find our direct access
477485   m_direct = &space().direct();
478486
479   switch(m_divider)
480   {
481      case C352_DIVIDER_228:
482         divider=228;
483         break;
484      case C352_DIVIDER_288:
485      default:
486         divider=288;
487         break;
488      case C352_DIVIDER_332:
489         divider=332;
490         break;
491   }
487   m_sample_rate_base = clock() / m_divider;
492488
493   m_sample_rate_base = clock() / divider;
494
495489   m_stream = machine().sound().stream_alloc(*this, 0, 4, m_sample_rate_base);
496490
497491   // generate mulaw table for mulaw format samples
trunk/src/emu/sound/c352.h
r249095r249096
66#define __C352_H__
77
88//**************************************************************************
9//  CONSTANTS
10//**************************************************************************
11
12enum
13{
14   C352_DIVIDER_228 = 0,
15   C352_DIVIDER_288 = 1,
16   C352_DIVIDER_332 = 2
17};
18
19//**************************************************************************
209//  INTERFACE CONFIGURATION MACROS
2110//**************************************************************************
2211
trunk/src/emu/sound/l7a1045_l6028_dsp_a.c
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi
33/***************************************************************************
44
55    L7A1045 L6028 DSP-A
trunk/src/emu/sound/l7a1045_l6028_dsp_a.h
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi
33//**************************************************************************
44//  TYPE DEFINITIONS
55//**************************************************************************
trunk/src/emu/sound/tms5110.c
r249095r249096
1414
1515     Todo:
1616        - implement CS
17        - implement missing commands
1817        - TMS5110_CMD_TEST_TALK is only partially implemented
1918
2019     TMS5100:
r249095r249096
7978//define INTERP_SHIFT / (1<<m_coeff->interp_coeff[m_IP])
8079
8180/* Other hacks */
82/* HACK?: if defined, outputs the low 4 bits of the lattice filter to the i/o
81/* HACK: if defined, outputs the low 4 bits of the lattice filter to the i/o
8382 * or clip logic, even though the real hardware doesn't do this, partially verified by decap */
8483#undef ALLOW_4_LSB
8584
85/* forces m_TALK active instantly whenever m_SPEN would be activated, causing speech delay to be reduced by up to one frame time */
86/* for some reason, this hack makes snmath behave marginally more accurate to hardware, though it does not match the patent */
87#define FAST_START_HACK 1
8688
89
8790/* *****configuration of chip connection stuff***** */
8891/* must be defined; if 0, output the waveform as if it was tapped on the speaker pin as usual, if 1, output the waveform as if it was tapped on the i/o pin (volume is much lower in the latter case) */
8992#define FORCE_DIGITAL 0
r249095r249096
212215{
213216   save_item(NAME(m_variant));
214217
215   save_item(NAME(m_fifo));
216   save_item(NAME(m_fifo_head));
217   save_item(NAME(m_fifo_tail));
218   save_item(NAME(m_fifo_count));
219
220218   save_item(NAME(m_PDC));
221219   save_item(NAME(m_CTL_pins));
222220   save_item(NAME(m_SPEN));
r249095r249096
241239   save_item(NAME(m_old_frame_pitch_idx));
242240   save_item(NAME(m_old_frame_k_idx));
243241   save_item(NAME(m_old_zpar));
242   save_item(NAME(m_old_uv_zpar));
244243#endif
245244   save_item(NAME(m_current_energy));
246245   save_item(NAME(m_current_pitch));
r249095r249096
310309}
311310#endif
312311
313
314312/******************************************************************************************
315313
316     FIFO_data_write -- handle bit data write to the TMS5110 (as a result of toggling M0 pin)
314     extract_bits -- extract a specific number of bits from the VSM
317315
318316******************************************************************************************/
319void tms5110_device::FIFO_data_write(int data)
320{
321   /* add this bit to the FIFO */
322   if (m_fifo_count < FIFO_SIZE)
323   {
324      m_fifo[m_fifo_tail] = (data&1); /* set bit to 1 or 0 */
325317
326      m_fifo_tail = (m_fifo_tail + 1) % FIFO_SIZE;
327      m_fifo_count++;
328
329      if (DEBUG_5110) logerror("Added bit to FIFO (size=%2d)\n", m_fifo_count);
330   }
331   else
332   {
333      if (DEBUG_5110) logerror("Ran out of room in the FIFO!\n");
334   }
335}
336
337/******************************************************************************************
338
339     extract_bits -- extract a specific number of bits from the FIFO
340
341******************************************************************************************/
342
343318int tms5110_device::extract_bits(int count)
344319{
345320   int val = 0;
346   if (DEBUG_5110) logerror("requesting %d bits from fifo: ", count);
347   while (count--)
321   if (DEBUG_5110) logerror("requesting %d bits", count);
322   for (int i = 0; i < count; i++)
348323   {
349      val = (val << 1) | (m_fifo[m_fifo_head] & 1);
350      m_fifo_count--;
351      m_fifo_head = (m_fifo_head + 1) % FIFO_SIZE;
324      val = (val<<1) | new_int_read();
325      if (DEBUG_5110) logerror("bit read: %d\n", val&1);
352326   }
353327   if (DEBUG_5110) logerror("returning: %02x\n", val);
354328   return val;
355329}
356330
357void tms5110_device::request_bits(int no)
358{
359   for (int i = 0; i < no; i++)
360   {
361      UINT8 data = new_int_read();
362      if (DEBUG_5110) logerror("bit added to fifo: %d\n", data);
363      FIFO_data_write(data);
364   }
365}
366331
367332void tms5110_device::perform_dummy_read()
368333{
r249095r249096
389354   int i, bitout;
390355   INT32 this_sample;
391356
392   /* if we're not speaking, fill with nothingness */
393   if (!m_TALKD)
394      goto empty;
395
396357   /* loop until the buffer is full or we've stopped speaking */
397   while ((size > 0) && m_TALKD)
358   while (size > 0)
398359   {
399      /* if it is the appropriate time to update the old energy/pitch indices,
400       * i.e. when IP=7, PC=12, T=17, subcycle=2, do so. Since IP=7 PC=12 T=17
401       * is JUST BEFORE the transition to IP=0 PC=0 T=0 sybcycle=(0 or 1),
402       * which happens 4 T-cycles later), we change on the latter.
403       * The indices are updated here ~12 PCs before the new frame is applied.
404       */
405      /** TODO: the patents 4331836, 4335277, and 4419540 disagree about the timing of this **/
406      if ((m_IP == 0) && (m_PC == 0) && (m_subcycle < 2))
360      if(m_TALKD) // speaking
407361      {
408         m_OLDE = (m_new_frame_energy_idx == 0);
409         m_OLDP = (m_new_frame_pitch_idx == 0);
410      }
362         /* if we're ready for a new frame to be applied, i.e. when IP=0, PC=12, Sub=1
363          * (In reality, the frame was really loaded incrementally during the entire IP=0
364          * PC=x time period, but it doesn't affect anything until IP=0 PC=12 happens)
365          */
366         if ((m_IP == 0) && (m_PC == 12) && (m_subcycle == 1))
367         {
368            // HACK for regression testing, be sure to comment out before release!
369            //m_RNG = 0x1234;
370            // end HACK
411371
412      /* if we're ready for a new frame to be applied, i.e. when IP=0, PC=12, Sub=1
413       * (In reality, the frame was really loaded incrementally during the entire IP=0
414       * PC=x time period, but it doesn't affect anything until IP=0 PC=12 happens)
415       */
416      if ((m_IP == 0) && (m_PC == 12) && (m_subcycle == 1))
417      {
418         // HACK for regression testing, be sure to comment out before release!
419         //m_RNG = 0x1234;
420         // end HACK
421
422372#ifdef PERFECT_INTERPOLATION_HACK
423         /* remember previous frame energy, pitch, and coefficients */
424         m_old_frame_energy_idx = m_new_frame_energy_idx;
425         m_old_frame_pitch_idx = m_new_frame_pitch_idx;
426         for (i = 0; i < m_coeff->num_k; i++)
427            m_old_frame_k_idx[i] = m_new_frame_k_idx[i];
373            /* remember previous frame energy, pitch, and coefficients */
374            m_old_frame_energy_idx = m_new_frame_energy_idx;
375            m_old_frame_pitch_idx = m_new_frame_pitch_idx;
376            for (i = 0; i < m_coeff->num_k; i++)
377               m_old_frame_k_idx[i] = m_new_frame_k_idx[i];
428378#endif
429379
430         /* Parse a new frame into the new_target_energy, new_target_pitch and new_target_k[] */
431         parse_frame();
432#ifdef DEBUG_PARSE_FRAME_DUMP
433         fprintf(stderr,"\n");
380            /* Parse a new frame into the new_target_energy, new_target_pitch and new_target_k[] */
381            parse_frame();
382
383            // if the new frame is unvoiced (or silenced via ZPAR), be sure to zero out the k5-k10 parameters
384            // NOTE: this is probably the bug the tms5100/tmc0280 has, pre-rev D, I think.
385            // GUESS: Pre-rev D versions start zeroing k5-k10 immediately upon new frame load regardless of interpolation inhibit
386            // I.e. ZPAR = /TALKD || (PC>5&&P=0)
387            // GUESS: D and later versions only start or stop zeroing k5-k10 at the IP7->IP0 transition AFTER the frame
388            // I.e. ZPAR = /TALKD || (PC>5&&OLDP)
389#ifdef PERFECT_INTERPOLATION_HACK
390            m_old_uv_zpar = m_uv_zpar;
391            m_old_zpar = m_zpar; // unset old zpar on new frame
434392#endif
435         /* if the new frame is unvoiced (or silenced via ZPAR), be sure to zero out the k5-k10 parameters */
436         m_uv_zpar = NEW_FRAME_UNVOICED_FLAG | m_zpar;
393            m_zpar = 0;
394            //m_uv_zpar = (OLD_FRAME_UNVOICED_FLAG||m_zpar); // GUESS: fixed version in tmc0280d/tms5100a/cd280x/tms5110
395            m_uv_zpar = (NEW_FRAME_UNVOICED_FLAG||m_zpar); // GUESS: buggy version in tmc0280/tms5100
437396
438         /* if the new frame is a stop frame, unset both TALK and SPEN. TALKD remains active while the energy is ramping to 0. */
439         if (NEW_FRAME_STOP_FLAG == 1)
440         {
441            m_TALK = m_SPEN = 0;
442         }
397            /* if the new frame is a stop frame, unset both TALK and SPEN (via TCON). TALKD remains active while the energy is ramping to 0. */
398            if (NEW_FRAME_STOP_FLAG == 1)
399            {
400               m_TALK = m_SPEN = 0;
401            }
443402
444         /* in all cases where interpolation would be inhibited, set the inhibit flag; otherwise clear it.
445            Interpolation inhibit cases:
446          * Old frame was voiced, new is unvoiced
447          * Old frame was silence/zero energy, new has nonzero energy
448          * Old frame was unvoiced, new is voiced (note this is the case on the patent but may not be correct on the real final chip)
449          */
450         if ( ((OLD_FRAME_UNVOICED_FLAG == 0) && (NEW_FRAME_UNVOICED_FLAG == 1))
451            || ((OLD_FRAME_UNVOICED_FLAG == 1) && (NEW_FRAME_UNVOICED_FLAG == 0)) /* this line needs further investigation, starwars tie fighters may sound better without it */
452            || ((OLD_FRAME_SILENCE_FLAG == 1) && (NEW_FRAME_SILENCE_FLAG == 0)) )
453            m_inhibit = 1;
454         else // normal frame, normal interpolation
455            m_inhibit = 0;
403            /* in all cases where interpolation would be inhibited, set the inhibit flag; otherwise clear it.
404               Interpolation inhibit cases:
405             * Old frame was voiced, new is unvoiced
406             * Old frame was silence/zero energy, new has nonzero energy
407             * Old frame was unvoiced, new is voiced (note this is the case on the patent but may not be correct on the real final chip)
408             */
409            if ( ((OLD_FRAME_UNVOICED_FLAG == 0) && (NEW_FRAME_UNVOICED_FLAG == 1))
410               || ((OLD_FRAME_UNVOICED_FLAG == 1) && (NEW_FRAME_UNVOICED_FLAG == 0)) /* this line needs further investigation, starwars tie fighters may sound better without it */
411               || ((OLD_FRAME_SILENCE_FLAG == 1) && (NEW_FRAME_SILENCE_FLAG == 0)) )
412               m_inhibit = 1;
413            else // normal frame, normal interpolation
414               m_inhibit = 0;
456415
457416#ifdef DEBUG_GENERATION
458         /* Debug info for current parsed frame */
459         fprintf(stderr, "OLDE: %d; OLDP: %d; ", m_OLDE, m_OLDP);
460         fprintf(stderr,"Processing frame: ");
461         if (m_inhibit == 0)
462            fprintf(stderr, "Normal Frame\n");
463         else
464            fprintf(stderr,"Interpolation Inhibited\n");
465         fprintf(stderr,"*** current Energy, Pitch and Ks =      %04d,   %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",m_current_energy, m_current_pitch, m_current_k[0], m_current_k[1], m_current_k[2], m_current_k[3], m_current_k[4], m_current_k[5], m_current_k[6], m_current_k[7], m_current_k[8], m_current_k[9]);
466         fprintf(stderr,"*** target Energy(idx), Pitch, and Ks = %04d(%x),%04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",
467            (m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar)),
468            m_new_frame_energy_idx,
469            (m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar)),
470            (m_coeff->ktable[0][m_new_frame_k_idx[0]] * (1-m_zpar)),
471            (m_coeff->ktable[1][m_new_frame_k_idx[1]] * (1-m_zpar)),
472            (m_coeff->ktable[2][m_new_frame_k_idx[2]] * (1-m_zpar)),
473            (m_coeff->ktable[3][m_new_frame_k_idx[3]] * (1-m_zpar)),
474            (m_coeff->ktable[4][m_new_frame_k_idx[4]] * (1-m_uv_zpar)),
475            (m_coeff->ktable[5][m_new_frame_k_idx[5]] * (1-m_uv_zpar)),
476            (m_coeff->ktable[6][m_new_frame_k_idx[6]] * (1-m_uv_zpar)),
477            (m_coeff->ktable[7][m_new_frame_k_idx[7]] * (1-m_uv_zpar)),
478            (m_coeff->ktable[8][m_new_frame_k_idx[8]] * (1-m_uv_zpar)),
479            (m_coeff->ktable[9][m_new_frame_k_idx[9]] * (1-m_uv_zpar)) );
417            /* Debug info for current parsed frame */
418            fprintf(stderr, "OLDE: %d; OLDP: %d; ", m_OLDE, m_OLDP);
419            fprintf(stderr,"Processing new frame: ");
420            if (m_inhibit == 0)
421               fprintf(stderr, "Normal Frame\n");
422            else
423               fprintf(stderr,"Interpolation Inhibited\n");
424            fprintf(stderr,"*** current Energy, Pitch and Ks =      %04d,   %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",m_current_energy, m_current_pitch, m_current_k[0], m_current_k[1], m_current_k[2], m_current_k[3], m_current_k[4], m_current_k[5], m_current_k[6], m_current_k[7], m_current_k[8], m_current_k[9]);
425            fprintf(stderr,"*** target Energy(idx), Pitch, and Ks = %04d(%x),%04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",
426               (m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar)),
427               m_new_frame_energy_idx,
428               (m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar)),
429               (m_coeff->ktable[0][m_new_frame_k_idx[0]] * (1-m_zpar)),
430               (m_coeff->ktable[1][m_new_frame_k_idx[1]] * (1-m_zpar)),
431               (m_coeff->ktable[2][m_new_frame_k_idx[2]] * (1-m_zpar)),
432               (m_coeff->ktable[3][m_new_frame_k_idx[3]] * (1-m_zpar)),
433               (m_coeff->ktable[4][m_new_frame_k_idx[4]] * (1-m_uv_zpar)),
434               (m_coeff->ktable[5][m_new_frame_k_idx[5]] * (1-m_uv_zpar)),
435               (m_coeff->ktable[6][m_new_frame_k_idx[6]] * (1-m_uv_zpar)),
436               (m_coeff->ktable[7][m_new_frame_k_idx[7]] * (1-m_uv_zpar)),
437               (m_coeff->ktable[8][m_new_frame_k_idx[8]] * (1-m_uv_zpar)),
438               (m_coeff->ktable[9][m_new_frame_k_idx[9]] * (1-m_uv_zpar)) );
480439#endif
481440
482      }
483      else // Not a new frame, just interpolate the existing frame.
484      {
485         int inhibit_state = ((m_inhibit==1)&&(m_IP != 0)); // disable inhibit when reaching the last interp period, but don't overwrite the m_inhibit value
486#ifdef PERFECT_INTERPOLATION_HACK
487         int samples_per_frame = m_subc_reload?175:266; // either (13 A cycles + 12 B cycles) * 7 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 7 interps for SPKSLOW
488         //int samples_per_frame = m_subc_reload?200:304; // either (13 A cycles + 12 B cycles) * 8 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 8 interps for SPKSLOW
489         int current_sample = (m_subcycle - m_subc_reload)+(m_PC*(3-m_subc_reload))+((m_subc_reload?25:38)*((m_IP-1)&7));
490         //fprintf(stderr, "CS: %03d", current_sample);
491         // reset the current energy, pitch, etc to what it was at frame start
492         m_current_energy = (m_coeff->energytable[m_old_frame_energy_idx] * (1-m_zpar));
493         m_current_pitch = (m_coeff->pitchtable[m_old_frame_pitch_idx] * (1-m_old_zpar));
494         for (i = 0; i < 4; i++)
495            m_current_k[i] = (m_coeff->ktable[i][m_old_frame_k_idx[i]] * (1-m_old_zpar));
496         for (i = 4; i < m_coeff->num_k; i++)
497            m_current_k[i] = (m_coeff->ktable[i][m_old_frame_k_idx[i]] * (1-m_uv_zpar));
498         // now adjust each value to be exactly correct for each of the samples per frame
499         if (m_IP != 0) // if we're still interpolating...
500         {
501            m_current_energy += ((((m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar)) - m_current_energy)*(1-inhibit_state))*current_sample)/samples_per_frame;
502            m_current_pitch += ((((m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar)) - m_current_pitch)*(1-inhibit_state))*current_sample)/samples_per_frame;
503            for (i = 0; i < m_coeff->num_k; i++)
504               m_current_k[i] += ((((m_coeff->ktable[i][m_new_frame_k_idx[i]] * (1-((i<4)?m_zpar:m_uv_zpar))) - m_current_k[i])*(1-inhibit_state))*current_sample)/samples_per_frame;
505441         }
506         else // we're done, play this frame for 1/8 frame.
442         else // Not a new frame, just interpolate the existing frame.
507443         {
508            m_current_energy = (m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar));
509            m_current_pitch = (m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar));
444            int inhibit_state = ((m_inhibit==1)&&(m_IP != 0)); // disable inhibit when reaching the last interp period, but don't overwrite the m_inhibit value
445#ifdef PERFECT_INTERPOLATION_HACK
446            int samples_per_frame = m_subc_reload?175:266; // either (13 A cycles + 12 B cycles) * 7 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 7 interps for SPKSLOW
447            //int samples_per_frame = m_subc_reload?200:304; // either (13 A cycles + 12 B cycles) * 8 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 8 interps for SPKSLOW
448            int current_sample = (m_subcycle - m_subc_reload)+(m_PC*(3-m_subc_reload))+((m_subc_reload?25:38)*((m_IP-1)&7));
449            //fprintf(stderr, "CS: %03d", current_sample);
450            // reset the current energy, pitch, etc to what it was at frame start
451            m_current_energy = (m_coeff->energytable[m_old_frame_energy_idx] * (1-m_old_zpar));
452            m_current_pitch = (m_coeff->pitchtable[m_old_frame_pitch_idx] * (1-m_old_zpar));
510453            for (i = 0; i < m_coeff->num_k; i++)
511               m_current_k[i] = (m_coeff->ktable[i][m_new_frame_k_idx[i]] * (1-((i<4)?m_zpar:m_uv_zpar)));
512         }
454               m_current_k[i] = (m_coeff->ktable[i][m_old_frame_k_idx[i]] * (1-((i<4)?m_old_zpar:m_old_uv_zpar)));
455            // now adjust each value to be exactly correct for each of the samples per frame
456            if (m_IP != 0) // if we're still interpolating...
457            {
458               m_current_energy = (m_current_energy + (((m_coeff->energytable[m_new_frame_energy_idx] - m_current_energy)*(1-inhibit_state))*current_sample)/samples_per_frame)*(1-m_zpar);
459               m_current_pitch = (m_current_pitch + (((m_coeff->pitchtable[m_new_frame_pitch_idx] - m_current_pitch)*(1-inhibit_state))*current_sample)/samples_per_frame)*(1-m_zpar);
460               for (i = 0; i < m_coeff->num_k; i++)
461                  m_current_k[i] = (m_current_k[i] + (((m_coeff->ktable[i][m_new_frame_k_idx[i]] - m_current_k[i])*(1-inhibit_state))*current_sample)/samples_per_frame)*(1-((i<4)?m_zpar:m_uv_zpar));
462            }
463            else // we're done, play this frame for 1/8 frame.
464            {
465               m_current_energy = (m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar));
466               m_current_pitch = (m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar));
467               for (i = 0; i < m_coeff->num_k; i++)
468                  m_current_k[i] = (m_coeff->ktable[i][m_new_frame_k_idx[i]] * (1-((i<4)?m_zpar:m_uv_zpar)));
469            }
513470#else
514         //Updates to parameters only happen on subcycle '2' (B cycle) of PCs.
515         if (m_subcycle == 2)
516         {
517            switch(m_PC)
471            //Updates to parameters only happen on subcycle '2' (B cycle) of PCs.
472            if (m_subcycle == 2)
518473            {
519               case 0: /* PC = 0, B cycle, write updated energy */
520               m_current_energy += ((((m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar)) - m_current_energy)*(1-inhibit_state)) INTERP_SHIFT);
521               break;
522               case 1: /* PC = 1, B cycle, write updated pitch */
523               m_current_pitch += ((((m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar)) - m_current_pitch)*(1-inhibit_state)) INTERP_SHIFT);
524               break;
525               case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11:
526               /* PC = 2 through 11, B cycle, write updated K1 through K10 */
527               m_current_k[m_PC-2] += ((((m_coeff->ktable[m_PC-2][m_new_frame_k_idx[m_PC-2]] * (1-(((m_PC-2)<4)?m_zpar:m_uv_zpar))) - m_current_k[m_PC-2])*(1-inhibit_state)) INTERP_SHIFT);
528               break;
529               case 12: /* PC = 12, do nothing */
530               break;
474               switch(m_PC)
475               {
476                  case 0: /* PC = 0, B cycle, write updated energy */
477                  m_current_energy = (m_current_energy + (((m_coeff->energytable[m_new_frame_energy_idx] - m_current_energy)*(1-inhibit_state)) INTERP_SHIFT))*(1-m_zpar);
478                  break;
479                  case 1: /* PC = 1, B cycle, write updated pitch */
480                  m_current_pitch = (m_current_pitch + (((m_coeff->pitchtable[m_new_frame_pitch_idx] - m_current_pitch)*(1-inhibit_state)) INTERP_SHIFT))*(1-m_zpar);
481                  break;
482                  case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11:
483                  /* PC = 2 through 11, B cycle, write updated K1 through K10 */
484                  m_current_k[m_PC-2] = (m_current_k[m_PC-2] + (((m_coeff->ktable[m_PC-2][m_new_frame_k_idx[m_PC-2]] - m_current_k[m_PC-2])*(1-inhibit_state)) INTERP_SHIFT))*(((m_PC-2)>4)?(1-m_uv_zpar):(1-m_zpar));
485                  break;
486                  case 12: /* PC = 12 */
487                  /* we should NEVER reach this point, PC=12 doesn't have a subcycle 2 */
488                  break;
489               }
531490            }
532         }
533491#endif
534      }
492         }
535493
536      // calculate the output
537      if (OLD_FRAME_UNVOICED_FLAG == 1)
538      {
539         // generate unvoiced samples here
540         if (m_RNG & 1)
541            m_excitation_data = ~0x3F; /* according to the patent it is (either + or -) half of the maximum value in the chirp table, so either 01000000(0x40) or 11000000(0xC0)*/
542         else
543            m_excitation_data = 0x40;
544      }
545      else /* (OLD_FRAME_UNVOICED_FLAG == 0) */
546      {
547         // generate voiced samples here
548         /* US patent 4331836 Figure 14B shows, and logic would hold, that a pitch based chirp
549          * function has a chirp/peak and then a long chain of zeroes.
550          * The last entry of the chirp rom is at address 0b110011 (51d), the 52nd sample,
551          * and if the address reaches that point the ADDRESS incrementer is
552          * disabled, forcing all samples beyond 51d to be == 51d
553          */
554         if (m_pitch_count >= 51)
555            m_excitation_data = (INT8)m_coeff->chirptable[51];
556         else /*m_pitch_count < 51*/
557            m_excitation_data = (INT8)m_coeff->chirptable[m_pitch_count];
558      }
494         // calculate the output
495         if (OLD_FRAME_UNVOICED_FLAG == 1)
496         {
497            // generate unvoiced samples here
498            if (m_RNG & 1)
499               m_excitation_data = ~0x3F; /* according to the patent it is (either + or -) half of the maximum value in the chirp table, so either 01000000(0x40) or 11000000(0xC0)*/
500            else
501               m_excitation_data = 0x40;
502         }
503         else /* (OLD_FRAME_UNVOICED_FLAG == 0) */
504         {
505            // generate voiced samples here
506            /* US patent 4331836 Figure 14B shows, and logic would hold, that a pitch based chirp
507             * function has a chirp/peak and then a long chain of zeroes.
508             * The last entry of the chirp rom is at address 0b110011 (51d), the 52nd sample,
509             * and if the address reaches that point the ADDRESS incrementer is
510             * disabled, forcing all samples beyond 51d to be == 51d
511             */
512            if (m_pitch_count >= 51)
513               m_excitation_data = (INT8)m_coeff->chirptable[51];
514            else /*m_pitch_count < 51*/
515               m_excitation_data = (INT8)m_coeff->chirptable[m_pitch_count];
516         }
559517
560      // Update LFSR *20* times every sample (once per T cycle), like patent shows
561   for (i=0; i<20; i++)
562   {
563      bitout = ((m_RNG >> 12) & 1) ^
564            ((m_RNG >>  3) & 1) ^
565            ((m_RNG >>  2) & 1) ^
566            ((m_RNG >>  0) & 1);
567      m_RNG <<= 1;
568      m_RNG |= bitout;
569   }
570      this_sample = lattice_filter(); /* execute lattice filter */
518         // Update LFSR *20* times every sample (once per T cycle), like patent shows
519         for (i=0; i<20; i++)
520         {
521            bitout = ((m_RNG >> 12) & 1) ^
522                  ((m_RNG >>  3) & 1) ^
523                  ((m_RNG >>  2) & 1) ^
524                  ((m_RNG >>  0) & 1);
525            m_RNG <<= 1;
526            m_RNG |= bitout;
527         }
528         this_sample = lattice_filter(); /* execute lattice filter */
571529#ifdef DEBUG_GENERATION_VERBOSE
572      //fprintf(stderr,"C:%01d; ",m_subcycle);
573      fprintf(stderr,"IP:%01d PC:%02d X:%04d E:%03d P:%03d Pc:%03d ",m_IP, m_PC, m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
574      //fprintf(stderr,"X:%04d E:%03d P:%03d Pc:%03d ", m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
575      for (i=0; i<10; i++)
576         fprintf(stderr,"K%d:%04d ", i+1, m_current_k[i]);
577      fprintf(stderr,"Out:%06d", this_sample);
578      fprintf(stderr,"\n");
530         //fprintf(stderr,"C:%01d; ",m_subcycle);
531         fprintf(stderr,"IP:%01d PC:%02d X:%04d E:%03d P:%03d Pc:%03d ",m_IP, m_PC, m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
532         //fprintf(stderr,"X:%04d E:%03d P:%03d Pc:%03d ", m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
533         for (i=0; i<10; i++)
534            fprintf(stderr,"K%d:%04d ", i+1, m_current_k[i]);
535         fprintf(stderr,"Out:%06d ", this_sample);
536//#ifdef PERFECT_INTERPOLATION_HACK
537//         fprintf(stderr,"%d%d%d%d",m_old_zpar,m_zpar,m_old_uv_zpar,m_uv_zpar);
538//#else
539//         fprintf(stderr,"x%dx%d",m_zpar,m_uv_zpar);
540//#endif
541         fprintf(stderr,"\n");
579542#endif
580      /* next, force result to 14 bits (since its possible that the addition at the final (k1) stage of the lattice overflowed) */
581      while (this_sample > 16383) this_sample -= 32768;
582      while (this_sample < -16384) this_sample += 32768;
583      if (m_digital_select == 0) // analog SPK pin output is only 8 bits, with clipping
584         buffer[buf_count] = clip_analog(this_sample);
585      else // digital I/O pin output is 12 bits
586      {
543         /* next, force result to 14 bits (since its possible that the addition at the final (k1) stage of the lattice overflowed) */
544         while (this_sample > 16383) this_sample -= 32768;
545         while (this_sample < -16384) this_sample += 32768;
546         if (m_digital_select == 0) // analog SPK pin output is only 8 bits, with clipping
547            buffer[buf_count] = clip_analog(this_sample);
548         else // digital I/O pin output is 12 bits
549         {
587550#ifdef ALLOW_4_LSB
588         // input:  ssss ssss ssss ssss ssnn nnnn nnnn nnnn
589         // N taps:                       ^                 = 0x2000;
590         // output: ssss ssss ssss ssss snnn nnnn nnnn nnnN
591         buffer[buf_count] = (this_sample<<1)|((this_sample&0x2000)>>13);
551            // input:  ssss ssss ssss ssss ssnn nnnn nnnn nnnn
552            // N taps:                       ^                 = 0x2000;
553            // output: ssss ssss ssss ssss snnn nnnn nnnn nnnN
554            buffer[buf_count] = (this_sample<<1)|((this_sample&0x2000)>>13);
592555#else
593         this_sample &= ~0xF;
594         // input:  ssss ssss ssss ssss ssnn nnnn nnnn 0000
595         // N taps:                       ^^ ^^^            = 0x3E00;
596         // output: ssss ssss ssss ssss snnn nnnn nnnN NNNN
597         buffer[buf_count] = (this_sample<<1)|((this_sample&0x3E00)>>9);
556            this_sample &= ~0xF;
557            // input:  ssss ssss ssss ssss ssnn nnnn nnnn 0000
558            // N taps:                       ^^ ^^^            = 0x3E00;
559            // output: ssss ssss ssss ssss snnn nnnn nnnN NNNN
560            buffer[buf_count] = (this_sample<<1)|((this_sample&0x3E00)>>9);
598561#endif
599      }
600      // Update all counts
562         }
563         // Update all counts
601564
602      m_subcycle++;
603      if ((m_subcycle == 2) && (m_PC == 12)) // RESETF3
604      {
605         /* Circuit 412 in the patent acts a reset, resetting the pitch counter to 0
606          * if INHIBIT was true during the most recent frame transition.
607          * The exact time this occurs is betwen IP=7, PC=12 sub=0, T=t12
608          * and m_IP = 0, PC=0 sub=0, T=t12, a period of exactly 20 cycles,
609          * which overlaps the time OLDE and OLDP are updated at IP=7 PC=12 T17
610          * (and hence INHIBIT itself 2 t-cycles later). We do it here because it is
611          * convenient and should make no difference in output.
612          */
613         if ((m_IP == 7)&&(m_inhibit==1)) m_pitch_zero = 1;
614         if ((m_IP == 0)&&(m_pitch_zero==1)) m_pitch_zero = 0;
615#ifdef PERFECT_INTERPOLATION_HACK
616         m_old_zpar = m_zpar;
617#endif
618         m_zpar = 0; /* this gets effectively reset by resetf3, same signal which resets m_PC to 0 */
619         if (m_IP == 7) // RESETL4
565         m_subcycle++;
566         if ((m_subcycle == 2) && (m_PC == 12)) // RESETF3
620567         {
621            /* if TALK was clear last frame, halt speech now, since TALKD (latched from TALK on new frame) just went inactive. */
568            /* Circuit 412 in the patent acts a reset, resetting the pitch counter to 0
569             * if INHIBIT was true during the most recent frame transition.
570             * The exact time this occurs is betwen IP=7, PC=12 sub=0, T=t12
571             * and m_IP = 0, PC=0 sub=0, T=t12, a period of exactly 20 cycles,
572             * which overlaps the time OLDE and OLDP are updated at IP=7 PC=12 T17
573             * (and hence INHIBIT itself 2 t-cycles later). We do it here because it is
574             * convenient and should make no difference in output.
575             */
576            if ((m_IP == 7)&&(m_inhibit==1)) m_pitch_zero = 1;
577            if ((m_IP == 0)&&(m_pitch_zero==1)) m_pitch_zero = 0;
578            if (m_IP == 7) // RESETL4
579            {
580               // Latch OLDE and OLDP
581               OLD_FRAME_SILENCE_FLAG = NEW_FRAME_SILENCE_FLAG; // m_OLDE
582               OLD_FRAME_UNVOICED_FLAG = NEW_FRAME_UNVOICED_FLAG; // m_OLDP
583               /* if TALK was clear last frame, halt speech now, since TALKD (latched from TALK on new frame) just went inactive. */
622584#ifdef DEBUG_GENERATION
623            if (m_TALK == 0)
624               fprintf(stderr,"tms5110_process: processing frame: TALKD = 0 caused by stop frame or buffer empty, halting speech.\n");
585               if (m_TALK == 0)
586                  fprintf(stderr,"tms5110_process: processing frame: TALKD = 0 caused by stop frame or buffer empty, halting speech.\n");
625587#endif
626            m_TALKD = m_TALK; // TALKD is latched from TALK
627            m_TALK = m_SPEN; // TALK is latched from SPEN
588               m_TALKD = m_TALK; // TALKD is latched from TALK
589               m_TALK = m_SPEN; // TALK is latched from SPEN
590            }
591            m_subcycle = m_subc_reload;
592            m_PC = 0;
593            m_IP++;
594            m_IP&=0x7;
628595         }
629         m_subcycle = m_subc_reload;
630         m_PC = 0;
631         m_IP++;
632         m_IP&=0x7;
596         else if (m_subcycle == 3)
597         {
598            m_subcycle = m_subc_reload;
599            m_PC++;
600         }
601         m_pitch_count++;
602         if ((m_pitch_count >= m_current_pitch)||(m_pitch_zero == 1)) m_pitch_count = 0;
603         m_pitch_count &= 0x1FF;
633604      }
634      else if (m_subcycle == 3)
605      else // m_TALKD == 0
635606      {
636         m_subcycle = m_subc_reload;
637         m_PC++;
638      }
639      m_pitch_count++;
640      if ((m_pitch_count >= m_current_pitch)||(m_pitch_zero == 1)) m_pitch_count = 0;
641      m_pitch_count &= 0x1FF;
642      buf_count++;
643      size--;
644   }
645
646empty:
647
648   while (size > 0)
649   {
650      m_subcycle++;
651      if ((m_subcycle == 2) && (m_PC == 12)) // RESETF3
652      {
653         if (m_IP == 7) // RESETL4
607         m_subcycle++;
608         if ((m_subcycle == 2) && (m_PC == 12)) // RESETF3
654609         {
655            m_TALKD = m_TALK; // TALKD is latched from TALK
656            m_TALK = m_SPEN; // TALK is latched from SPEN
610            if (m_IP == 7) // RESETL4
611            {
612               m_TALKD = m_TALK; // TALKD is latched from TALK
613               m_TALK = m_SPEN; // TALK is latched from SPEN
614            }
615            m_subcycle = m_subc_reload;
616            m_PC = 0;
617            m_IP++;
618            m_IP&=0x7;
657619         }
658         m_subcycle = m_subc_reload;
659         m_PC = 0;
660         m_IP++;
661         m_IP&=0x7;
620         else if (m_subcycle == 3)
621         {
622            m_subcycle = m_subc_reload;
623            m_PC++;
624         }
625         buffer[buf_count] = -1; /* should be just -1; actual chip outputs -1 every idle sample; (cf note in data sheet, p 10, table 4) */
662626      }
663      else if (m_subcycle == 3)
664      {
665         m_subcycle = m_subc_reload;
666         m_PC++;
667      }
668      buffer[buf_count] = -1; /* should be just -1; actual chip outputs -1 every idle sample; (cf note in data sheet, p 10, table 4) */
669      buf_count++;
670      size--;
627   buf_count++;
628   size--;
671629   }
672630}
673631
r249095r249096
897855#endif
898856               perform_dummy_read();
899857               m_SPEN = 1; /* start immediately */
858#ifdef FAST_START_HACK
859               m_TALK = 1;
860#endif
900861               /* clear out variables before speaking */
901862               m_zpar = 1; // zero all the parameters
863               m_uv_zpar = 1; // zero k4-k10 as well
864               m_OLDE = 1; // 'silence/zpar' frames are zero energy
865               m_OLDP = 1; // 'silence/zpar' frames are zero pitch
866#ifdef PERFECT_INTERPOLATION_HACK
867               m_old_zpar = 1; // zero all the old parameters
868               m_old_uv_zpar = 1; // zero old k4-k10 as well
869#endif
902870               m_subc_reload = 0; // SPKSLOW means this is 0
903               m_subcycle = m_subc_reload;
904               m_PC = 0;
905               m_IP = 0;
906871               break;
907872
908873            case TMS5110_CMD_READ_BIT:
r249095r249096
916881#ifdef DEBUG_COMMAND_DUMP
917882                  fprintf(stderr,"actually reading a bit now\n");
918883#endif
919                  request_bits(1);
920884                  m_CTL_buffer >>= 1;
921885                  m_CTL_buffer |= (extract_bits(1)<<3);
922886                  m_CTL_buffer &= 0xF;
r249095r249096
929893#endif
930894               perform_dummy_read();
931895               m_SPEN = 1; /* start immediately */
896#ifdef FAST_START_HACK
897               m_TALK = 1;
898#endif
932899               /* clear out variables before speaking */
933900               m_zpar = 1; // zero all the parameters
901               m_uv_zpar = 1; // zero k4-k10 as well
902               m_OLDE = 1; // 'silence/zpar' frames are zero energy
903               m_OLDP = 1; // 'silence/zpar' frames are zero pitch
904#ifdef PERFECT_INTERPOLATION_HACK
905               m_old_zpar = 1; // zero all the old parameters
906               m_old_uv_zpar = 1; // zero old k4-k10 as well
907#endif
934908               m_subc_reload = 1; // SPEAK means this is 1
935               m_subcycle = m_subc_reload;
936               m_PC = 0;
937               m_IP = 0;
938909               break;
939910
940911            case TMS5110_CMD_READ_BRANCH:
r249095r249096
979950
980951void tms5110_device::parse_frame()
981952{
982   int bits, i, rep_flag;
983   /** TODO: get rid of bits handling here and move into extract_bits (as in tms5220.c) **/
984   /* count the total number of bits available */
985   bits = m_fifo_count;
953   int i, rep_flag;
986954
987   /* attempt to extract the energy index */
988   bits -= m_coeff->energy_bits;
989   if (bits < 0)
990   {
991      request_bits( -bits ); /* toggle M0 to receive needed bits */
992      bits = 0;
993   }
994955   // attempt to extract the energy index
995956   m_new_frame_energy_idx = extract_bits(m_coeff->energy_bits);
996957#ifdef DEBUG_PARSE_FRAME_DUMP
r249095r249096
998959   fprintf(stderr," ");
999960#endif
1000961
1001   /* if the energy index is 0 or 15, we're done
1002
1003   if ((indx == 0) || (indx == 15))
1004   {
1005       if (DEBUG_5110) logerror("  (4-bit energy=%d frame)\n",m_new_energy);
1006
1007   // clear the k's
1008       if (indx == 0)
1009       {
1010           for (i = 0; i < m_coeff->num_k; i++)
1011               m_new_k[i] = 0;
1012       }
1013
1014       // clear fifo if stop frame encountered
1015       if (indx == 15)
1016       {
1017           if (DEBUG_5110) logerror("  (4-bit energy=%d STOP frame)\n",m_new_energy);
1018           m_fifo_head = m_fifo_tail = m_fifo_count = 0;
1019       }
1020       return;
1021   }*/
1022962   // if the energy index is 0 or 15, we're done
1023963   if ((m_new_frame_energy_idx == 0) || (m_new_frame_energy_idx == 15))
1024964      return;
1025965
1026
1027   /* attempt to extract the repeat flag */
1028   bits -= 1;
1029   if (bits < 0)
1030   {
1031      request_bits( -bits ); /* toggle M0 to receive needed bits */
1032      bits = 0;
1033   }
1034966   rep_flag = extract_bits(1);
1035967#ifdef DEBUG_PARSE_FRAME_DUMP
1036968   printbits(rep_flag, 1);
1037969   fprintf(stderr," ");
1038970#endif
1039971
1040   /* attempt to extract the pitch */
1041   bits -= m_coeff->pitch_bits;
1042   if (bits < 0)
1043   {
1044      request_bits( -bits ); /* toggle M0 to receive needed bits */
1045      bits = 0;
1046   }
1047972   m_new_frame_pitch_idx = extract_bits(m_coeff->pitch_bits);
1048973#ifdef DEBUG_PARSE_FRAME_DUMP
1049974   printbits(m_new_frame_pitch_idx,m_coeff->pitch_bits);
r249095r249096
1056981   // extract first 4 K coefficients
1057982   for (i = 0; i < 4; i++)
1058983   {
1059      /* attempt to extract 4 K's */
1060      bits -= m_coeff->kbits[i];
1061      if (bits < 0)
1062      {
1063         request_bits( -bits ); /* toggle M0 to receive needed bits */
1064         bits = 0;
1065      }
1066984      m_new_frame_k_idx[i] = extract_bits(m_coeff->kbits[i]);
1067985#ifdef DEBUG_PARSE_FRAME_DUMP
1068986      printbits(m_new_frame_k_idx[i],m_coeff->kbits[i]);
r249095r249096
1080998   // If we got here, we need the remaining 6 K's
1081999   for (i = 4; i < m_coeff->num_k; i++)
10821000   {
1083      bits -= m_coeff->kbits[i];
1084      if (bits < 0)
1085      {
1086         request_bits( -bits ); /* toggle M0 to receive needed bits */
1087         bits = 0;
1088      }
10891001      m_new_frame_k_idx[i] = extract_bits(m_coeff->kbits[i]);
10901002#ifdef DEBUG_PARSE_FRAME_DUMP
10911003      printbits(m_new_frame_k_idx[i],m_coeff->kbits[i]);
10921004      fprintf(stderr," ");
10931005#endif
10941006   }
1007#ifdef DEBUG_PARSE_FRAME_DUMP
1008         fprintf(stderr,"\n");
1009#endif
10951010#ifdef VERBOSE
1096   if (m_speak_external)
1097      logerror("Parsed a frame successfully in FIFO - %d bits remaining\n", (m_fifo_count*8)-(m_fifo_bits_taken));
1098   else
10991011      logerror("Parsed a frame successfully in ROM\n");
11001012#endif
11011013   return;
r249095r249096
12391151void tms5110_device::device_reset()
12401152{
12411153   m_digital_select = FORCE_DIGITAL; // assume analog output
1242   /* initialize the FIFO */
1243   memset(m_fifo, 0, sizeof(m_fifo));
1244   m_fifo_head = m_fifo_tail = m_fifo_count = 0;
12451154
12461155   /* initialize the chip state */
12471156   m_SPEN = m_TALK = m_TALKD = 0;
r249095r249096
12541163#ifdef PERFECT_INTERPOLATION_HACK
12551164   m_old_frame_energy_idx = m_old_frame_pitch_idx = 0;
12561165   memset(m_old_frame_k_idx, 0, sizeof(m_old_frame_k_idx));
1257   m_old_zpar = 0;
1166   m_old_zpar = m_old_uv_zpar = 0;
12581167#endif
12591168   m_new_frame_energy_idx = m_current_energy = m_previous_energy = 0;
12601169   m_new_frame_pitch_idx = m_current_pitch = 0;
r249095r249096
13911300}
13921301
13931302
1394
13951303/******************************************************************************
13961304
1397     tms5110_ready_r -- return the not ready status from the sound chip
1398
1399******************************************************************************/
1400
1401int tms5110_device::ready_r()
1402{
1403   /* bring up to date first */
1404   m_stream->update();
1405   return (m_fifo_count < FIFO_SIZE-1);
1406}
1407
1408
1409
1410/******************************************************************************
1411
14121305     tms5110_update -- update the sound chip so that it is in sync with CPU execution
14131306
14141307******************************************************************************/
trunk/src/emu/sound/tms5110.h
r249095r249096
77
88#include "emu.h"
99
10#define FIFO_SIZE               64 // TODO: technically the tms51xx chips don't have a fifo at all
10/* HACK: if defined, uses impossibly perfect 'straight line' interpolation */
11#undef PERFECT_INTERPOLATION_HACK
1112
1213/* TMS5110 commands */
1314                              /* CTL8  CTL4  CTL2  CTL1  |   PDC's  */
r249095r249096
1516#define TMS5110_CMD_RESET        (0) /*    0     0     0     x  |     1    */
1617#define TMS5110_CMD_LOAD_ADDRESS (2) /*    0     0     1     x  |     2    */
1718#define TMS5110_CMD_OUTPUT       (4) /*    0     1     0     x  |     3    */
18#define TMS5110_CMD_SPKSLOW      (6) /*    0     1     1     x  |     1    | Note: this command is undocumented on the datasheets, it only appears on the patents. It might not actually work properly on some of the real chips as manufactured. Acts the same as CMD_SPEAK, but makes the interpolator take two A cycles whereever it would normally only take one, effectively making speech of any given word take about twice as long as normal. */
19#define TMS5110_CMD_SPKSLOW      (6) /*    0     1     1     x  |     1    | Note: this command is undocumented on the datasheets, it only appears on the patents. It might not actually work properly on some of the real chips as manufactured. Acts the same as CMD_SPEAK, but makes the interpolator take three A cycles whereever it would normally only take one, effectively making speech of any given word take twice as long as normal. */
1920#define TMS5110_CMD_READ_BIT     (8) /*    1     0     0     x  |     1    */
2021#define TMS5110_CMD_SPEAK       (10) /*    1     0     1     x  |     1    */
2122#define TMS5110_CMD_READ_BRANCH (12) /*    1     1     0     x  |     1    */
r249095r249096
6465    */
6566   DECLARE_READ8_MEMBER( romclk_hack_r );
6667
67   int ready_r();
6868   void set_frequency(int frequency);
6969
7070   int _speech_rom_read_bit();
r249095r249096
9393   void new_int_write_addr(UINT8 addr);
9494   UINT8 new_int_read();
9595   void register_for_save_states();
96   void FIFO_data_write(int data);
9796   int extract_bits(int count);
98   void request_bits(int no);
9997   void perform_dummy_read();
10098   INT32 lattice_filter();
10199   void process(INT16 *buffer, unsigned int size);
r249095r249096
109107   /* coefficient tables */
110108   const struct tms5100_coeffs *m_coeff;
111109
112   /* these contain data that describes the 4 bit "FIFO" */
113   UINT8 m_fifo[FIFO_SIZE];
114   UINT8 m_fifo_head;
115   UINT8 m_fifo_tail;
116   UINT8 m_fifo_count;
117
118110   /* these contain global status bits */
119111   UINT8 m_PDC;
120112   UINT8 m_CTL_pins;
r249095r249096
162154   UINT8 m_old_frame_pitch_idx;
163155   UINT8 m_old_frame_k_idx[10];
164156   UINT8 m_old_zpar;
157   UINT8 m_old_uv_zpar;
165158
166159   INT32 m_current_energy;
167160   INT32 m_current_pitch;
trunk/src/emu/sound/tms5220.c
r249095r249096
4848
4949TODO:
5050    * Ever since the big rewrite, there are glitches on certain frame transitions
51      for example in the word 'robots' during the eprom attract mode,
51      for example in the word 'rid' during the eprom attract mode,
5252      I (LN) am not entirely sure why the real chip doesn't have these as well.
5353      Needs more real hardware testing/dumps for comparison.
54    * Ever since the timing rewrite, the above problem is slightly worse. This
55      time, however, it is probably a 'real' bug, which I (LN) am in the process
56      of tracking down.
57      i.e. the word 'congratulations' in victory when you get a high score.
5854    * Implement a ready callback for pc interfaces
5955    - this will be quite a challenge since for it to be really accurate
6056      the whole emulation has to run in sync (lots of timers) with the
r249095r249096
6258    * If a command is still executing, /READY will be kept high until the command has
6359      finished if the next command is written.
6460    * tomcat has a 5220 which is not hooked up at all
65    * Is the TS=0 forcing energy to 0 for next frame in the interpolator actually correct? I'm (LN) guessing no. The patent schematics state that TS=0 shuts off the output dac completely, though doesn't affect the I/O pin.
6661
6762Pedantic detail from observation of real chip:
6863The 5200 and 5220 chips outputs the following coefficients over PROMOUT while
r249095r249096
267262//define INTERP_SHIFT / (1<<m_coeff->interp_coeff[m_IP])
268263
269264/* Other hacks */
270/* HACK?: if defined, outputs the low 4 bits of the lattice filter to the i/o
265/* HACK: if defined, outputs the low 4 bits of the lattice filter to the i/o
271266 * or clip logic, even though the real hardware doesn't do this, partially verified by decap */
272267#undef ALLOW_4_LSB
273268
269/* forces m_TALK active instantly whenever m_SPEN would be activated, causing speech delay to be reduced by up to one frame time */
270/* for some reason, this hack makes victory behave better, though it does not match the patent */
271#define FAST_START_HACK 1
274272
273
275274/* *****configuration of chip connection stuff***** */
276275/* must be defined; if 0, output the waveform as if it was tapped on the speaker pin as usual, if 1, output the waveform as if it was tapped on the i/o pin (volume is much lower in the latter case) */
277276#define FORCE_DIGITAL 0
r249095r249096
361360   save_item(NAME(m_fifo_count));
362361   save_item(NAME(m_fifo_bits_taken));
363362
364   save_item(NAME(m_speaking_now));
365   save_item(NAME(m_speak_external));
366   save_item(NAME(m_talk_status));
363   save_item(NAME(m_previous_TALK_STATUS));
364   save_item(NAME(m_SPEN));
365   save_item(NAME(m_DDIS));
366   save_item(NAME(m_TALK));
367   save_item(NAME(m_TALKD));
367368   save_item(NAME(m_buffer_low));
368369   save_item(NAME(m_buffer_empty));
369370   save_item(NAME(m_irq_pin));
r249095r249096
384385   save_item(NAME(m_current_pitch));
385386   save_item(NAME(m_current_k));
386387
387   save_item(NAME(m_target_energy));
388   save_item(NAME(m_target_pitch));
389   save_item(NAME(m_target_k));
390
391388   save_item(NAME(m_previous_energy));
392389
393390   save_item(NAME(m_subcycle));
r249095r249096
395392   save_item(NAME(m_PC));
396393   save_item(NAME(m_IP));
397394   save_item(NAME(m_inhibit));
395   save_item(NAME(m_uv_zpar));
396   save_item(NAME(m_zpar));
397   save_item(NAME(m_pitch_zero));
398398   save_item(NAME(m_c_variant_rate));
399399   save_item(NAME(m_pitch_count));
400400
r249095r249096
465465
466466void tms5220_device::data_write(int data)
467467{
468   int old_buffer_low = m_buffer_low;
468469#ifdef DEBUG_DUMP_INPUT_DATA
469470   fprintf(stdout, "%c",data);
470471#endif
471   if (m_speak_external) // If we're in speak external mode
472   if (m_DDIS) // If we're in speak external mode
472473   {
473474      // add this byte to the FIFO
474475      if (m_fifo_count < FIFO_SIZE)
r249095r249096
477478         m_fifo_tail = (m_fifo_tail + 1) % FIFO_SIZE;
478479         m_fifo_count++;
479480#ifdef DEBUG_FIFO
480         logerror("data_write: Added byte to FIFO (current count=%2d)\n", m_fifo_count);
481         fprintf(stderr,"data_write: Added byte to FIFO (current count=%2d)\n", m_fifo_count);
481482#endif
482483         update_fifo_status_and_ints();
483         if ((m_talk_status == 0) && (m_buffer_low == 0)) // we just unset buffer low with that last write, and talk status *was* zero...
484         // if we just unset buffer low with that last write, and SPEN *was* zero (see circuit 251, sheet 12)
485         if ((m_SPEN == 0) && ((old_buffer_low == 1) && (m_buffer_low == 0))) // MUST HAVE EDGE DETECT
484486         {
485         int i;
487            int i;
486488#ifdef DEBUG_FIFO
487         logerror("data_write triggered talk status to go active!\n");
489            fprintf(stderr,"data_write triggered SPEN to go active!\n");
488490#endif
489            // ...then we now have enough bytes to start talking; clear out the new frame parameters (it will become old frame just before the first call to parse_frame() )
490            // TODO: the 3 lines below (and others) are needed for victory to not fail its selftest due to a sample ending too late, may require additional investigation
491            m_subcycle = m_subc_reload;
492            m_PC = 0;
493            m_IP = reload_table[m_c_variant_rate&0x3]; // is this correct? should this be always 7 instead, so that the new frame is loaded quickly?
491            // ...then we now have enough bytes to start talking; set zpar and clear out the new frame parameters (it will become old frame just before the first call to parse_frame() )
492            m_zpar = 1;
493            m_uv_zpar = 1; // zero k4-k10 as well
494            m_OLDE = 1; // 'silence/zpar' frames are zero energy
495            m_OLDP = 1; // 'silence/zpar' frames are zero pitch
496#ifdef PERFECT_INTERPOLATION_HACK
497            m_old_zpar = 1; // zero all the old parameters
498            m_old_uv_zpar = 1; // zero old k4-k10 as well
499#endif
500            m_SPEN = 1;
501#ifdef FAST_START_HACK
502            m_TALK = 1;
503#endif
494504            m_new_frame_energy_idx = 0;
495505            m_new_frame_pitch_idx = 0;
496506            for (i = 0; i < 4; i++)
r249095r249096
499509               m_new_frame_k_idx[i] = 0xF;
500510            for (i = 7; i < m_coeff->num_k; i++)
501511               m_new_frame_k_idx[i] = 0x7;
502            m_talk_status = m_speaking_now = 1;
512
503513         }
504514      }
505515      else
506516      {
507517#ifdef DEBUG_FIFO
508         logerror("data_write: Ran out of room in the tms52xx FIFO! this should never happen!\n");
518         fprintf(stderr,"data_write: Ran out of room in the tms52xx FIFO! this should never happen!\n");
509519         // at this point, /READY should remain HIGH/inactive until the fifo has at least one byte open in it.
510520#endif
511521      }
512522
513523
514524   }
515   else //(! m_speak_external)
525   else //(! m_DDIS)
516526      // R Nabet : we parse commands at once.  It is necessary for such commands as read.
517527      process_command(data);
518528}
r249095r249096
560570      m_buffer_low = 0;
561571
562572   /* BE is set if neither byte 15 nor 14 of the fifo are in use; this
563   translates to having fifo_count equal to exactly 0 */
573   translates to having fifo_count equal to exactly 0
574   */
564575   if (m_fifo_count == 0)
565576   {
566577      // generate an interrupt if necessary; if /BE was inactive and is now active, set int.
567578      if (!m_buffer_empty)
568579         set_interrupt_state(1);
569580      m_buffer_empty = 1;
581      m_TALK = m_SPEN = 0; // /BE being active clears the TALK(TCON) status which in turn clears SPEN
570582   }
571583   else
572584      m_buffer_empty = 0;
573585
574   /* TS is talk status and is set elsewhere in the fifo parser and in
575   the SPEAK command handler; however, if /BE is true during speak external
576   mode, it is immediately unset here. */
577   if ((m_speak_external == 1) && (m_buffer_empty == 1))
586   // generate an interrupt if /TS was active, and is now inactive.
587   // also, in this case, regardless if DDIS was set, unset it.
588   if (m_previous_TALK_STATUS == 1 && (TALK_STATUS == 0))
578589   {
579      // generate an interrupt: /TS was active, and is now inactive.
580      if (m_talk_status == 1)
581      {
582         m_talk_status = m_speak_external = 0;
583         set_interrupt_state(1);
584      }
590#ifdef VERBOSE
591      fprintf(stderr,"Talk status WAS 1, is now 0, unsetting DDIS and firing an interrupt!\n");
592#endif
593      set_interrupt_state(1);
594      m_DDIS = 0;
585595   }
586   /* Note that TS being unset will also generate an interrupt when a STOP
587   frame is encountered; this is handled in the sample generator code and not here */
596   m_previous_TALK_STATUS = TALK_STATUS;
597
588598}
589599
590600/**********************************************************************************************
r249095r249096
597607{
598608   int val = 0;
599609
600   if (m_speak_external)
610   if (m_DDIS)
601611   {
602612      // extract from FIFO
603613      while (count--)
r249095r249096
643653      /* clear the interrupt pin on status read */
644654      set_interrupt_state(0);
645655#ifdef DEBUG_PIN_READS
646      logerror("Status read: TS=%d BL=%d BE=%d\n", m_talk_status, m_buffer_low, m_buffer_empty);
656      fprintf(stderr,"Status read: TS=%d BL=%d BE=%d\n", TALK_STATUS, m_buffer_low, m_buffer_empty);
647657#endif
648658
649      return (m_talk_status << 7) | (m_buffer_low << 6) | (m_buffer_empty << 5);
659      return (TALK_STATUS << 7) | (m_buffer_low << 6) | (m_buffer_empty << 5);
650660   }
651661}
652662
r249095r249096
660670int tms5220_device::ready_read()
661671{
662672#ifdef DEBUG_PIN_READS
663   logerror("ready_read: ready pin read, io_ready is %d, fifo count is %d\n", m_io_ready, m_fifo_count);
673   fprintf(stderr,"ready_read: ready pin read, io_ready is %d, fifo count is %d, DDIS(speak external) is %d\n", m_io_ready, m_fifo_count, m_DDIS);
664674#endif
665   return ((m_fifo_count < FIFO_SIZE)||(!m_speak_external)) && m_io_ready;
675   return ((m_fifo_count < FIFO_SIZE)||(!m_DDIS)) && m_io_ready;
666676}
667677
668678
r249095r249096
718728int tms5220_device::int_read()
719729{
720730#ifdef DEBUG_PIN_READS
721   logerror("int_read: irq pin read, state is %d\n", m_irq_pin);
731   fprintf(stderr,"int_read: irq pin read, state is %d\n", m_irq_pin);
722732#endif
723733   return m_irq_pin;
724734}
r249095r249096
733743void tms5220_device::process(INT16 *buffer, unsigned int size)
734744{
735745   int buf_count=0;
736   int i, bitout, zpar;
746   int i, bitout;
737747   INT32 this_sample;
738748
739   /* the following gotos are probably safe to remove */
740   /* if we're empty and still not speaking, fill with nothingness */
741   if (!m_speaking_now)
742      goto empty;
749#ifdef VERBOSE
750   fprintf(stderr,"process called with size of %d; IP=%d, PC=%d, subcycle=%d, m_SPEN=%d, m_TALK=%d, m_TALKD=%d\n", size, m_IP, m_PC, m_subcycle, m_SPEN, m_TALK, m_TALKD);
751#endif
743752
744   /* if speak external is set, but talk status is not (yet) set,
745   wait for buffer low to clear */
746   if (!m_talk_status && m_speak_external && m_buffer_low)
747      goto empty;
748
749753   /* loop until the buffer is full or we've stopped speaking */
750   while ((size > 0) && m_speaking_now)
754   while (size > 0)
751755   {
752      /* if it is the appropriate time to update the old energy/pitch indices,
753       * i.e. when IP=7, PC=12, T=17, subcycle=2, do so. Since IP=7 PC=12 T=17
754       * is JUST BEFORE the transition to IP=0 PC=0 T=0 sybcycle=(0 or 1),
755       * which happens 4 T-cycles later), we change on the latter.
756       * The indices are updated here ~12 PCs before the new frame is applied.
757       */
758      /** TODO: the patents 4331836, 4335277, and 4419540 disagree about the timing of this **/
759      if ((m_IP == 0) && (m_PC == 0) && (m_subcycle < 2))
756      if(m_TALKD) // speaking
760757      {
761         m_OLDE = (m_new_frame_energy_idx == 0);
762         m_OLDP = (m_new_frame_pitch_idx == 0);
763      }
758         /* if we're ready for a new frame to be applied, i.e. when IP=0, PC=12, Sub=1
759         * (In reality, the frame was really loaded incrementally during the entire IP=0
760         * PC=x time period, but it doesn't affect anything until IP=0 PC=12 happens)
761         */
762         if ((m_IP == 0) && (m_PC == 12) && (m_subcycle == 1))
763         {
764            // HACK for regression testing, be sure to comment out before release!
765            //m_RNG = 0x1234;
766            // end HACK
764767
765      /* if we're ready for a new frame to be applied, i.e. when IP=0, PC=12, Sub=1
766       * (In reality, the frame was really loaded incrementally during the entire IP=0
767       * PC=x time period, but it doesn't affect anything until IP=0 PC=12 happens)
768       */
769      if ((m_IP == 0) && (m_PC == 12) && (m_subcycle == 1))
770      {
771         // HACK for regression testing, be sure to comment out before release!
772         //m_RNG = 0x1234;
773         // end HACK
768            /* appropriately override the interp count if needed; this will be incremented after the frame parse! */
769            m_IP = reload_table[m_c_variant_rate&0x3];
774770
775         /* appropriately override the interp count if needed; this will be incremented after the frame parse! */
776         m_IP = reload_table[m_c_variant_rate&0x3];
777
778771#ifdef PERFECT_INTERPOLATION_HACK
779         /* remember previous frame energy, pitch, and coefficients */
780         m_old_frame_energy_idx = m_new_frame_energy_idx;
781         m_old_frame_pitch_idx = m_new_frame_pitch_idx;
782         for (i = 0; i < m_coeff->num_k; i++)
783            m_old_frame_k_idx[i] = m_new_frame_k_idx[i];
772            /* remember previous frame energy, pitch, and coefficients */
773            m_old_frame_energy_idx = m_new_frame_energy_idx;
774            m_old_frame_pitch_idx = m_new_frame_pitch_idx;
775            for (i = 0; i < m_coeff->num_k; i++)
776               m_old_frame_k_idx[i] = m_new_frame_k_idx[i];
784777#endif
785778
786         /* if the talk status was clear last frame, halt speech now. */
787         if (m_talk_status == 0)
788         {
789#ifdef DEBUG_GENERATION
790            fprintf(stderr,"tms5220_process: processing frame: talk status = 0 caused by stop frame or buffer empty, halting speech.\n");
791#endif
792            if (m_speaking_now == 1) // we're done, set all coeffs to idle state but keep going for a bit...
793            {
794               /**TODO: should index clearing be done here, or elsewhere? **/
795               m_new_frame_energy_idx = 0;
796               m_new_frame_pitch_idx = 0;
797               for (i = 0; i < 4; i++)
798                  m_new_frame_k_idx[i] = 0;
799               for (i = 4; i < 7; i++)
800                  m_new_frame_k_idx[i] = 0xF;
801               for (i = 7; i < m_coeff->num_k; i++)
802                  m_new_frame_k_idx[i] = 0x7;
803               m_speaking_now = 2; // wait 8 extra interp periods before shutting down so we can interpolate everything to zero state
804            }
805            else // m_speaking_now == 2 // now we're really done.
806            {
807               m_speaking_now = 0; // finally halt speech
808               goto empty;
809            }
810         }
779            /* Parse a new frame into the new_target_energy, new_target_pitch and new_target_k[] */
780            parse_frame();
811781
812
813         /* Parse a new frame into the new_target_energy, new_target_pitch and new_target_k[],
814          * but only if we're not just about to end speech */
815         if (m_speaking_now == 1) parse_frame();
816#ifdef DEBUG_PARSE_FRAME_DUMP
817         fprintf(stderr,"\n");
782            // if the new frame is unvoiced (or silenced via ZPAR), be sure to zero out the k5-k10 parameters
783            // NOTE: this is probably the bug the tms5100/tmc0280 has, pre-rev D, I think.
784            // GUESS: Pre-rev D versions start zeroing k5-k10 immediately upon new frame load regardless of interpolation inhibit
785            // I.e. ZPAR = /TALKD || (PC>5&&P=0)
786            // GUESS: D and later versions only start or stop zeroing k5-k10 at the IP7->IP0 transition AFTER the frame
787            // I.e. ZPAR = /TALKD || (PC>5&&OLDP)
788#ifdef PERFECT_INTERPOLATION_HACK
789            m_old_uv_zpar = m_uv_zpar;
790            m_old_zpar = m_zpar; // unset old zpar on new frame
818791#endif
792            m_zpar = 0;
793            //m_uv_zpar = (OLD_FRAME_UNVOICED_FLAG||m_zpar); // GUESS: fixed version in tmc0280d/tms5100a/cd280x/tms5110
794            m_uv_zpar = (NEW_FRAME_UNVOICED_FLAG||m_zpar); // GUESS: buggy version in tmc0280/tms5100
819795
820         /* if the new frame is a stop frame, set an interrupt and set talk status to 0 */
821         /** TODO: investigate this later! **/
822         if (NEW_FRAME_STOP_FLAG == 1)
796            /* if the new frame is a stop frame, unset both TALK and SPEN (via TCON). TALKD remains active while the energy is ramping to 0. */
797            if (NEW_FRAME_STOP_FLAG == 1)
823798            {
824               m_talk_status = m_speak_external = 0;
825               set_interrupt_state(1);
826               update_fifo_status_and_ints();
799               m_TALK = m_SPEN = 0;
827800            }
828801
829         /* in all cases where interpolation would be inhibited, set the inhibit flag; otherwise clear it.
830            Interpolation inhibit cases:
831          * Old frame was voiced, new is unvoiced
832          * Old frame was silence/zero energy, new has nonzero energy
833          * Old frame was unvoiced, new is voiced
834          * Old frame was unvoiced, new frame is silence/zero energy (unique to tms52xx)
835          */
836         if ( ((OLD_FRAME_UNVOICED_FLAG == 0) && (NEW_FRAME_UNVOICED_FLAG == 1))
837            || ((OLD_FRAME_UNVOICED_FLAG == 1) && (NEW_FRAME_UNVOICED_FLAG == 0))
838            || ((OLD_FRAME_SILENCE_FLAG == 1) && (NEW_FRAME_SILENCE_FLAG == 0))
839            || ((OLD_FRAME_UNVOICED_FLAG == 1) && (NEW_FRAME_SILENCE_FLAG == 1)) )
840            m_inhibit = 1;
841         else // normal frame, normal interpolation
842            m_inhibit = 0;
802            /* in all cases where interpolation would be inhibited, set the inhibit flag; otherwise clear it.
803            Interpolation inhibit cases:
804            * Old frame was voiced, new is unvoiced
805            * Old frame was silence/zero energy, new has nonzero energy
806            * Old frame was unvoiced, new is voiced
807            * Old frame was unvoiced, new frame is silence/zero energy (unique to tms52xx)
808            */
809            if ( ((OLD_FRAME_UNVOICED_FLAG == 0) && (NEW_FRAME_UNVOICED_FLAG == 1))
810               || ((OLD_FRAME_UNVOICED_FLAG == 1) && (NEW_FRAME_UNVOICED_FLAG == 0))
811               || ((OLD_FRAME_SILENCE_FLAG == 1) && (NEW_FRAME_SILENCE_FLAG == 0))
812               || ((OLD_FRAME_UNVOICED_FLAG == 1) && (NEW_FRAME_SILENCE_FLAG == 1)) )
813               m_inhibit = 1;
814            else // normal frame, normal interpolation
815               m_inhibit = 0;
843816
844         /* load new frame targets from tables, using parsed indices */
845         m_target_energy = m_coeff->energytable[m_new_frame_energy_idx];
846         m_target_pitch = m_coeff->pitchtable[m_new_frame_pitch_idx];
847         zpar = NEW_FRAME_UNVOICED_FLAG; // find out if parameters k5-k10 should be zeroed
848         for (i = 0; i < 4; i++)
849            m_target_k[i] = m_coeff->ktable[i][m_new_frame_k_idx[i]];
850         for (i = 4; i < m_coeff->num_k; i++)
851            m_target_k[i] = (m_coeff->ktable[i][m_new_frame_k_idx[i]] * (1-zpar));
852
853817#ifdef DEBUG_GENERATION
854         /* Debug info for current parsed frame */
855         fprintf(stderr, "OLDE: %d; OLDP: %d; ", m_OLDE, m_OLDP);
856         fprintf(stderr,"Processing frame: ");
857         if (m_inhibit == 0)
858            fprintf(stderr, "Normal Frame\n");
859         else
860            fprintf(stderr,"Interpolation Inhibited\n");
861         fprintf(stderr,"*** current Energy, Pitch and Ks =      %04d,   %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",m_current_energy, m_current_pitch, m_current_k[0], m_current_k[1], m_current_k[2], m_current_k[3], m_current_k[4], m_current_k[5], m_current_k[6], m_current_k[7], m_current_k[8], m_current_k[9]);
862         fprintf(stderr,"*** target Energy(idx), Pitch, and Ks = %04d(%x),%04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",m_target_energy, m_new_frame_energy_idx, m_target_pitch, m_target_k[0], m_target_k[1], m_target_k[2], m_target_k[3], m_target_k[4], m_target_k[5], m_target_k[6], m_target_k[7], m_target_k[8], m_target_k[9]);
818            /* Debug info for current parsed frame */
819            fprintf(stderr, "OLDE: %d; OLDP: %d; ", m_OLDE, m_OLDP);
820            fprintf(stderr,"Processing new frame: ");
821            if (m_inhibit == 0)
822               fprintf(stderr, "Normal Frame\n");
823            else
824               fprintf(stderr,"Interpolation Inhibited\n");
825            fprintf(stderr,"*** current Energy, Pitch and Ks =      %04d,   %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",m_current_energy, m_current_pitch, m_current_k[0], m_current_k[1], m_current_k[2], m_current_k[3], m_current_k[4], m_current_k[5], m_current_k[6], m_current_k[7], m_current_k[8], m_current_k[9]);
826            fprintf(stderr,"*** target Energy(idx), Pitch, and Ks = %04d(%x),%04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d, %04d\n",
827               (m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar)),
828               m_new_frame_energy_idx,
829               (m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar)),
830               (m_coeff->ktable[0][m_new_frame_k_idx[0]] * (1-m_zpar)),
831               (m_coeff->ktable[1][m_new_frame_k_idx[1]] * (1-m_zpar)),
832               (m_coeff->ktable[2][m_new_frame_k_idx[2]] * (1-m_zpar)),
833               (m_coeff->ktable[3][m_new_frame_k_idx[3]] * (1-m_zpar)),
834               (m_coeff->ktable[4][m_new_frame_k_idx[4]] * (1-m_uv_zpar)),
835               (m_coeff->ktable[5][m_new_frame_k_idx[5]] * (1-m_uv_zpar)),
836               (m_coeff->ktable[6][m_new_frame_k_idx[6]] * (1-m_uv_zpar)),
837               (m_coeff->ktable[7][m_new_frame_k_idx[7]] * (1-m_uv_zpar)),
838               (m_coeff->ktable[8][m_new_frame_k_idx[8]] * (1-m_uv_zpar)),
839               (m_coeff->ktable[9][m_new_frame_k_idx[9]] * (1-m_uv_zpar)) );
863840#endif
864841
865         /* if TS is now 0, ramp the energy down to 0. Is this really correct to hardware? */
866         if (m_talk_status == 0)
842         }
843         else // Not a new frame, just interpolate the existing frame.
867844         {
868#ifdef DEBUG_GENERATION
869            fprintf(stderr,"Talk status is 0, forcing target energy to 0\n");
845            int inhibit_state = ((m_inhibit==1)&&(m_IP != 0)); // disable inhibit when reaching the last interp period, but don't overwrite the m_inhibit value
846#ifdef PERFECT_INTERPOLATION_HACK
847            int samples_per_frame = m_subc_reload?175:266; // either (13 A cycles + 12 B cycles) * 7 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 7 interps for SPKSLOW
848            //int samples_per_frame = m_subc_reload?200:304; // either (13 A cycles + 12 B cycles) * 8 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 8 interps for SPKSLOW
849            int current_sample = (m_subcycle - m_subc_reload)+(m_PC*(3-m_subc_reload))+((m_subc_reload?25:38)*((m_IP-1)&7));
850            //fprintf(stderr, "CS: %03d", current_sample);
851            // reset the current energy, pitch, etc to what it was at frame start
852            m_current_energy = (m_coeff->energytable[m_old_frame_energy_idx] * (1-m_old_zpar));
853            m_current_pitch = (m_coeff->pitchtable[m_old_frame_pitch_idx] * (1-m_old_zpar));
854            for (i = 0; i < m_coeff->num_k; i++)
855               m_current_k[i] = (m_coeff->ktable[i][m_old_frame_k_idx[i]] * (1-((i<4)?m_old_zpar:m_old_uv_zpar)));
856            // now adjust each value to be exactly correct for each of the samples per frame
857            if (m_IP != 0) // if we're still interpolating...
858            {
859               m_current_energy = (m_current_energy + (((m_coeff->energytable[m_new_frame_energy_idx] - m_current_energy)*(1-inhibit_state))*current_sample)/samples_per_frame)*(1-m_zpar);
860               m_current_pitch = (m_current_pitch + (((m_coeff->pitchtable[m_new_frame_pitch_idx] - m_current_pitch)*(1-inhibit_state))*current_sample)/samples_per_frame)*(1-m_zpar);
861               for (i = 0; i < m_coeff->num_k; i++)
862                  m_current_k[i] = (m_current_k[i] + (((m_coeff->ktable[i][m_new_frame_k_idx[i]] - m_current_k[i])*(1-inhibit_state))*current_sample)/samples_per_frame)*(1-((i<4)?m_zpar:m_uv_zpar));
863            }
864            else // we're done, play this frame for 1/8 frame.
865            {
866               m_current_energy = (m_coeff->energytable[m_new_frame_energy_idx] * (1-m_zpar));
867               m_current_pitch = (m_coeff->pitchtable[m_new_frame_pitch_idx] * (1-m_zpar));
868               for (i = 0; i < m_coeff->num_k; i++)
869                  m_current_k[i] = (m_coeff->ktable[i][m_new_frame_k_idx[i]] * (1-((i<4)?m_zpar:m_uv_zpar)));
870            }
871#else
872            //Updates to parameters only happen on subcycle '2' (B cycle) of PCs.
873            if (m_subcycle == 2)
874            {
875               switch(m_PC)
876               {
877                  case 0: /* PC = 0, B cycle, write updated energy */
878                  m_current_energy = (m_current_energy + (((m_coeff->energytable[m_new_frame_energy_idx] - m_current_energy)*(1-inhibit_state)) INTERP_SHIFT))*(1-m_zpar);
879                  break;
880                  case 1: /* PC = 1, B cycle, write updated pitch */
881                  m_current_pitch = (m_current_pitch + (((m_coeff->pitchtable[m_new_frame_pitch_idx] - m_current_pitch)*(1-inhibit_state)) INTERP_SHIFT))*(1-m_zpar);
882                  break;
883                  case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11:
884                  /* PC = 2 through 11, B cycle, write updated K1 through K10 */
885                  m_current_k[m_PC-2] = (m_current_k[m_PC-2] + (((m_coeff->ktable[m_PC-2][m_new_frame_k_idx[m_PC-2]] - m_current_k[m_PC-2])*(1-inhibit_state)) INTERP_SHIFT))*(((m_PC-2)>4)?(1-m_uv_zpar):(1-m_zpar));
886                  break;
887                  case 12: /* PC = 12 */
888                  /* we should NEVER reach this point, PC=12 doesn't have a subcycle 2 */
889                  break;
890               }
891            }
870892#endif
871            m_target_energy = 0;
872893         }
873      }
874      else // Not a new frame, just interpolate the existing frame.
875      {
876         int inhibit_state = ((m_inhibit==1)&&(m_IP != 0)); // disable inhibit when reaching the last interp period, but don't overwrite the m_inhibit value
877#ifdef PERFECT_INTERPOLATION_HACK
878         int samples_per_frame = m_subc_reload?175:266; // either (13 A cycles + 12 B cycles) * 7 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 7 interps for SPKSLOW
879         //int samples_per_frame = m_subc_reload?200:304; // either (13 A cycles + 12 B cycles) * 8 interps for normal SPEAK/SPKEXT, or (13*2 A cycles + 12 B cycles) * 8 interps for SPKSLOW
880         int current_sample = (m_subcycle - m_subc_reload)+(m_PC*(3-m_subc_reload))+((m_subc_reload?25:38)*((m_IP-1)&7));
881894
882         zpar = OLD_FRAME_UNVOICED_FLAG;
883         //fprintf(stderr, "CS: %03d", current_sample);
884         // reset the current energy, pitch, etc to what it was at frame start
885         m_current_energy = m_coeff->energytable[m_old_frame_energy_idx];
886         m_current_pitch = m_coeff->pitchtable[m_old_frame_pitch_idx];
887         for (i = 0; i < 4; i++)
888            m_current_k[i] = m_coeff->ktable[i][m_old_frame_k_idx[i]];
889         for (i = 4; i < m_coeff->num_k; i++)
890            m_current_k[i] = (m_coeff->ktable[i][m_old_frame_k_idx[i]] * (1-zpar));
891         // now adjust each value to be exactly correct for each of the samples per frame
892         if (m_IP != 0) // if we're still interpolating...
895         // calculate the output
896         if (OLD_FRAME_UNVOICED_FLAG == 1)
893897         {
894            m_current_energy += (((m_target_energy - m_current_energy)*(1-inhibit_state))*current_sample)/samples_per_frame;
895            m_current_pitch += (((m_target_pitch - m_current_pitch)*(1-inhibit_state))*current_sample)/samples_per_frame;
896            for (i = 0; i < m_coeff->num_k; i++)
897               m_current_k[i] += (((m_target_k[i] - m_current_k[i])*(1-inhibit_state))*current_sample)/samples_per_frame;
898            // generate unvoiced samples here
899            if (m_RNG & 1)
900               m_excitation_data = ~0x3F; /* according to the patent it is (either + or -) half of the maximum value in the chirp table, so either 01000000(0x40) or 11000000(0xC0)*/
901            else
902               m_excitation_data = 0x40;
898903         }
899         else // we're done, play this frame for 1/8 frame.
904         else /* (OLD_FRAME_UNVOICED_FLAG == 0) */
900905         {
901            m_current_energy = m_target_energy;
902            m_current_pitch = m_target_pitch;
903            for (i = 0; i < m_coeff->num_k; i++)
904               m_current_k[i] = m_target_k[i];
906            // generate voiced samples here
907            /* US patent 4331836 Figure 14B shows, and logic would hold, that a pitch based chirp
908            * function has a chirp/peak and then a long chain of zeroes.
909            * The last entry of the chirp rom is at address 0b110011 (51d), the 52nd sample,
910            * and if the address reaches that point the ADDRESS incrementer is
911            * disabled, forcing all samples beyond 51d to be == 51d
912            */
913            if (m_pitch_count >= 51)
914               m_excitation_data = (INT8)m_coeff->chirptable[51];
915            else /*m_pitch_count < 51*/
916               m_excitation_data = (INT8)m_coeff->chirptable[m_pitch_count];
905917         }
906#else
907         //Updates to parameters only happen on subcycle '2' (B cycle) of PCs.
908         if (m_subcycle == 2)
918
919         // Update LFSR *20* times every sample (once per T cycle), like patent shows
920         for (i=0; i<20; i++)
909921         {
910            switch(m_PC)
911            {
912               case 0: /* PC = 0, B cycle, write updated energy */
913               m_current_energy += (((m_target_energy - m_current_energy)*(1-inhibit_state)) INTERP_SHIFT);
914               break;
915               case 1: /* PC = 1, B cycle, write updated pitch */
916               m_current_pitch += (((m_target_pitch - m_current_pitch)*(1-inhibit_state)) INTERP_SHIFT);
917               break;
918               case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11:
919               /* PC = 2 through 11, B cycle, write updated K1 through K10 */
920               m_current_k[m_PC-2] += (((m_target_k[m_PC-2] - m_current_k[m_PC-2])*(1-inhibit_state)) INTERP_SHIFT);
921               break;
922               case 12: /* PC = 12, do nothing */
923               break;
924            }
922            bitout = ((m_RNG >> 12) & 1) ^
923                  ((m_RNG >>  3) & 1) ^
924                  ((m_RNG >>  2) & 1) ^
925                  ((m_RNG >>  0) & 1);
926            m_RNG <<= 1;
927            m_RNG |= bitout;
925928         }
926#endif
927      }
928
929      // calculate the output
930      if (OLD_FRAME_UNVOICED_FLAG == 1)
931      {
932         // generate unvoiced samples here
933         if (m_RNG & 1)
934            m_excitation_data = ~0x3F; /* according to the patent it is (either + or -) half of the maximum value in the chirp table, so either 01000000(0x40) or 11000000(0xC0)*/
935         else
936            m_excitation_data = 0x40;
937      }
938      else /* (OLD_FRAME_UNVOICED_FLAG == 0) */
939      {
940         // generate voiced samples here
941         /* US patent 4331836 Figure 14B shows, and logic would hold, that a pitch based chirp
942          * function has a chirp/peak and then a long chain of zeroes.
943          * The last entry of the chirp rom is at address 0b110011 (51d), the 52nd sample,
944          * and if the address reaches that point the ADDRESS incrementer is
945          * disabled, forcing all samples beyond 51d to be == 51d
946          */
947         if (m_pitch_count >= 51)
948            m_excitation_data = (INT8)m_coeff->chirptable[51];
949         else /*m_pitch_count < 51*/
950            m_excitation_data = (INT8)m_coeff->chirptable[m_pitch_count];
951      }
952
953      // Update LFSR *20* times every sample (once per T cycle), like patent shows
954   for (i=0; i<20; i++)
955   {
956      bitout = ((m_RNG >> 12) & 1) ^
957            ((m_RNG >>  3) & 1) ^
958            ((m_RNG >>  2) & 1) ^
959            ((m_RNG >>  0) & 1);
960      m_RNG <<= 1;
961      m_RNG |= bitout;
962   }
963      this_sample = lattice_filter(); /* execute lattice filter */
929         this_sample = lattice_filter(); /* execute lattice filter */
964930#ifdef DEBUG_GENERATION_VERBOSE
965      //fprintf(stderr,"C:%01d; ",m_subcycle);
966      fprintf(stderr,"IP:%01d PC:%02d X:%04d E:%03d P:%03d Pc:%03d ",m_IP, m_PC, m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
967      //fprintf(stderr,"X:%04d E:%03d P:%03d Pc:%03d ", m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
968      for (i=0; i<10; i++)
969         fprintf(stderr,"K%d:%04d ", i+1, m_current_k[i]);
970      fprintf(stderr,"Out:%06d", this_sample);
971      fprintf(stderr,"\n");
931         //fprintf(stderr,"C:%01d; ",m_subcycle);
932         fprintf(stderr,"IP:%01d PC:%02d X:%04d E:%03d P:%03d Pc:%03d ",m_IP, m_PC, m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
933         //fprintf(stderr,"X:%04d E:%03d P:%03d Pc:%03d ", m_excitation_data, m_current_energy, m_current_pitch, m_pitch_count);
934         for (i=0; i<10; i++)
935            fprintf(stderr,"K%d:%04d ", i+1, m_current_k[i]);
936         fprintf(stderr,"Out:%06d ", this_sample);
937//#ifdef PERFECT_INTERPOLATION_HACK
938//         fprintf(stderr,"%d%d%d%d",m_old_zpar,m_zpar,m_old_uv_zpar,m_uv_zpar);
939//#else
940//         fprintf(stderr,"x%dx%d",m_zpar,m_uv_zpar);
941//#endif
942         fprintf(stderr,"\n");
972943#endif
973      /* next, force result to 14 bits (since its possible that the addition at the final (k1) stage of the lattice overflowed) */
974      while (this_sample > 16383) this_sample -= 32768;
975      while (this_sample < -16384) this_sample += 32768;
976      if (m_digital_select == 0) // analog SPK pin output is only 8 bits, with clipping
977         buffer[buf_count] = clip_analog(this_sample);
978      else // digital I/O pin output is 12 bits
979      {
944         /* next, force result to 14 bits (since its possible that the addition at the final (k1) stage of the lattice overflowed) */
945         while (this_sample > 16383) this_sample -= 32768;
946         while (this_sample < -16384) this_sample += 32768;
947         if (m_digital_select == 0) // analog SPK pin output is only 8 bits, with clipping
948            buffer[buf_count] = clip_analog(this_sample);
949         else // digital I/O pin output is 12 bits
950         {
980951#ifdef ALLOW_4_LSB
981         // input:  ssss ssss ssss ssss ssnn nnnn nnnn nnnn
982         // N taps:                       ^                 = 0x2000;
983         // output: ssss ssss ssss ssss snnn nnnn nnnn nnnN
984         buffer[buf_count] = (this_sample<<1)|((this_sample&0x2000)>>13);
952            // input:  ssss ssss ssss ssss ssnn nnnn nnnn nnnn
953            // N taps:                       ^                 = 0x2000;
954            // output: ssss ssss ssss ssss snnn nnnn nnnn nnnN
955            buffer[buf_count] = (this_sample<<1)|((this_sample&0x2000)>>13);
985956#else
986         this_sample &= ~0xF;
987         // input:  ssss ssss ssss ssss ssnn nnnn nnnn 0000
988         // N taps:                       ^^ ^^^            = 0x3E00;
989         // output: ssss ssss ssss ssss snnn nnnn nnnN NNNN
990         buffer[buf_count] = (this_sample<<1)|((this_sample&0x3E00)>>9);
957            this_sample &= ~0xF;
958            // input:  ssss ssss ssss ssss ssnn nnnn nnnn 0000
959            // N taps:                       ^^ ^^^            = 0x3E00;
960            // output: ssss ssss ssss ssss snnn nnnn nnnN NNNN
961            buffer[buf_count] = (this_sample<<1)|((this_sample&0x3E00)>>9);
991962#endif
992      }
993      // Update all counts
963         }
964         // Update all counts
994965
995      m_subcycle++;
996      if ((m_subcycle == 2) && (m_PC == 12))
997      {
998         /* Circuit 412 in the patent acts a reset, resetting the pitch counter to 0
999          * if INHIBIT was true during the most recent frame transition.
1000          * The exact time this occurs is betwen IP=7, PC=12 sub=0, T=t12
1001          * and m_IP = 0, PC=0 sub=0, T=t12, a period of exactly 20 cycles,
1002          * which overlaps the time OLDE and OLDP are updated at IP=7 PC=12 T17
1003          * (and hence INHIBIT itself 2 t-cycles later). We do it here because it is
1004          * convenient and should make no difference in output.
1005          */
1006         if ((m_IP == 7)&&(m_inhibit==1)) m_pitch_count = 0;
1007         m_subcycle = m_subc_reload;
1008         m_PC = 0;
1009         m_IP++;
1010         m_IP&=0x7;
966         m_subcycle++;
967         if ((m_subcycle == 2) && (m_PC == 12)) // RESETF3
968         {
969            /* Circuit 412 in the patent acts a reset, resetting the pitch counter to 0
970            * if INHIBIT was true during the most recent frame transition.
971            * The exact time this occurs is betwen IP=7, PC=12 sub=0, T=t12
972            * and m_IP = 0, PC=0 sub=0, T=t12, a period of exactly 20 cycles,
973            * which overlaps the time OLDE and OLDP are updated at IP=7 PC=12 T17
974            * (and hence INHIBIT itself 2 t-cycles later). We do it here because it is
975            * convenient and should make no difference in output.
976            */
977            if ((m_IP == 7)&&(m_inhibit==1)) m_pitch_zero = 1;
978            if ((m_IP == 0)&&(m_pitch_zero==1)) m_pitch_zero = 0;
979            if (m_IP == 7) // RESETL4
980            {
981               // Latch OLDE and OLDP
982               OLD_FRAME_SILENCE_FLAG = NEW_FRAME_SILENCE_FLAG; // m_OLDE
983               OLD_FRAME_UNVOICED_FLAG = NEW_FRAME_UNVOICED_FLAG; // m_OLDP
984               /* if TALK was clear last frame, halt speech now, since TALKD (latched from TALK on new frame) just went inactive. */
985#ifdef DEBUG_GENERATION
986               fprintf(stderr,"RESETL4, about to update status: IP=%d, PC=%d, subcycle=%d, m_SPEN=%d, m_TALK=%d, m_TALKD=%d\n", m_IP, m_PC, m_subcycle, m_SPEN, m_TALK, m_TALKD);
987#endif
988#ifdef DEBUG_GENERATION
989               if (m_TALK == 0)
990                  fprintf(stderr,"tms5220_process: processing frame: TALKD = 0 caused by stop frame or buffer empty, halting speech.\n");
991#endif
992               m_TALKD = m_TALK; // TALKD is latched from TALK
993               update_fifo_status_and_ints(); // to trigger an interrupt if TALK_STATUS is now inactive
994               m_TALK = m_SPEN; // TALK is latched from SPEN
995#ifdef DEBUG_GENERATION
996               fprintf(stderr,"RESETL4, status updated: IP=%d, PC=%d, subcycle=%d, m_SPEN=%d, m_TALK=%d, m_TALKD=%d\n", m_IP, m_PC, m_subcycle, m_SPEN, m_TALK, m_TALKD);
997#endif
998            }
999            m_subcycle = m_subc_reload;
1000            m_PC = 0;
1001            m_IP++;
1002            m_IP&=0x7;
1003         }
1004         else if (m_subcycle == 3)
1005         {
1006            m_subcycle = m_subc_reload;
1007            m_PC++;
1008         }
1009         m_pitch_count++;
1010         if ((m_pitch_count >= m_current_pitch)||(m_pitch_zero == 1)) m_pitch_count = 0;
1011         m_pitch_count &= 0x1FF;
10111012      }
1012      else if (m_subcycle == 3)
1013      else // m_TALKD == 0
10131014      {
1014         m_subcycle = m_subc_reload;
1015         m_PC++;
1015         m_subcycle++;
1016         if ((m_subcycle == 2) && (m_PC == 12)) // RESETF3
1017         {
1018            if (m_IP == 7) // RESETL4
1019            {
1020               m_TALKD = m_TALK; // TALKD is latched from TALK
1021               m_TALK = m_SPEN; // TALK is latched from SPEN
1022            }
1023            m_subcycle = m_subc_reload;
1024            m_PC = 0;
1025            m_IP++;
1026            m_IP&=0x7;
1027         }
1028         else if (m_subcycle == 3)
1029         {
1030            m_subcycle = m_subc_reload;
1031            m_PC++;
1032         }
1033         buffer[buf_count] = -1; /* should be just -1; actual chip outputs -1 every idle sample; (cf note in data sheet, p 10, table 4) */
10161034      }
1017      m_pitch_count++;
1018      if (m_pitch_count >= m_current_pitch) m_pitch_count = 0;
1019      m_pitch_count &= 0x1FF;
1020      buf_count++;
1021      size--;
1035   buf_count++;
1036   size--;
10221037   }
1023
1024empty:
1025
1026   while (size > 0)
1027   {
1028      m_subcycle++;
1029      if ((m_subcycle == 2) && (m_PC == 12))
1030      {
1031         m_subcycle = m_subc_reload;
1032         m_PC = 0;
1033         m_IP++;
1034         m_IP&=0x7;
1035      }
1036      else if (m_subcycle == 3)
1037      {
1038         m_subcycle = m_subc_reload;
1039         m_PC++;
1040      }
1041      buffer[buf_count] = -1; /* should be just -1; actual chip outputs -1 every idle sample; (cf note in data sheet, p 10, table 4) */
1042      buf_count++;
1043      size--;
1044   }
10451038}
10461039
10471040/**********************************************************************************************
r249095r249096
11821175
11831176void tms5220_device::process_command(unsigned char cmd)
11841177{
1178   int i;
11851179#ifdef DEBUG_COMMAND_DUMP
11861180      fprintf(stderr,"process_command called with parameter %02X\n",cmd);
11871181#endif
r249095r249096
11891183      switch (cmd & 0x70)
11901184      {
11911185      case 0x10 : /* read byte */
1192         if (m_talk_status == 0) /* TALKST must be clear for RDBY */
1186         if (TALK_STATUS == 0) /* TALKST must be clear for RDBY */
11931187         {
11941188            if (m_schedule_dummy_read)
11951189            {
r249095r249096
12111205      break;
12121206
12131207      case 0x30 : /* read and branch */
1214         if (m_talk_status == 0) /* TALKST must be clear for RB */
1208         if (TALK_STATUS == 0) /* TALKST must be clear for RB */
12151209         {
12161210#ifdef VERBOSE
1217            logerror("read and branch command received\n");
1211            fprintf(stderr,"read and branch command received\n");
12181212#endif
12191213            m_RDB_flag = FALSE;
12201214            if (m_speechrom)
r249095r249096
12231217         break;
12241218
12251219      case 0x40 : /* load address */
1226         if (m_talk_status == 0) /* TALKST must be clear for LA */
1220         if (TALK_STATUS == 0) /* TALKST must be clear for LA */
12271221         {
12281222            /* tms5220 data sheet says that if we load only one 4-bit nibble, it won't work.
12291223               This code does not care about this. */
r249095r249096
12401234            if (m_speechrom)
12411235               m_speechrom->read(1);
12421236         }
1243         m_speaking_now = 1;
1244         m_speak_external = 0;
1245         m_talk_status = 1;  /* start immediately */
1246         /* clear out variables before speaking */
1247         // TODO: similar to the victory case described above, but for VSM speech
1248         m_subcycle = m_subc_reload;
1249         m_PC = 0;
1250         m_IP = reload_table[m_c_variant_rate&0x3];
1237         m_SPEN = 1;
1238#ifdef FAST_START_HACK
1239         m_TALK = 1;
1240#endif
1241         m_DDIS = 0;
1242         m_zpar = 1; // zero all the parameters
1243         m_uv_zpar = 1; // zero k4-k10 as well
1244         m_OLDE = 1; // 'silence/zpar' frames are zero energy
1245         m_OLDP = 1; // 'silence/zpar' frames are zero pitch
1246#ifdef PERFECT_INTERPOLATION_HACK
1247         m_old_zpar = 1; // zero all the old parameters
1248         m_old_uv_zpar = 1; // zero old k4-k10 as well
1249#endif
1250         // following is semi-hack but matches idle state observed on chip
12511251         m_new_frame_energy_idx = 0;
12521252         m_new_frame_pitch_idx = 0;
1253         int i;
12541253         for (i = 0; i < 4; i++)
12551254            m_new_frame_k_idx[i] = 0;
12561255         for (i = 4; i < 7; i++)
r249095r249096
12601259         break;
12611260
12621261      case 0x60 : /* speak external */
1263         //SPKEXT going active activates SPKEE which clears the fifo
1262         // SPKEXT going active activates SPKEE which clears the fifo
12641263         m_fifo_head = m_fifo_tail = m_fifo_count = m_fifo_bits_taken = 0;
1265         m_speak_external = 1;
1264         // SPEN is enabled when the fifo passes half full (falling edge of BL signal)
1265         m_DDIS = 1;
1266         m_zpar = 1; // zero all the parameters
1267         m_uv_zpar = 1; // zero k4-k10 as well
1268         m_OLDE = 1; // 'silence/zpar' frames are zero energy
1269         m_OLDP = 1; // 'silence/zpar' frames are zero pitch
1270#ifdef PERFECT_INTERPOLATION_HACK
1271         m_old_zpar = 1; // zero all the old parameters
1272         m_old_uv_zpar = 1; // zero old k4-k10 as well
1273#endif
1274         // following is semi-hack but matches idle state observed on chip
1275         m_new_frame_energy_idx = 0;
1276         m_new_frame_pitch_idx = 0;
1277         for (i = 0; i < 4; i++)
1278            m_new_frame_k_idx[i] = 0;
1279         for (i = 4; i < 7; i++)
1280            m_new_frame_k_idx[i] = 0xF;
1281         for (i = 7; i < m_coeff->num_k; i++)
1282            m_new_frame_k_idx[i] = 0x7;
12661283         m_RDB_flag = FALSE;
12671284         break;
12681285
r249095r249096
13081325   m_IP = reload_table[m_c_variant_rate&0x3];
13091326
13101327   update_fifo_status_and_ints();
1311   if (!m_talk_status) goto ranout;
1328   if (m_DDIS && m_buffer_empty) goto ranout;
13121329
13131330   // attempt to extract the energy index
13141331   m_new_frame_energy_idx = extract_bits(m_coeff->energy_bits);
r249095r249096
13171334   fprintf(stderr," ");
13181335#endif
13191336   update_fifo_status_and_ints();
1320   if (!m_talk_status) goto ranout;
1337   if (m_DDIS && m_buffer_empty) goto ranout;
13211338   // if the energy index is 0 or 15, we're done
13221339   if ((m_new_frame_energy_idx == 0) || (m_new_frame_energy_idx == 15))
13231340      return;
r249095r249096
13371354   fprintf(stderr," ");
13381355#endif
13391356   update_fifo_status_and_ints();
1340   if (!m_talk_status) goto ranout;
1357   if (m_DDIS && m_buffer_empty) goto ranout;
13411358   // if this is a repeat frame, just do nothing, it will reuse the old coefficients
13421359   if (rep_flag)
13431360      return;
r249095r249096
13511368      fprintf(stderr," ");
13521369#endif
13531370      update_fifo_status_and_ints();
1354      if (!m_talk_status) goto ranout;
1371      if (m_DDIS && m_buffer_empty) goto ranout;
13551372   }
13561373
13571374   // if the pitch index was zero, we only need 4 K's...
r249095r249096
13701387      fprintf(stderr," ");
13711388#endif
13721389      update_fifo_status_and_ints();
1373      if (!m_talk_status) goto ranout;
1390      if (m_DDIS && m_buffer_empty) goto ranout;
13741391   }
1392#ifdef DEBUG_PARSE_FRAME_DUMP
1393         fprintf(stderr,"\n");
1394#endif
13751395#ifdef VERBOSE
1376   if (m_speak_external)
1377      logerror("Parsed a frame successfully in FIFO - %d bits remaining\n", (m_fifo_count*8)-(m_fifo_bits_taken));
1396   if (m_DDIS)
1397      fprintf(stderr,"Parsed a frame successfully in FIFO - %d bits remaining\n", (m_fifo_count*8)-(m_fifo_bits_taken));
13781398   else
1379      logerror("Parsed a frame successfully in ROM\n");
1399      fprintf(stderr,"Parsed a frame successfully in ROM\n");
13801400#endif
13811401   return;
13821402
13831403   ranout:
13841404#ifdef DEBUG_FRAME_ERRORS
1385   logerror("Ran out of bits on a parse!\n");
1405   fprintf(stderr,"Ran out of bits on a parse!\n");
13861406#endif
13871407   return;
13881408}
r249095r249096
13971417{
13981418   if (!TMS5220_IS_52xx) return; // bail out if not a 52xx chip, since there's no int pin
13991419#ifdef DEBUG_PIN_READS
1400   logerror("irq pin set to state %d\n", state);
1420   fprintf(stderr,"irq pin set to state %d\n", state);
14011421#endif
14021422   if (!m_irq_handler.isnull() && state != m_irq_pin)
14031423      m_irq_handler(!state);
r249095r249096
14141434{
14151435   int state = ready_read();
14161436#ifdef DEBUG_PIN_READS
1417   logerror("ready pin set to state %d\n", state);
1437   fprintf(stderr,"ready pin set to state %d\n", state);
14181438#endif
14191439   if (!m_readyq_handler.isnull() && state != m_ready_pin)
14201440      m_readyq_handler(!state);
r249095r249096
15141534
15151535   /* initialize the chip state */
15161536   /* Note that we do not actually clear IRQ on start-up : IRQ is even raised if m_buffer_empty or m_buffer_low are 0 */
1517   m_speaking_now = m_speak_external = m_talk_status = m_irq_pin = m_ready_pin = 0;
1537   m_SPEN = m_DDIS = m_TALK = m_TALKD = m_previous_TALK_STATUS = m_irq_pin = m_ready_pin = 0;
15181538   set_interrupt_state(0);
15191539   update_ready_state();
15201540   m_buffer_empty = m_buffer_low = 1;
r249095r249096
15251545#ifdef PERFECT_INTERPOLATION_HACK
15261546   m_old_frame_energy_idx = m_old_frame_pitch_idx = 0;
15271547   memset(m_old_frame_k_idx, 0, sizeof(m_old_frame_k_idx));
1548   m_old_zpar = 0;
15281549#endif
1529   m_new_frame_energy_idx = m_current_energy = m_target_energy = m_previous_energy = 0;
1530   m_new_frame_pitch_idx = m_current_pitch = m_target_pitch = 0;
1550   m_new_frame_energy_idx = m_current_energy =  m_previous_energy = 0;
1551   m_new_frame_pitch_idx = m_current_pitch = 0;
1552   m_zpar = m_uv_zpar = 0;
15311553   memset(m_new_frame_k_idx, 0, sizeof(m_new_frame_k_idx));
15321554   memset(m_current_k, 0, sizeof(m_current_k));
1533   memset(m_target_k, 0, sizeof(m_target_k));
15341555
15351556   /* initialize the sample generators */
15361557   m_inhibit = 1;
r249095r249096
15741595            /* Write */
15751596            /* bring up to date first */
15761597#ifdef DEBUG_IO_READY
1577            logerror("Serviced write: %02x\n", m_write_latch);
1598            fprintf(stderr,"Serviced write: %02x\n", m_write_latch);
15781599            //fprintf(stderr, "Processed write data: %02X\n", m_write_latch);
15791600#endif
15801601            m_stream->update();
r249095r249096
16101631   m_true_timing = 1;
16111632   state &= 0x01;
16121633#ifdef DEBUG_RS_WS
1613   logerror("/RS written with data: %d\n", state);
1634   fprintf(stderr,"/RS written with data: %d\n", state);
16141635#endif
16151636   new_val = (m_rs_ws & 0x01) | (state<<1);
16161637   if (new_val != m_rs_ws)
r249095r249096
16231644#ifdef DEBUG_RS_WS
16241645         else
16251646            /* illegal */
1626            logerror("tms5220_rs_w: illegal\n");
1647            fprintf(stderr,"tms5220_rs_w: illegal\n");
16271648#endif
16281649         return;
16291650      }
r249095r249096
16411662      {
16421663         /* high to low - schedule ready cycle */
16431664#ifdef DEBUG_RS_WS
1644         logerror("Scheduling ready cycle for /RS...\n");
1665         fprintf(stderr,"Scheduling ready cycle for /RS...\n");
16451666#endif
16461667         /* upon /RS being activated, /READY goes inactive after 100 nsec from data sheet, through 3 asynchronous gates on patent. This is effectively within one clock, so we immediately set io_ready to 0 and activate the callback. */
16471668         m_io_ready = 0;
r249095r249096
16621683   m_true_timing = 1;
16631684   state &= 0x01;
16641685#ifdef DEBUG_RS_WS
1665   logerror("/WS written with data: %d\n", state);
1686   fprintf(stderr,"/WS written with data: %d\n", state);
16661687#endif
16671688   new_val = (m_rs_ws & 0x02) | (state<<0);
16681689   if (new_val != m_rs_ws)
r249095r249096
16751696#ifdef DEBUG_RS_WS
16761697         else
16771698            /* illegal */
1678            logerror("tms5220_ws_w: illegal\n");
1699            fprintf(stderr,"tms5220_ws_w: illegal\n");
16791700#endif
16801701         return;
16811702      }
r249095r249096
16931714      {
16941715         /* high to low - schedule ready cycle */
16951716#ifdef DEBUG_RS_WS
1696         logerror("Scheduling ready cycle for /WS...\n");
1717         fprintf(stderr,"Scheduling ready cycle for /WS...\n");
16971718#endif
16981719         /* upon /WS being activated, /READY goes inactive after 100 nsec from data sheet, through 3 asynchronous gates on patent. This is effectively within one clock, so we immediately set io_ready to 0 and activate the callback. */
16991720         m_io_ready = 0;
r249095r249096
17261747   if (space.debugger_access()) return;
17271748
17281749#ifdef DEBUG_RS_WS
1729   logerror("tms5220_data_w: data %02x\n", data);
1750   fprintf(stderr,"tms5220_data_w: data %02x\n", data);
17301751#endif
17311752   if (!m_true_timing)
17321753   {
r249095r249096
17391760      /* actually in a write ? */
17401761#ifdef DEBUG_RS_WS
17411762      if (!(m_rs_ws == 0x02))
1742         logerror("tms5220_data_w: data written outside ws, status: %02x!\n", m_rs_ws);
1763         fprintf(stderr,"tms5220_data_w: data written outside ws, status: %02x!\n", m_rs_ws);
17431764#endif
17441765      m_write_latch = data;
17451766   }
r249095r249096
17711792         return m_read_latch;
17721793#ifdef DEBUG_RS_WS
17731794      else
1774         logerror("tms5220_status_r: data read outside rs!\n");
1795         fprintf(stderr,"tms5220_status_r: data read outside rs!\n");
17751796#endif
17761797      return 0xff;
17771798   }
trunk/src/emu/sound/tms5220.h
r249095r249096
105105
106106
107107   /* these contain global status bits */
108   UINT8 m_speaking_now;     /* True only if actual speech is being generated right now. Is set when a speak vsm command happens OR when speak external happens and buffer low becomes nontrue; Is cleared when speech halts after the last stop frame or the last frame after talk status is otherwise cleared.*/
109   UINT8 m_speak_external;   /* If 1, DDIS is 1, i.e. Speak External command in progress, writes go to FIFO. */
110   UINT8 m_talk_status;      /* If 1, TS status bit is 1, i.e. speak or speak external is in progress and we have not encountered a stop frame yet; talk_status differs from speaking_now in that speaking_now is set as soon as a speak or speak external command is started; talk_status does NOT go active until after 8 bytes are written to the fifo on a speak external command, otherwise the two are the same. TS is cleared by 3 things: 1. when a STOP command has just been processed as a new frame in the speech stream; 2. if the fifo runs out in speak external mode; 3. on power-up/during a reset command; When it gets cleared, speak_external is also cleared, an interrupt is generated, and speaking_now will be cleared when the next frame starts. */
108   UINT8 m_previous_TALK_STATUS;      /* this is the OLD value of TALK_STATUS (i.e. previous value of m_SPEN|m_TALKD), needed for generating interrupts on a falling TALK_STATUS edge */
109   UINT8 m_SPEN;             /* set on speak(or speak external and BL falling edge) command, cleared on stop command, reset command, or buffer out */
110   UINT8 m_DDIS;             /* If 1, DDIS is 1, i.e. Speak External command in progress, writes go to FIFO. */
111   UINT8 m_TALK;             /* set on SPEN & RESETL4(pc12->pc0 transition), cleared on stop command or reset command */
112#define TALK_STATUS (m_SPEN|m_TALKD)
113   UINT8 m_TALKD;            /* TALK(TCON) value, latched every RESETL4 */
111114   UINT8 m_buffer_low;       /* If 1, FIFO has less than 8 bytes in it */
112115   UINT8 m_buffer_empty;     /* If 1, FIFO is empty */
113116   UINT8 m_irq_pin;          /* state of the IRQ pin (output) */
r249095r249096
132135   INT16 m_current_energy;
133136   INT16 m_current_pitch;
134137   INT16 m_current_k[10];
135
136   INT16 m_target_energy;
137   INT16 m_target_pitch;
138   INT16 m_target_k[10];
139138#else
140139   UINT8 m_old_frame_energy_idx;
141140   UINT8 m_old_frame_pitch_idx;
142141   UINT8 m_old_frame_k_idx[10];
142   UINT8 m_old_zpar;
143   UINT8 m_old_uv_zpar;
143144
144145   INT32 m_current_energy;
145146   INT32 m_current_pitch;
146147   INT32 m_current_k[10];
147
148   INT32 m_target_energy;
149   INT32 m_target_pitch;
150   INT32 m_target_k[10];
151148#endif
152149
153150   UINT16 m_previous_energy; /* needed for lattice filter to match patent */
r249095r249096
155152   UINT8 m_subcycle;         /* contains the current subcycle for a given PC: 0 is A' (only used on SPKSLOW mode on 51xx), 1 is A, 2 is B */
156153   UINT8 m_subc_reload;      /* contains 1 for normal speech, 0 when SPKSLOW is active */
157154   UINT8 m_PC;               /* current parameter counter (what param is being interpolated), ranges from 0 to 12 */
158   /* TODO/NOTE: the current interpolation period, counts 1,2,3,4,5,6,7,0 for divide by 8,8,8,4,4,2,2,1 */
155   /* NOTE: the interpolation period counts 1,2,3,4,5,6,7,0 for divide by 8,8,8,4,4,2,2,1 */
159156   UINT8 m_IP;               /* the current interpolation period */
160157   UINT8 m_inhibit;          /* If 1, interpolation is inhibited until the DIV1 period */
158   UINT8 m_uv_zpar;          /* If 1, zero k5 thru k10 coefficients */
159   UINT8 m_zpar;             /* If 1, zero ALL parameters. */
160   UINT8 m_pitch_zero;       /* circuit 412; pitch is forced to zero under certain circumstances */
161161   UINT8 m_c_variant_rate;    /* only relevant for tms5220C's multi frame rate feature; is the actual 4 bit value written on a 0x2* or 0x0* command */
162162   UINT16 m_pitch_count;     /* pitch counter; provides chirp rom address */
163163
164164   INT32 m_u[11];
165165   INT32 m_x[10];
166166
167   UINT16 m_RNG;             /* the random noise generator configuration is: 1 + x + x^3 + x^4 + x^13 */
167   UINT16 m_RNG;             /* the random noise generator configuration is: 1 + x + x^3 + x^4 + x^13 TODO: no it isn't */
168168   INT16 m_excitation_data;
169169
170170   /* R Nabet : These have been added to emulate speech Roms */
trunk/src/emu/video/poly.h
r249095r249096
3434
3535#pragma once
3636
37#ifndef __POLYNEW_H__
38#define __POLYNEW_H__
37#ifndef __POLY_H__
38#define __POLY_H__
3939
4040#include <limits.h>
4141
r249095r249096
11721172   return nextout - outv;
11731173}
11741174
1175#endif  // __POLYNEW_H__
1175#endif  // __POLY_H__
trunk/src/emu/video/polylgcy.h
r249095r249096
3434
3535#pragma once
3636
37#ifndef __POLYNEW_H__
38#define __POLYNEW_H__
37#ifndef __POLYLGCY_H__
38#define __POLYLGCY_H__
3939
4040
4141/***************************************************************************
r249095r249096
152152int poly_zclip_if_less(int numverts, const poly_vertex *v, poly_vertex *outv, int paramcount, float clipval);
153153
154154
155#endif  /* __POLY_H__ */
155#endif  /* __POLYLGCY_H__ */
trunk/src/mame/arcade.lst
r249095r249096
82208220nbajamte3       // (c) 1994 Midway
82218221nbajamten       // (c) 1995 Midway
82228222revx            // (c) 1994 Midway
8223revxp5          // (c) 1994 Midway
82238224mk3             // (c) 1994 Midway
82248225mk3r20          // (c) 1994 Midway
82258226mk3r10          // (c) 1994 Midway
r249095r249096
95659566magicbubb       // (c) Yun Sung
95669567shocking        // (c) 1997 Yun Sung
95679568shockingk       // (c) 1997 Yun Sung
9569shockingko      // (c) 1997 Yun Sung
95689570bombkick        // (c) 1998 Yun Sung
95699571bombkicka       // (c) 1998 Yun Sung
95709572nmg5            // (c) 1998 Yun Sung
trunk/src/mame/audio/hng64.c
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner
33/* Hyper NeoGeo 64 Audio */
44
55// uses a V53A ( == V33A with extra peripherals eg. DMA, Timers, MMU giving virtual 24-bit address space etc.)
trunk/src/mame/drivers/cps1.c
r249095r249096
95449544   ROM_LOAD( "sou1",         0x0000, 0x0117, CRC(84f4b2fe) SHA1(dcc9e86cc36316fe42eace02d6df75d08bc8bb6d) )
95459545
95469546   ROM_REGION( 0x0200, "bboardplds", 0 )
9547   ROM_LOAD( "va63b.1a",     0x0000, 0x0117, BAD_DUMP CRC(38540e86) SHA1(86e0aba363108f80a8eff84b99d11528ad6db099) ) /* Handcrafted but works on actual US PCB.  Redump needed */
9547   ROM_LOAD( "va63b.1a",     0x0000, 0x0117, CRC(132ab7c5) SHA1(54b78b02cdd9430c90e2289d42585ee71cf71cdc) )
95489548   ROM_LOAD( "iob1.12d",     0x0000, 0x0117, CRC(3abc0700) SHA1(973043aa46ec6d5d1db20dc9d5937005a0f9f6ae) )
95499549   ROM_LOAD( "bprg1.11d",    0x0000, 0x0117, CRC(31793da7) SHA1(400fa7ac517421c978c1ee7773c30b9ed0c5d3f3) )
95509550ROM_END
r249095r249096
96309630   ROM_LOAD( "sou1",         0x0000, 0x0117, CRC(84f4b2fe) SHA1(dcc9e86cc36316fe42eace02d6df75d08bc8bb6d) )
96319631
96329632   ROM_REGION( 0x0200, "bboardplds", 0 )
9633   ROM_LOAD( "va63b.1a",     0x0000, 0x0117, BAD_DUMP CRC(38540e86) SHA1(86e0aba363108f80a8eff84b99d11528ad6db099) ) /* Handcrafted but works on actual US PCB.  Redump needed */
9633   ROM_LOAD( "va63b.1a",     0x0000, 0x0117, CRC(132ab7c5) SHA1(54b78b02cdd9430c90e2289d42585ee71cf71cdc) )
96349634   ROM_LOAD( "iob1.12d",     0x0000, 0x0117, CRC(3abc0700) SHA1(973043aa46ec6d5d1db20dc9d5937005a0f9f6ae) )
96359635   ROM_LOAD( "bprg1.11d",    0x0000, 0x0117, CRC(31793da7) SHA1(400fa7ac517421c978c1ee7773c30b9ed0c5d3f3) )
96369636
trunk/src/mame/drivers/deco32.c
r249095r249096
223223
224224                   PROM.9J     Fujitsu MB7124 compatible with 82S147  Labelled 'LN-00'
225225
226Night Slashers
227Data East, 1993
228               
229DE-0395-1   DEC-22VO
230|-----------------------------------------------------|
231| TA8205AH  6164            |-----|   2M-16M*   MBH-07|
232|            02-  HuC6280A  | 52  |   MBH-09    MBH-06|
233|           YM2151          |     |   2M-16M*   MBH-05|
234|     YM3012      32.220MHz |-----|   MBH-08    MBH-04|
235|  JP1   MBH-11   93C45     |-----|             MBH-03|
236|CN2     MBH-10             | 52  |             MBH-02|
237|  M6295(1)                 |     |                   |
238|     M6295(2)              |-----|                   |
239|      |-----|                       |-----|          |
240|J     | 104 |    |-----|  |-----|   | 52  |          |
241|A     |     |    | 153 |  | 113 |   |     |          |
242|M     |-----|    |     |  |     |   |-----|          |
243|M                |-----|  |-----|            28MHz   |
244|A  |-----|                                           |
245|   | 99  |  VM-02                                    |
246|   |     |  LN-00             |-----| 6164    MBH-01 |
247|   |-----|                    | 74  | 6164           |
248|                              |     |         MBH-00 |
249|      |-----|  |-----|        |-----|                |
250|      | 113 |  | 200 |        |-----| 6164           |
251|      |     |  |     |        | 141 | 6164           |
252|      |-----|  |-----|        |     |  VE-01A        |
253|TEST_SW                       |-----|  VE-00 |-----| |
254|                                             | 156 | |
255|  CN4      LH52250  LH52250     01-          |     | |
256|  CN3      LH52250  LH52250     00-          |-----| |
257|-----------------------------------------------------|
226258
259NOTE: Program EPROMs did NOT have regional letter codes, just 00, 01 & 02
227260
261Same PCB as shown below for Fighter's History, but populated with more
262chips as needed. It is worth noting that Night Slashers uses the encryption
263features of the 156 chip where as Fighter's History does not.
264
265*****************************************************************************************************
266
228267Fighter's History
229268Data East, 1993
230269
r249095r249096
261300|  CN3*     LH52250  LH52250   LE00           |-----| |
262301|-----------------------------------------------------|
263302
303
264304Very similar to the DE-0396-0 described below with the notable exceptions:
265305  The sound area reworked to use the HuC6280A instead of a standard Z80
266306  Uses the larger 113 instead of the 153 chips, however both PCBs have
r249095r249096
24722512
24732513/**********************************************************************************/
24742514
2475ROM_START( captaven )
2515ROM_START( captaven ) /* DE-0351-x PCB (x=3 or 4) */
24762516   ROM_REGION(0x100000, "maincpu", 0 ) /* ARM 32 bit code */
24772517   ROM_LOAD32_BYTE( "hn_00-4.1e",  0x000000, 0x20000, CRC(147fb094) SHA1(6bd759c42f4b7f9e1c3f2d3ece0b3ec72de1a982) )
24782518   ROM_LOAD32_BYTE( "hn_01-4.1h",  0x000001, 0x20000, CRC(11ecdb95) SHA1(832b56f05ae7e15e67fbdd321da8c1cc5e7629a0) )
r249095r249096
25222562
25232563   ROM_REGION(0x80000, "oki1", 0 )
25242564   ROM_LOAD( "man-11.16k", 0x000000,  0x80000,  CRC(0dc60a4c) SHA1(4d0daa6a0272852a37f341a0cdc48baee0ad9dd8) )
2565
2566   ROM_REGION( 0x0600, "plds", 0 )
2567   ROM_LOAD( "ts-00.4h",  0x0000, 0x0117, CRC(ebc2908e) SHA1(dca14a55abd1d88ee09092d4122614e55c3e7f53) )
2568   ROM_LOAD( "ts-01.5h",  0x0200, 0x0117, CRC(c776a980) SHA1(cd4bdcfb755f561fefa4c88fab5d6d2397332aa7) )
2569   ROM_LOAD( "ts-02.12l", 0x0400, 0x01bf, CRC(6f26528c) SHA1(2cf869b2a789a9b0646162a61c147bcbb13c9141) )
25252570ROM_END
25262571
2527ROM_START( captavena )
2572ROM_START( captavena ) /* DE-0351-x PCB (x=3 or 4) */
25282573   ROM_REGION(0x100000, "maincpu", 0 ) /* ARM 32 bit code */
25292574   ROM_LOAD32_BYTE( "hn_00.e1",    0x000000, 0x20000, CRC(12dd0c71) SHA1(77bd0e5f1b105ec70de5e76cb9c8138f02a496be) )
25302575   ROM_LOAD32_BYTE( "hn_01.h1",    0x000001, 0x20000, CRC(ac5ea492) SHA1(e08fa2b3e3a40cba6dcdf07049d67056d59ed72a) )
r249095r249096
25742619
25752620   ROM_REGION(0x80000, "oki1", 0 )
25762621   ROM_LOAD( "man-11.16k", 0x000000,  0x80000,  CRC(0dc60a4c) SHA1(4d0daa6a0272852a37f341a0cdc48baee0ad9dd8) )
2622
2623   ROM_REGION( 0x0600, "plds", 0 )
2624   ROM_LOAD( "ts-00.4h",  0x0000, 0x0117, CRC(ebc2908e) SHA1(dca14a55abd1d88ee09092d4122614e55c3e7f53) )
2625   ROM_LOAD( "ts-01.5h",  0x0200, 0x0117, CRC(c776a980) SHA1(cd4bdcfb755f561fefa4c88fab5d6d2397332aa7) )
2626   ROM_LOAD( "ts-02.12l", 0x0400, 0x01bf, CRC(6f26528c) SHA1(2cf869b2a789a9b0646162a61c147bcbb13c9141) )
25772627ROM_END
25782628
2579ROM_START( captavene )
2629ROM_START( captavene ) /* DE-0351-x PCB (x=3 or 4) */
25802630   ROM_REGION(0x100000, "maincpu", 0 ) /* ARM 32 bit code */
25812631   ROM_LOAD32_BYTE( "hg_00-4.1e",  0x000000, 0x20000, CRC(7008d43c) SHA1(a39143e13075ebc58ecc576391f04d2649675dfb) )
25822632   ROM_LOAD32_BYTE( "hg_01-4.1h",  0x000001, 0x20000, CRC(53dc1042) SHA1(4547ad20e5bc3b9cedae53f73f1628fa3493aafa) )
r249095r249096
26282678   ROM_LOAD( "man-11.16k", 0x000000,  0x80000,  CRC(0dc60a4c) SHA1(4d0daa6a0272852a37f341a0cdc48baee0ad9dd8) )
26292679
26302680   ROM_REGION( 0x0800, "plds", 0 )
2631   ROM_LOAD( "pal16l8a.12l", 0x0000, 0x0104, NO_DUMP ) /* PAL is read protected */
2632   ROM_LOAD( "pal16l8a.4h",  0x0200, 0x0104, NO_DUMP ) /* PAL is read protected */
2633   ROM_LOAD( "pal16l8a.5h",  0x0400, 0x0104, NO_DUMP ) /* PAL is read protected */
2681   ROM_LOAD( "ts-00.4h",  0x0000, 0x0117, CRC(ebc2908e) SHA1(dca14a55abd1d88ee09092d4122614e55c3e7f53) )
2682   ROM_LOAD( "ts-01.5h",  0x0200, 0x0117, CRC(c776a980) SHA1(cd4bdcfb755f561fefa4c88fab5d6d2397332aa7) )
2683   ROM_LOAD( "ts-02.12l", 0x0400, 0x01bf, CRC(6f26528c) SHA1(2cf869b2a789a9b0646162a61c147bcbb13c9141) )
26342684   ROM_LOAD( "pal16r8b.14c", 0x0600, 0x0104, NO_DUMP ) /* PAL is read protected */
26352685ROM_END
26362686
2637ROM_START( captavenu )
2687ROM_START( captavenu ) /* DE-0351-x PCB (x=3 or 4) */
26382688   ROM_REGION(0x100000, "maincpu", 0 ) /* ARM 32 bit code */
26392689   ROM_LOAD32_BYTE( "hh_00-19.1e", 0x000000, 0x20000, CRC(08b870e0) SHA1(44c837e3c5dfc9764d89b0ebb3e9b7a40fe4d76f) )
26402690   ROM_LOAD32_BYTE( "hh_01-19.1h", 0x000001, 0x20000, CRC(0dc0feca) SHA1(cb1c97aac59dabcf6c37bc1562cf2f62bca951f1) )
r249095r249096
26842734
26852735   ROM_REGION(0x80000, "oki1", 0 )
26862736   ROM_LOAD( "man-11.16k", 0x000000,  0x80000,  CRC(0dc60a4c) SHA1(4d0daa6a0272852a37f341a0cdc48baee0ad9dd8) )
2737
2738   ROM_REGION( 0x0600, "plds", 0 )
2739   ROM_LOAD( "ts-00.4h",  0x0000, 0x0117, CRC(ebc2908e) SHA1(dca14a55abd1d88ee09092d4122614e55c3e7f53) )
2740   ROM_LOAD( "ts-01.5h",  0x0200, 0x0117, CRC(c776a980) SHA1(cd4bdcfb755f561fefa4c88fab5d6d2397332aa7) )
2741   ROM_LOAD( "ts-02.12l", 0x0400, 0x01bf, CRC(6f26528c) SHA1(2cf869b2a789a9b0646162a61c147bcbb13c9141) )
26872742ROM_END
26882743
2689ROM_START( captavenuu )
2744ROM_START( captavenuu ) /* DE-0351-x PCB (x=3 or 4) */
26902745   ROM_REGION(0x100000, "maincpu", 0 ) /* ARM 32 bit code */
26912746   ROM_LOAD32_BYTE( "hh-00.1e",    0x000000, 0x20000, CRC(c34da654) SHA1(a1988a6a45991db6dee10b484049f6703b4671c9) )
26922747   ROM_LOAD32_BYTE( "hh-01.1h",    0x000001, 0x20000, CRC(55abe63f) SHA1(98772eff3ebb5a4f243c7a77d398eb142d1505cb) )
r249095r249096
27362791
27372792   ROM_REGION(0x80000, "oki1", 0 )
27382793   ROM_LOAD( "man-11.16k", 0x000000,  0x80000,  CRC(0dc60a4c) SHA1(4d0daa6a0272852a37f341a0cdc48baee0ad9dd8) )
2794
2795   ROM_REGION( 0x0600, "plds", 0 )
2796   ROM_LOAD( "ts-00.4h",  0x0000, 0x0117, CRC(ebc2908e) SHA1(dca14a55abd1d88ee09092d4122614e55c3e7f53) )
2797   ROM_LOAD( "ts-01.5h",  0x0200, 0x0117, CRC(c776a980) SHA1(cd4bdcfb755f561fefa4c88fab5d6d2397332aa7) )
2798   ROM_LOAD( "ts-02.12l", 0x0400, 0x01bf, CRC(6f26528c) SHA1(2cf869b2a789a9b0646162a61c147bcbb13c9141) )
27392799ROM_END
27402800
2741ROM_START( captavenua )
2801ROM_START( captavenua ) /* DE-0351-x PCB (x=3 or 4) */
27422802   ROM_REGION(0x100000, "maincpu", 0 ) /* ARM 32 bit code */
27432803   ROM_LOAD32_BYTE( "hh_00-4.2e",   0x000000, 0x20000, CRC(0e1acc05) SHA1(7eb6206efad233f9f4ee51102f9fe6b58f0719ea) )
27442804   ROM_LOAD32_BYTE( "hh_01-4.2h",   0x000001, 0x20000, CRC(4ff0351d) SHA1(15fc2662ff0d32986c4d4d074b985ad853da34e1) )
r249095r249096
27882848
27892849   ROM_REGION(0x80000, "oki1", 0 )
27902850   ROM_LOAD( "man-11.16k", 0x000000,  0x80000,  CRC(0dc60a4c) SHA1(4d0daa6a0272852a37f341a0cdc48baee0ad9dd8) )
2851
2852   ROM_REGION( 0x0600, "plds", 0 )
2853   ROM_LOAD( "ts-00.4h",  0x0000, 0x0117, CRC(ebc2908e) SHA1(dca14a55abd1d88ee09092d4122614e55c3e7f53) )
2854   ROM_LOAD( "ts-01.5h",  0x0200, 0x0117, CRC(c776a980) SHA1(cd4bdcfb755f561fefa4c88fab5d6d2397332aa7) )
2855   ROM_LOAD( "ts-02.12l", 0x0400, 0x01bf, CRC(6f26528c) SHA1(2cf869b2a789a9b0646162a61c147bcbb13c9141) )
27912856ROM_END
27922857
2793ROM_START( captavenj )
2858ROM_START( captavenj ) /* DE-0351-x PCB (x=3 or 4) */
27942859   ROM_REGION(0x100000, "maincpu", 0 ) /* ARM 32 bit code */
27952860   ROM_LOAD32_BYTE( "hj_00-2.1e",  0x000000, 0x20000, CRC(10b1faaf) SHA1(9d76885200a846b4751c8d44ff591e2aff7c4148) )
27962861   ROM_LOAD32_BYTE( "hj_01-2.1h",  0x000001, 0x20000, CRC(62c59f27) SHA1(20bbb7f3ff63a8c795686c1d56d51e90305daa77) )
r249095r249096
28402905
28412906   ROM_REGION(0x80000, "oki1", 0 )
28422907   ROM_LOAD( "man-11.16k", 0x000000,  0x80000,  CRC(0dc60a4c) SHA1(4d0daa6a0272852a37f341a0cdc48baee0ad9dd8) )
2908
2909   ROM_REGION( 0x0600, "plds", 0 )
2910   ROM_LOAD( "ts-00.4h",  0x0000, 0x0117, CRC(ebc2908e) SHA1(dca14a55abd1d88ee09092d4122614e55c3e7f53) )
2911   ROM_LOAD( "ts-01.5h",  0x0200, 0x0117, CRC(c776a980) SHA1(cd4bdcfb755f561fefa4c88fab5d6d2397332aa7) )
2912   ROM_LOAD( "ts-02.12l", 0x0400, 0x01bf, CRC(6f26528c) SHA1(2cf869b2a789a9b0646162a61c147bcbb13c9141) )
28432913ROM_END
28442914
28452915ROM_START( dragngun )
r249095r249096
30223092   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
30233093
30243094   ROM_REGION( 0x0400, "plds", 0 )
3025   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3026   ROM_LOAD( "ve-01.4d",  0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3095   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3096   ROM_LOAD( "ve-01.4d",  0x0200, 0x0117, CRC(4ba7e6a9) SHA1(b65d696a3519e792df226f9f148c759cdb0e1e43) )
30273097ROM_END
30283098
30293099ROM_START( fghthista ) /* DE-0380-2 PCB */
r249095r249096
30563126   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
30573127
30583128   ROM_REGION( 0x0400, "plds", 0 )
3059   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3060   ROM_LOAD( "ve-01.4d",  0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3129   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3130   ROM_LOAD( "ve-01.4d",  0x0200, 0x0117, CRC(4ba7e6a9) SHA1(b65d696a3519e792df226f9f148c759cdb0e1e43) )
3131   /* PAL16L8BCN at 8J is unpopulated */
30613132ROM_END
30623133
30633134ROM_START( fghthistu ) /* DE-0396-0 PCB */
r249095r249096
30903161   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
30913162
30923163   ROM_REGION( 0x0400, "plds", 0 )
3093   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3094   ROM_LOAD( "ve-01.4d",  0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3164   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3165   ROM_LOAD( "ve-01.4d",  0x0200, 0x0117, CRC(4ba7e6a9) SHA1(b65d696a3519e792df226f9f148c759cdb0e1e43) )
3166   /* PAL16L8BCN at 8J is unpopulated */
30953167ROM_END
30963168
30973169ROM_START( fghthistua ) /* DE-0395-1 PCB */
r249095r249096
31243196   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
31253197
31263198   ROM_REGION( 0x0400, "plds", 0 )
3127   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3128   ROM_LOAD( "ve-01a.4d", 0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3199   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3200   ROM_LOAD( "ve-01a.4d", 0x0200, 0x0117, CRC(109613c8) SHA1(5991e010c1bc2a827c8ee2c85a9b40e00a3167b3) )
3201   /* PAL16L8BCN at 8J is unpopulated */
31293202ROM_END
31303203
31313204ROM_START( fghthistub ) /* DE-0395-1 PCB */
r249095r249096
31583231   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
31593232
31603233   ROM_REGION( 0x0400, "plds", 0 )
3161   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3162   ROM_LOAD( "ve-01a.4d", 0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3234   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3235   ROM_LOAD( "ve-01a.4d", 0x0200, 0x0117, CRC(109613c8) SHA1(5991e010c1bc2a827c8ee2c85a9b40e00a3167b3) )
3236   /* PAL16L8BCN at 8J is unpopulated */
31633237ROM_END
31643238
31653239ROM_START( fghthistuc ) /* DE-0380-2 PCB */
r249095r249096
31923266   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
31933267
31943268   ROM_REGION( 0x0400, "plds", 0 )
3195   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3196   ROM_LOAD( "ve-01.4d",  0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3269   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3270   ROM_LOAD( "ve-01.4d",  0x0200, 0x0117, CRC(4ba7e6a9) SHA1(b65d696a3519e792df226f9f148c759cdb0e1e43) )
3271   /* PAL16L8BCN at 8J is unpopulated */
31973272ROM_END
31983273
31993274ROM_START( fghthistj ) /* DE-0395-1 PCB */
r249095r249096
32263301   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
32273302
32283303   ROM_REGION( 0x0400, "plds", 0 )
3229   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3230   ROM_LOAD( "ve-01a.4d", 0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3304   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3305   ROM_LOAD( "ve-01a.4d", 0x0200, 0x0117, CRC(109613c8) SHA1(5991e010c1bc2a827c8ee2c85a9b40e00a3167b3) )
3306   /* PAL16L8BCN at 8J is unpopulated */
32313307ROM_END
32323308
32333309ROM_START( fghthistja ) /* DE-0380-2 PCB */
r249095r249096
32603336   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
32613337
32623338   ROM_REGION( 0x0400, "plds", 0 )
3263   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3264   ROM_LOAD( "ve-01.4d",  0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3339   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3340   ROM_LOAD( "ve-01.4d",  0x0200, 0x0117, CRC(4ba7e6a9) SHA1(b65d696a3519e792df226f9f148c759cdb0e1e43) )
3341   /* PAL16L8BCN at 8J is unpopulated */
32653342ROM_END
32663343
32673344ROM_START( fghthistjb ) /* DE-0380-1 PCB */
r249095r249096
32943371   ROM_LOAD( "kt-00.8j",  0,  512,  CRC(7294354b) SHA1(14fe42ad5d26d022c0fe9a46a4a9017af2296f40) ) /* MB7124H type prom */
32953372
32963373   ROM_REGION( 0x0400, "plds", 0 )
3297   ROM_LOAD( "ve-00.3d",  0x0000, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3298   ROM_LOAD( "ve-01.4d",  0x0200, 0x0104, NO_DUMP ) /* PAL16L8 is read protected */
3374   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3375   ROM_LOAD( "ve-01.4d",  0x0200, 0x0117, CRC(4ba7e6a9) SHA1(b65d696a3519e792df226f9f148c759cdb0e1e43) )
3376   /* PAL16L8BCN at 8J is unpopulated */
32993377ROM_END
33003378
33013379ROM_START( lockload ) /* Board No. DE-0420-1 + Bottom board DE-0421-0 slightly different hardware, a unique PCB and not a Dragongun conversion */
r249095r249096
36733751   ROM_LOAD( "eeprom-tattass.bin", 0x0000, 0x0400, CRC(7140f40c) SHA1(4fb7897933046b6adaf00b4626d5fd23d0e8a666) )
36743752ROM_END
36753753
3676ROM_START( nslasher )
3754ROM_START( nslasher ) /* DE-0397-0 PCB */
36773755   ROM_REGION(0x100000, "maincpu", 0 ) /* Encrypted ARM 32 bit code */
36783756   ROM_LOAD32_WORD( "mainprg.1f", 0x000000, 0x80000, CRC(507acbae) SHA1(329a2bb244f2f3adb8d75cab5aa2dcb129d70712) )
36793757   ROM_LOAD32_WORD( "mainprg.2f", 0x000002, 0x80000, CRC(931fc7ee) SHA1(54eb12abfa3f332ce9b43a45ec424aaee88641a6) )
r249095r249096
36813759   ROM_REGION(0x10000, "audiocpu", 0 ) /* Sound CPU */
36823760   ROM_LOAD( "sndprg.17l",  0x00000,  0x10000,  CRC(18939e92) SHA1(50b37a78d9d2259d4b140dd17393c4e5ca92bca5) )
36833761
3684
36853762   ROM_REGION( 0x200000, "gfx1", 0 )
36863763   ROM_LOAD( "mbh-00.8c",  0x000000,  0x200000,  CRC(a877f8a3) SHA1(79253525f360a73161894f31e211e4d6b38d307a) ) /* Encrypted tiles */
36873764
r249095r249096
37083785
37093786   ROM_REGION(0x200, "prom", 0 )
37103787   ROM_LOAD( "ln-00.j7", 0x000000,  0x200, CRC(5e83eaf3) SHA1(95f5eb8e56dff6c2dce7c39a6dd458bfc38fe1cf) )
3788
3789   ROM_REGION( 0x0600, "plds", 0 )
3790   ROM_LOAD( "vm-00.3d",  0x0000, 0x0117, NO_DUMP ) /* 16L8ACN is read protected */
3791   ROM_LOAD( "vm-01.4d",  0x0200, 0x0117, NO_DUMP ) /* 16L8ACN is read protected */
3792   ROM_LOAD( "vm-02.8j",  0x0400, 0x0117, CRC(53692426) SHA1(b8f8cf6b1f6b637fcd1fcd62474e637f5d4a6901) )
37113793ROM_END
37123794
3713ROM_START( nslasherj )
3795ROM_START( nslasherj ) /* DE-0397-0 PCB */
37143796   ROM_REGION(0x100000, "maincpu", 0 ) /* Encrypted ARM 32 bit code */
37153797   ROM_LOAD32_WORD( "lx-00.1f", 0x000000, 0x80000, CRC(6ed5fb88) SHA1(84350da7939a479968a523c84e254e3ee54b8da2) )
37163798   ROM_LOAD32_WORD( "lx-01.2f", 0x000002, 0x80000, CRC(a6df2152) SHA1(6fe7e0b2e71c5f807951dcc81a6a3cff55247961) )
r249095r249096
37443826
37453827   ROM_REGION(0x200, "prom", 0 )
37463828   ROM_LOAD( "ln-00.j7", 0x000000,  0x200, CRC(5e83eaf3) SHA1(95f5eb8e56dff6c2dce7c39a6dd458bfc38fe1cf) )
3829
3830   ROM_REGION( 0x0600, "plds", 0 )
3831   ROM_LOAD( "vm-00.3d",  0x0000, 0x0117, NO_DUMP ) /* 16L8ACN is read protected */
3832   ROM_LOAD( "vm-01.4d",  0x0200, 0x0117, NO_DUMP ) /* 16L8ACN is read protected */
3833   ROM_LOAD( "vm-02.8j",  0x0400, 0x0117, CRC(53692426) SHA1(b8f8cf6b1f6b637fcd1fcd62474e637f5d4a6901) )
37473834ROM_END
37483835
3749ROM_START( nslashers )
3836ROM_START( nslashers ) /* DE-0397-0 PCB */
37503837   ROM_REGION(0x100000, "maincpu", 0 ) /* Encrypted ARM 32 bit code */
37513838   ROM_LOAD32_WORD( "ly-00.1f", 0x000000, 0x80000, CRC(fa0646f9) SHA1(7f9633bda230a0ced59171cdc5ab40a6d56c3d34) )
37523839   ROM_LOAD32_WORD( "ly-01.2f", 0x000002, 0x80000, CRC(ae508149) SHA1(3592949e5fb2770adb9c9daa4e38c4e75f3e2554) )
r249095r249096
37803867
37813868   ROM_REGION(0x200, "prom", 0 )
37823869   ROM_LOAD( "ln-00.j7", 0x000000,  0x200, CRC(5e83eaf3) SHA1(95f5eb8e56dff6c2dce7c39a6dd458bfc38fe1cf) )
3870
3871   ROM_REGION( 0x0600, "plds", 0 )
3872   ROM_LOAD( "vm-00.3d",  0x0000, 0x0117, NO_DUMP ) /* 16L8ACN is read protected */
3873   ROM_LOAD( "vm-01.4d",  0x0200, 0x0117, NO_DUMP ) /* 16L8ACN is read protected */
3874   ROM_LOAD( "vm-02.8j",  0x0400, 0x0117, CRC(53692426) SHA1(b8f8cf6b1f6b637fcd1fcd62474e637f5d4a6901) )
37833875ROM_END
37843876
3785ROM_START( nslasheru )
3877ROM_START( nslasheru ) /* DE-0395-1 PCB */
37863878   ROM_REGION(0x100000, "maincpu", 0 ) /* Encrypted ARM 32 bit code */
37873879   ROM_LOAD32_WORD( "00.f1", 0x000000, 0x80000, CRC(944f3329) SHA1(7e7909e203b9752de3d3d798c6f84ac6ae824a07) )
37883880   ROM_LOAD32_WORD( "01.f2", 0x000002, 0x80000, CRC(ac12d18a) SHA1(7cd4e843bf575c70c5c39a8afa78b803106f59b0) )
r249095r249096
38163908
38173909   ROM_REGION(0x200, "prom", 0 )
38183910   ROM_LOAD( "ln-00.j7", 0x000000,  0x200, CRC(5e83eaf3) SHA1(95f5eb8e56dff6c2dce7c39a6dd458bfc38fe1cf) )
3911
3912   ROM_REGION( 0x0600, "plds", 0 )
3913   ROM_LOAD( "ve-00.3d",  0x0000, 0x0117, CRC(384d316c) SHA1(61b50c695d4210c199cf6f7bbe50c8a5ecd1d21c) )
3914   ROM_LOAD( "ve-01a.4d", 0x0200, 0x0117, CRC(109613c8) SHA1(5991e010c1bc2a827c8ee2c85a9b40e00a3167b3) )
3915   ROM_LOAD( "vm-02.8j",  0x0400, 0x0117, CRC(53692426) SHA1(b8f8cf6b1f6b637fcd1fcd62474e637f5d4a6901) )
38193916ROM_END
38203917
38213918DRIVER_INIT_MEMBER(deco32_state,captaven)
r249095r249096
39784075GAME( 1991, captavenua, captaven, captaven, captaven, deco32_state,   captaven,  ROT0, "Data East Corporation", "Captain America and The Avengers (US Rev 1.4)", MACHINE_SUPPORTS_SAVE )
39794076GAME( 1991, captavenj,  captaven, captaven, captaven, deco32_state,   captaven,  ROT0, "Data East Corporation", "Captain America and The Avengers (Japan Rev 0.2)", MACHINE_SUPPORTS_SAVE )
39804077
3981// DE-0396-0 PCB sets (uses a Z80)
4078// DE-0396-0 PCB sets (Z80 for sound)
39824079GAME( 1993, fghthistu,  fghthist, fghthistz,fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (US ver 42-09, DE-0396-0 PCB)", MACHINE_SUPPORTS_SAVE )
3983// DE-0395-1 PCB sets
4080// DE-0395-1 PCB sets (HuC6280 for sound)
39844081GAME( 1993, fghthistua, fghthist, fghthsta, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (US ver 42-06, DE-0395-1 PCB)", MACHINE_SUPPORTS_SAVE )
39854082GAME( 1993, fghthistub, fghthist, fghthsta, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (US ver 42-05, DE-0395-1 PCB)", MACHINE_SUPPORTS_SAVE )
39864083GAME( 1993, fghthistj,  fghthist, fghthsta, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (Japan ver 41-07, DE-0395-1 PCB)", MACHINE_SUPPORTS_SAVE )
3987// DE-0380-2 PCB sets
4084// DE-0380-2 PCB sets (HuC6280 for sound)
39884085GAME( 1993, fghthist,   0,        fghthist, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (World ver 43-07, DE-0380-2 PCB)", MACHINE_SUPPORTS_SAVE )
39894086GAME( 1993, fghthista,  fghthist, fghthist, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (World ver 43-05, DE-0380-2 PCB)", MACHINE_SUPPORTS_SAVE )
39904087GAME( 1993, fghthistuc, fghthist, fghthist, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (US ver 42-03, DE-0380-2 PCB)", MACHINE_SUPPORTS_SAVE )
39914088GAME( 1993, fghthistja, fghthist, fghthist, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (Japan ver 41-05, DE-0380-2 PCB)", MACHINE_SUPPORTS_SAVE )
3992// DE-0380-1 PCB sets
4089// DE-0380-1 PCB sets (HuC6280 for sound)
39934090GAME( 1993, fghthistjb, fghthist, fghthist, fghthist, deco32_state,   fghthist,  ROT0, "Data East Corporation", "Fighter's History (Japan ver 41-04, DE-0380-1 PCB)", MACHINE_SUPPORTS_SAVE )
39944091
3995GAME( 1994, nslasher,   0,        nslasher, nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (Korea Rev 1.3)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
3996GAME( 1994, nslasherj,  nslasher, nslasher, nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (Japan Rev 1.2)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
3997GAME( 1994, nslashers,  nslasher, nslasher, nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (Over Sea Rev 1.2)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
3998GAME( 1994, nslasheru,  nslasher, nslasheru,nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (US Rev 1.2, HuC6280 Sound CPU)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
4092// DE-0397-0 PCB sets (Z80 for sound)
4093GAME( 1994, nslasher,   0,        nslasher, nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (Korea Rev 1.3, DE-0397-0 PCB)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
4094GAME( 1994, nslasherj,  nslasher, nslasher, nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (Japan Rev 1.2, DE-0397-0 PCB)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
4095GAME( 1994, nslashers,  nslasher, nslasher, nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (Over Sea Rev 1.2, DE-0397-0 PCB)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
4096// DE-0395-1 PCB sets (HuC6280 for sound)
4097GAME( 1994, nslasheru,  nslasher, nslasheru,nslasher, deco32_state,   nslasher,  ROT0, "Data East Corporation", "Night Slashers (US Rev 1.2, DE-0395-1 PCB)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
39994098
40004099GAME( 1994, tattass,    0,        tattass,  tattass,  deco32_state,   tattass,   ROT0, "Data East Pinball",     "Tattoo Assassins (US prototype)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
40014100GAME( 1994, tattassa,   tattass,  tattass,  tattass,  deco32_state,   tattass,   ROT0, "Data East Pinball",     "Tattoo Assassins (Asia prototype)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE )
trunk/src/mame/drivers/fcrash.c
r249095r249096
29582958
29592959GAME( 1992, sf2b,      sf2,      sf2b,      sf2mdt,   cps_state, sf2b,     ROT0,   "bootleg", "Street Fighter II: The World Warrior (bootleg)",  MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE ) //910204 - based on World version
29602960
2961GAME( 1992, sf2m9,     sf2ce,    sf2m1,     sf2,      cps_state, dinopic,  ROT0,   "bootleg", "Street Fighter II': Champion Edition (M9, bootleg)",  MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE ) // 920313 ETC
2961GAME( 1992, sf2m9,     sf2ce,    sf2m1,     sf2,      cps_state, sf2m1,    ROT0,   "bootleg", "Street Fighter II': Champion Edition (M9, bootleg)",  MACHINE_IMPERFECT_GRAPHICS | MACHINE_SUPPORTS_SAVE ) // 920313 ETC
29622962
29632963GAME( 1993, slampic,   slammast, slampic,   slammast, cps_state, dinopic,  ROT0,   "bootleg", "Saturday Night Slam Masters (bootleg with PIC16c57)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_NO_SOUND | MACHINE_SUPPORTS_SAVE ) // 930713 ETC
29642964
trunk/src/mame/drivers/galastrm.c
r249095r249096
252252   { 0, 8, 16, 24 },
253253   { 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7 },
254254   { 0*64, 1*64,  2*64,  3*64,  4*64,  5*64,  6*64,  7*64,
255      8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64 },
255     8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64 },
256256   64*16   /* every sprite takes 128 consecutive bytes */
257257};
258258
trunk/src/mame/drivers/groundfx.c
r249095r249096
245245   PORT_BIT( 0xff, 0x7f, IPT_AD_STICK_X ) PORT_SENSITIVITY(25) PORT_KEYDELTA(15) PORT_REVERSE PORT_PLAYER(1)
246246
247247   PORT_START("AN1")   /* IN 3, accel */
248   PORT_BIT( 0xff, 0xff, IPT_AD_STICK_Y ) PORT_SENSITIVITY(20) PORT_KEYDELTA(10) PORT_PLAYER(1)
248   PORT_BIT( 0xff, 0x00, IPT_AD_STICK_Y ) PORT_SENSITIVITY(20) PORT_KEYDELTA(10) PORT_PLAYER(1)
249249
250250   PORT_START("AN2")   /* IN 4, sound volume */
251251   PORT_BIT( 0xff, 0x00, IPT_AD_STICK_X ) PORT_SENSITIVITY(20) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(2)
trunk/src/mame/drivers/hng64.c
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner
33/* Hyper NeoGeo 64
44
55Driver by David Haywood, ElSemi, Andrew Gardner and Angelo Salese
6Rasterizing code provided in part by Andrew Zaferakis.
76
87
98Notes:
trunk/src/mame/drivers/lethalj.c
r249095r249096
681681
682682ROM_START( lethalj )
683683   ROM_REGION16_LE( 0x100000, "user1", 0 )     /* 34010 code */
684   ROM_LOAD16_BYTE( "vc8",  0x000000, 0x080000, CRC(8d568e1d) SHA1(e4dd3794789f9ccd7be8374978a3336f2b79136f) )
685   ROM_LOAD16_BYTE( "vc9",  0x000001, 0x080000, CRC(8f22add4) SHA1(e773d3ae9cf512810fc266e784d21ed115c8830c) )
684   ROM_LOAD16_BYTE( "lethal_vc8_2.3.vc8",  0x000000, 0x080000, CRC(8d568e1d) SHA1(e4dd3794789f9ccd7be8374978a3336f2b79136f) ) /* Labeled as LETHAL VC8 2.3, also found labeled as VC-8 */
685   ROM_LOAD16_BYTE( "lethal_vc9_2.3.vc9",  0x000001, 0x080000, CRC(8f22add4) SHA1(e773d3ae9cf512810fc266e784d21ed115c8830c) ) /* Labeled as LETHAL VC9 2.3, also found labeled as VC-9 */
686686
687687   ROM_REGION16_LE( 0x600000, "gfx1", 0 )          /* graphics data */
688   ROM_LOAD16_BYTE( "gr1",  0x000000, 0x100000, CRC(27f7b244) SHA1(628b29c066e217e1fe54553ea3ed98f86735e262) )
689   ROM_LOAD16_BYTE( "gr2",  0x000001, 0x100000, CRC(1f25d3ab) SHA1(bdb8a3c546cdee9a5630c47b9c5079a956e8a093) )
690   ROM_LOAD16_BYTE( "gr4",  0x200000, 0x100000, CRC(c5838b4c) SHA1(9ad03d0f316eb31fdf0ca6f65c02a27d3406d072) )
691   ROM_LOAD16_BYTE( "gr3",  0x200001, 0x100000, CRC(ba9fa057) SHA1(db6f11a8964870f04f94fef6f1b1a58168a942ad) )
692   ROM_LOAD16_BYTE( "gr6",  0x400000, 0x100000, CRC(51c99b85) SHA1(9a23bf21a73d2884b49c64a8f42c288534c79dc5) )
693   ROM_LOAD16_BYTE( "gr5",  0x400001, 0x100000, CRC(80dda9b5) SHA1(d8a79cad112bc7d9e4ba31a950e4807581f3bf46) )
688   ROM_LOAD16_BYTE( "gr1.gr1",             0x000000, 0x100000, CRC(27f7b244) SHA1(628b29c066e217e1fe54553ea3ed98f86735e262) ) /* These had non specific GRx labels, also found labeled as GR-x */
689   ROM_LOAD16_BYTE( "gr2.gr2",             0x000001, 0x100000, CRC(1f25d3ab) SHA1(bdb8a3c546cdee9a5630c47b9c5079a956e8a093) )
690   ROM_LOAD16_BYTE( "gr4.gr4",             0x200000, 0x100000, CRC(c5838b4c) SHA1(9ad03d0f316eb31fdf0ca6f65c02a27d3406d072) )
691   ROM_LOAD16_BYTE( "gr3.gr3",             0x200001, 0x100000, CRC(ba9fa057) SHA1(db6f11a8964870f04f94fef6f1b1a58168a942ad) )
692   ROM_LOAD16_BYTE( "lethal_gr6_2.3.gr6",  0x400000, 0x100000, CRC(51c99b85) SHA1(9a23bf21a73d2884b49c64a8f42c288534c79dc5) ) /* Labeled as LETHAL GR6 2.3, also found labeled as GR-6 */
693   ROM_LOAD16_BYTE( "lethal_gr5_2.3.gr5",  0x400001, 0x100000, CRC(80dda9b5) SHA1(d8a79cad112bc7d9e4ba31a950e4807581f3bf46) ) /* Labeled as LETHAL GR5 2.3, also found labeled as GR-5 */
694694
695695   ROM_REGION( 0x40000, "oki1", 0 )                /* sound data */
696696   ROM_LOAD( "sound1.u20", 0x00000, 0x40000, CRC(7d93ca66) SHA1(9e1dc0efa5d0f770c7e1f10de56fbf5620dea437) )
r249095r249096
10071007 *
10081008 *************************************/
10091009
1010GAME( 1996, lethalj,   0,        lethalj,  lethalj,   driver_device, 0,        ROT0,  "The Game Room", "Lethal Justice", 0 )
1010GAME( 1996, lethalj,   0,        lethalj,  lethalj,   driver_device, 0,        ROT0,  "The Game Room", "Lethal Justice (Version 2.3)", 0 )
10111011GAME( 1996, franticf,  0,        gameroom, franticf,  driver_device, 0,        ROT0,  "The Game Room", "Frantic Fred", MACHINE_NOT_WORKING )
10121012GAME( 1997, eggventr,  0,        gameroom, eggventr,  driver_device, 0,        ROT0,  "The Game Room", "Egg Venture (Release 10)", 0 )
10131013GAME( 1997, eggventr8, eggventr, gameroom, eggventr,  driver_device, 0,        ROT0,  "The Game Room", "Egg Venture (Release 8)", 0 )
trunk/src/mame/drivers/midxunit.c
r249095r249096
345345   ROM_LOAD( "a-17721.u955", 0x200, 0x117, CRC(033fe902) SHA1(6efb4e519ed3c9d49fff046a679762b506b3a75b) )
346346ROM_END
347347
348ROM_START( revxp5 )
349   ROM_REGION16_LE( 0x1000000, "dcs", ROMREGION_ERASEFF )  /* sound data */
350   ROM_LOAD16_BYTE( "revx_snd.2", 0x000000, 0x80000, CRC(4ed9e803) SHA1(ba50f1beb9f2a2cf5110897209b5e9a2951ff165) )
351   ROM_LOAD16_BYTE( "revx_snd.3", 0x200000, 0x80000, CRC(af8f253b) SHA1(25a0000cab177378070f7a6e3c7378fe87fad63e) )
352   ROM_LOAD16_BYTE( "revx_snd.4", 0x400000, 0x80000, CRC(3ccce59c) SHA1(e81a31d64c64e7b1d25f178c53da3d68453c203c) )
353   ROM_LOAD16_BYTE( "revx_snd.5", 0x600000, 0x80000, CRC(a0438006) SHA1(560d216d21cb8073dbee0fd20ebe589932a9144e) )
354   ROM_LOAD16_BYTE( "revx_snd.6", 0x800000, 0x80000, CRC(b7b34f60) SHA1(3b9682c6a00fa3bdb47e69d8e8ceccc244ee55b5) )
355   ROM_LOAD16_BYTE( "revx_snd.7", 0xa00000, 0x80000, CRC(6795fd88) SHA1(7c3790730a8b99b63112c851318b1c7e4989e5e0) )
356   ROM_LOAD16_BYTE( "revx_snd.8", 0xc00000, 0x80000, CRC(793a7eb5) SHA1(4b1f81b68f95cedf1b356ef362d1eb37acc74b16) )
357   ROM_LOAD16_BYTE( "revx_snd.9", 0xe00000, 0x80000, CRC(14ddbea1) SHA1(8dba9dc5529ea77c4312ea61f825bf9062ffc6c3) )
348358
359   ROM_REGION16_LE( 0x200000, "maincpu", 0 )   /* 34020 code */
360   ROM_LOAD32_BYTE( "revx_p5.51",  0x00000, 0x80000, CRC(f3877eee) SHA1(7a4fdce36edddd35308c107c992ce626a2c9eb8c) )
361   ROM_LOAD32_BYTE( "revx_p5.52",  0x00001, 0x80000, CRC(199a54d8) SHA1(45319437e11176d4926c00c95c372098203a32a3) )
362   ROM_LOAD32_BYTE( "revx_p5.53",  0x00002, 0x80000, CRC(fcfcf72a) SHA1(b471afb416e3d348b046b0b40f497d27b0afa470) )
363   ROM_LOAD32_BYTE( "revx_p5.54",  0x00003, 0x80000, CRC(fd684c31) SHA1(db3453792e4d9fc375297d030f0b3f9cc3cad925) )
349364
365   ROM_REGION( 0x2000, "pic", 0 )
366   ROM_LOAD( "revx_16c57.bin", 0x0000000, 0x2000, CRC(eb8a8649) SHA1(a1e1d0b7a5e9802e8f889eb7e719259656dc8133) )
367
368   ROM_REGION( 0x1000000, "gfxrom", 0 )
369   ROM_LOAD32_BYTE( "revx.120", 0x0000000, 0x80000, CRC(523af1f0) SHA1(a67c0fd757e860fc1c1236945952a295b4d5df5a) )
370   ROM_LOAD32_BYTE( "revx.121", 0x0000001, 0x80000, CRC(78201d93) SHA1(fb0b8f887eec433f7624f387d7fb6f633ea30d7c) )
371   ROM_LOAD32_BYTE( "revx.122", 0x0000002, 0x80000, CRC(2cf36144) SHA1(22ed0eefa2c7c836811fac5f717c3f38254eabc2) )
372   ROM_LOAD32_BYTE( "revx.123", 0x0000003, 0x80000, CRC(6912e1fb) SHA1(416f0de711d80e9182ede524c568c5095b1bec61) )
373
374   ROM_LOAD32_BYTE( "revx.110", 0x0200000, 0x80000, CRC(e3f7f0af) SHA1(5877d9f488b0f4362a9482007c3ff7f4589a036f) )
375   ROM_LOAD32_BYTE( "revx.111", 0x0200001, 0x80000, CRC(49fe1a69) SHA1(9ae54b461f0524c034fbcb6fcd3fd5ccb5d7265a) )
376   ROM_LOAD32_BYTE( "revx.112", 0x0200002, 0x80000, CRC(7e3ba175) SHA1(dd2fe90988b544f67dbe6151282fd80d49631388) )
377   ROM_LOAD32_BYTE( "revx.113", 0x0200003, 0x80000, CRC(c0817583) SHA1(2f866e5888e212b245984344950d0e1fb8957a73) )
378
379   ROM_LOAD32_BYTE( "revx.101", 0x0400000, 0x80000, CRC(5a08272a) SHA1(17da3c9d71114f5fdbf50281a942be3da3b6f564) )
380   ROM_LOAD32_BYTE( "revx.102", 0x0400001, 0x80000, CRC(11d567d2) SHA1(7ebe6fd39a0335e1fdda150d2dc86c3eaab17b2e) )
381   ROM_LOAD32_BYTE( "revx.103", 0x0400002, 0x80000, CRC(d338e63b) SHA1(0a038217542667b3a01ecbcad824ee18c084f293) )
382   ROM_LOAD32_BYTE( "revx.104", 0x0400003, 0x80000, CRC(f7b701ee) SHA1(0fc5886e5857326bee7272d5d482a878cbcea83c) )
383
384   ROM_LOAD32_BYTE( "revx.91",  0x0600000, 0x80000, CRC(52a63713) SHA1(dcc0ff3596bd5d273a8d4fd33b0b9b9d588d8354) )
385   ROM_LOAD32_BYTE( "revx.92",  0x0600001, 0x80000, CRC(fae3621b) SHA1(715d41ea789c0c724baa5bd90f6f0f06b9cb1c64) )
386   ROM_LOAD32_BYTE( "revx.93",  0x0600002, 0x80000, CRC(7065cf95) SHA1(6c5888da099e51c4b1c592721c5027c899cf52e3) )
387   ROM_LOAD32_BYTE( "revx.94",  0x0600003, 0x80000, CRC(600d5b98) SHA1(6aef98c91f87390c0759fe71a272a3ccadd71066) )
388
389   ROM_LOAD32_BYTE( "revx.81",  0x0800000, 0x80000, CRC(729eacb1) SHA1(d130162ae22b99c84abfbe014c4e23e20afb757f) )
390   ROM_LOAD32_BYTE( "revx.82",  0x0800001, 0x80000, CRC(19acb904) SHA1(516059b516bc5b1669c9eb085e0cdcdee520dff0) )
391   ROM_LOAD32_BYTE( "revx.83",  0x0800002, 0x80000, CRC(0e223456) SHA1(1eedbd667f4a214533d1c22ca5312ecf2d4a3ab4) )
392   ROM_LOAD32_BYTE( "revx.84",  0x0800003, 0x80000, CRC(d3de0192) SHA1(2d22c5bac07a7411f326691167c7c70eba4b371f) )
393
394   ROM_LOAD32_BYTE( "revx.71",  0x0a00000, 0x80000, CRC(2b29fddb) SHA1(57b71e5c18b56bf58216e690fdefa6d30d88d34a) )
395   ROM_LOAD32_BYTE( "revx.72",  0x0a00001, 0x80000, CRC(2680281b) SHA1(d1ae0701d20166a00d8733d9d12246c140a5fb96) )
396   ROM_LOAD32_BYTE( "revx.73",  0x0a00002, 0x80000, CRC(420bde4d) SHA1(0f010cdeddb59631a5420dddfc142c50c2a1e65a) )
397   ROM_LOAD32_BYTE( "revx.74",  0x0a00003, 0x80000, CRC(26627410) SHA1(a612121554549afff5c8e8c54774ca7b0220eda8) )
398
399   ROM_LOAD32_BYTE( "revx.63",  0x0c00000, 0x80000, CRC(3066e3f3) SHA1(25548923db111bd6c6cff44bfb63cb9eb2ef0b53) )
400   ROM_LOAD32_BYTE( "revx.64",  0x0c00001, 0x80000, CRC(c33f5309) SHA1(6bb333f563ea66c4c862ffd5fb91fb5e1b919fe8) )
401   ROM_LOAD32_BYTE( "revx.65",  0x0c00002, 0x80000, CRC(6eee3e71) SHA1(0ef22732e0e2bb5207559decd43f90d1e338ad7b) )
402   ROM_LOAD32_BYTE( "revx.66",  0x0c00003, 0x80000, CRC(b43d6fff) SHA1(87584e7aeea9d52a43023d40c359591ff6342e84) )
403   
404   ROM_LOAD32_BYTE( "revx_p5.51",  0xe00000, 0x80000, CRC(f3877eee) SHA1(7a4fdce36edddd35308c107c992ce626a2c9eb8c) )
405   ROM_LOAD32_BYTE( "revx_p5.52",  0xe00001, 0x80000, CRC(199a54d8) SHA1(45319437e11176d4926c00c95c372098203a32a3) )
406   ROM_LOAD32_BYTE( "revx_p5.53",  0xe00002, 0x80000, CRC(fcfcf72a) SHA1(b471afb416e3d348b046b0b40f497d27b0afa470) )
407   ROM_LOAD32_BYTE( "revx_p5.54",  0xe00003, 0x80000, CRC(fd684c31) SHA1(db3453792e4d9fc375297d030f0b3f9cc3cad925) )
408
409   ROM_REGION( 0x400, "plds", 0 )
410   ROM_LOAD( "a-17722.u1",   0x000, 0x117, CRC(054de7a3) SHA1(bb7abaec50ed704c03b44d5d54296898f7c80d38) )
411   ROM_LOAD( "a-17721.u955", 0x200, 0x117, CRC(033fe902) SHA1(6efb4e519ed3c9d49fff046a679762b506b3a75b) )
412ROM_END
413
414
415
350416/*************************************
351417 *
352418 *  Game drivers
353419 *
354420 *************************************/
355421
356GAME( 1994, revx,   0,         midxunit, revx, midxunit_state, revx, ROT0, "Midway",   "Revolution X (Rev. 1.0 6/16/94)", MACHINE_SUPPORTS_SAVE )
422GAME( 1994, revx,     0,    midxunit, revx, midxunit_state, revx, ROT0, "Midway",   "Revolution X (rev 1.0 6/16/94)", MACHINE_SUPPORTS_SAVE )
423GAME( 1994, revxp5,   revx, midxunit, revx, midxunit_state, revx, ROT0, "Midway",   "Revolution X (prototype, rev 5.0 5/23/94)", MACHINE_SUPPORTS_SAVE )
trunk/src/mame/drivers/model2.c
r249095r249096
59855985
59865986
59875987// Model 2 (TGPs, Model 1 sound board)
5988GAME( 1993, daytona,         0, model2o, daytona, driver_device, 0,       ROT0, "Sega",   "Daytona USA (Japan, Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5989GAME( 1993, daytonase, daytona, model2o, daytona, driver_device, 0,       ROT0, "Sega",   "Daytona USA Special Edition (Japan, Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5990GAME( 1993, daytona93, daytona, model2o, daytona, driver_device, 0,       ROT0, "Sega",   "Daytona USA Deluxe '93", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5991GAME( 1993, daytonas,  daytona, model2o, daytona, driver_device, 0,       ROT0, "Sega",   "Daytona USA (With Saturn Adverts)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5992GAME( 1993, daytonat,  daytona, model2o, daytona, driver_device, 0,       ROT0, "Sega",   "Daytona USA (Japan, Turbo hack, set 1)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5993GAME( 1993, daytonata, daytona, model2o, daytona, driver_device, 0,       ROT0, "Sega",   "Daytona USA (Japan, Turbo hack, set 2)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5994GAME( 1993, daytonam,  daytona, model2o, daytona, model2_state,  daytonam,ROT0, "Sega",   "Daytona USA (Japan, To The MAXX)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5995GAME( 1994, desert,          0, model2o, desert,  driver_device, 0,       ROT0, "Sega / Martin Marietta", "Desert Tank", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5996GAME( 1994, vcop,            0, model2o, vcop,    driver_device, 0,       ROT0, "Sega",   "Virtua Cop (Revision B)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5997GAME( 1994, vcopa,        vcop, model2o, vcop,    driver_device, 0,       ROT0, "Sega",   "Virtua Cop (Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5988GAME( 1993, daytona,         0, model2o, daytona, driver_device, 0,        ROT0, "Sega",   "Daytona USA (Japan, Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5989GAME( 1993, daytonase, daytona, model2o, daytona, driver_device, 0,        ROT0, "Sega",   "Daytona USA Special Edition (Japan, Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5990GAME( 1993, daytona93, daytona, model2o, daytona, driver_device, 0,        ROT0, "Sega",   "Daytona USA Deluxe '93", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5991GAME( 1993, daytonas,  daytona, model2o, daytona, driver_device, 0,        ROT0, "Sega",   "Daytona USA (With Saturn Adverts)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5992GAME( 1993, daytonat,  daytona, model2o, daytona, driver_device, 0,        ROT0, "Sega",   "Daytona USA (Japan, Turbo hack, set 1)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5993GAME( 1993, daytonata, daytona, model2o, daytona, driver_device, 0,        ROT0, "Sega",   "Daytona USA (Japan, Turbo hack, set 2)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5994GAME( 1993, daytonam,  daytona, model2o, daytona, model2_state,  daytonam, ROT0, "Sega",   "Daytona USA (Japan, To The MAXX)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5995GAME( 1994, desert,          0, model2o, desert,  driver_device, 0,        ROT0, "Sega / Martin Marietta", "Desert Tank", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5996GAME( 1994, vcop,            0, model2o, vcop,    driver_device, 0,        ROT0, "Sega",   "Virtua Cop (Revision B)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
5997GAME( 1994, vcopa,        vcop, model2o, vcop,    driver_device, 0,        ROT0, "Sega",   "Virtua Cop (Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
59985998
59995999// Model 2A-CRX (TGPs, SCSP sound board)
6000GAME( 1995, manxtt,          0, manxttdx     ,manxtt,  driver_device, 0, ROT0, "Sega", "Manx TT Superbike - DX (Revision D)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6001GAME( 1995, manxttc,         0, model2a,      manxtt,  driver_device, 0,       ROT0, "Sega",   "Manx TT Superbike - Twin (Revision C)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6002GAME( 1995, srallyc,         0, srallyc,      srallyc, model2_state,  srallyc, ROT0, "Sega",   "Sega Rally Championship - TWIN (Revision C)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6003GAME( 1995, srallycb,  srallyc, srallyc,      srallyc, model2_state,  srallyc, ROT0, "Sega",   "Sega Rally Championship - TWIN (Revision B)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6004GAME( 1995, srallyca,  srallyc, srallyc,      srallyc, model2_state,  srallyc, ROT0, "Sega",   "Sega Rally Championship - DX (Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6005GAME( 1995, vf2,             0, model2a,      model2,  driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2 (Version 2.1)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6006GAME( 1995, vf2b,          vf2, model2a,      model2,  driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2 (Revision B)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6007GAME( 1995, vf2a,          vf2, model2a,      model2,  driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2 (Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6008GAME( 1995, vf2o,          vf2, model2a,      model2,  driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6009GAME( 1995, vcop2,           0, model2a,      vcop2,   driver_device, 0,       ROT0, "Sega",   "Virtua Cop 2", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6010GAME( 1995, skytargt,        0, model2a,      skytargt,driver_device, 0,       ROT0, "Sega",   "Sky Target", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6011GAME( 1996, doaa,          doa, model2a_0229,  model2,  model2_state,  doa,     ROT0, "Sega",   "Dead or Alive (Model 2A, Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6012GAME( 1997, zeroguna,  zerogun, model2a_5881, model2,  model2_state,  zerogun, ROT0, "Psikyo", "Zero Gunner (Export, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6013GAME( 1997, zerogunaj, zerogun, model2a_5881, model2,  model2_state,  zerogun, ROT0, "Psikyo", "Zero Gunner (Japan, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6014GAME( 1997, motoraid,        0, model2a,      manxtt,  driver_device, 0,       ROT0, "Sega",   "Motor Raid - Twin", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6015GAME( 1998, dynamcop,        0, model2a_5881, model2,  model2_state,  genprot, ROT0, "Sega",   "Dynamite Cop (Export, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6016GAME( 1998, dyndeka2, dynamcop, model2a_5881, model2,  model2_state,  genprot, ROT0, "Sega",   "Dynamite Deka 2 (Japan, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6017GAME( 1998, pltkidsa,  pltkids, model2a_5881, model2,  model2_state,  pltkids, ROT0, "Psikyo", "Pilot Kids (Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6000GAME( 1995, manxtt,          0, manxttdx,     manxtt,   driver_device, 0,       ROT0, "Sega",   "Manx TT Superbike - DX (Revision D)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6001GAME( 1995, manxttc,         0, model2a,      manxtt,   driver_device, 0,       ROT0, "Sega",   "Manx TT Superbike - Twin (Revision C)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6002GAME( 1995, srallyc,         0, srallyc,      srallyc,  model2_state,  srallyc, ROT0, "Sega",   "Sega Rally Championship - TWIN (Revision C)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6003GAME( 1995, srallycb,  srallyc, srallyc,      srallyc,  model2_state,  srallyc, ROT0, "Sega",   "Sega Rally Championship - TWIN (Revision B)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6004GAME( 1995, srallyca,  srallyc, srallyc,      srallyc,  model2_state,  srallyc, ROT0, "Sega",   "Sega Rally Championship - DX (Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6005GAME( 1995, vf2,             0, model2a,      model2,   driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2 (Version 2.1)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6006GAME( 1995, vf2b,          vf2, model2a,      model2,   driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2 (Revision B)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6007GAME( 1995, vf2a,          vf2, model2a,      model2,   driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2 (Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6008GAME( 1995, vf2o,          vf2, model2a,      model2,   driver_device, 0,       ROT0, "Sega",   "Virtua Fighter 2", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6009GAME( 1995, vcop2,           0, model2a,      vcop2,    driver_device, 0,       ROT0, "Sega",   "Virtua Cop 2", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6010GAME( 1995, skytargt,        0, model2a,      skytargt, driver_device, 0,       ROT0, "Sega",   "Sky Target", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6011GAME( 1996, doaa,          doa, model2a_0229, model2,   model2_state,  doa,     ROT0, "Sega",   "Dead or Alive (Model 2A, Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6012GAME( 1997, zeroguna,  zerogun, model2a_5881, model2,   model2_state,  zerogun, ROT0, "Psikyo", "Zero Gunner (Export, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6013GAME( 1997, zerogunaj, zerogun, model2a_5881, model2,   model2_state,  zerogun, ROT0, "Psikyo", "Zero Gunner (Japan, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6014GAME( 1997, motoraid,        0, model2a,      manxtt,   driver_device, 0,       ROT0, "Sega",   "Motor Raid - Twin", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6015GAME( 1998, dynamcop,        0, model2a_5881, model2,   model2_state,  genprot, ROT0, "Sega",   "Dynamite Cop (Export, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6016GAME( 1998, dyndeka2, dynamcop, model2a_5881, model2,   model2_state,  genprot, ROT0, "Sega",   "Dynamite Deka 2 (Japan, Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
6017GAME( 1998, pltkidsa,  pltkids, model2a_5881, model2,   model2_state,  pltkids, ROT0, "Psikyo", "Pilot Kids (Model 2A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
60186018
60196019// Model 2B-CRX (SHARC, SCSP sound board)
60206020GAME( 1994, vstriker,        0, model2b,      model2,  driver_device, 0,       ROT0, "Sega",   "Virtua Striker (Revision A)", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_GRAPHICS )
trunk/src/mame/drivers/model3.c
r249095r249096
11// license:BSD-3-Clause
2// copyright-holders:Andrew Gardner, R. Belmont, Ville Linde
2// copyright-holders:R. Belmont, Ville Linde
33/*
44    Sega Model 3
55    PowerPC 603e + tilemaps + Real3D 1000 + 68000 + 2x SCSP
trunk/src/mame/drivers/namcofl.c
r249095r249096
610610   MCFG_VIDEO_START_OVERRIDE(namcofl_state,namcofl)
611611
612612   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
613   MCFG_C352_ADD("c352", 48384000/2, C352_DIVIDER_288)
613   MCFG_C352_ADD("c352", 48384000/2, 288)
614614   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
615615   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
616616   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
trunk/src/mame/drivers/namconb1.c
r249095r249096
11261126   MCFG_VIDEO_START_OVERRIDE(namconb1_state,namconb1)
11271127
11281128   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
1129   MCFG_C352_ADD("c352", MASTER_CLOCK/2, C352_DIVIDER_288)
1129   MCFG_C352_ADD("c352", MASTER_CLOCK/2, 288)
11301130   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
11311131   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
11321132   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
r249095r249096
11631163   MCFG_VIDEO_START_OVERRIDE(namconb1_state,namconb2)
11641164
11651165   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
1166   MCFG_C352_ADD("c352", MASTER_CLOCK/2, C352_DIVIDER_288)
1166   MCFG_C352_ADD("c352", MASTER_CLOCK/2, 288)
11671167   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
11681168   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
11691169   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
trunk/src/mame/drivers/namcond1.c
r249095r249096
307307   /* sound hardware */
308308   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
309309
310   MCFG_C352_ADD("c352", XTAL_49_152MHz/2, C352_DIVIDER_288)
310   MCFG_C352_ADD("c352", XTAL_49_152MHz/2, 288)
311311   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
312312   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
313313   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
trunk/src/mame/drivers/namcos11.c
r249095r249096
571571
572572   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
573573
574   MCFG_C352_ADD("c352", 20013200, C352_DIVIDER_228)
574   MCFG_C352_ADD("c352", 20013200, 228)
575575   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
576576   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
577577   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
trunk/src/mame/drivers/namcos12.c
r249095r249096
16221622   /* sound hardware */
16231623   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
16241624
1625   MCFG_C352_ADD("c352", 29168000, C352_DIVIDER_332)
1625   MCFG_C352_ADD("c352", 29168000, 332)
16261626   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
16271627   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
16281628   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
trunk/src/mame/drivers/namcos22.c
r249095r249096
37813781   /* sound hardware */
37823782   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
37833783
3784   MCFG_C352_ADD("c352", SS22_MASTER_CLOCK/2, C352_DIVIDER_288)
3784   MCFG_C352_ADD("c352", SS22_MASTER_CLOCK/2, 288)
37853785   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
37863786   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
37873787   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
r249095r249096
38303830   /* sound hardware */
38313831   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
38323832
3833   MCFG_C352_ADD("c352", SS22_MASTER_CLOCK/2, C352_DIVIDER_288)
3833   MCFG_C352_ADD("c352", SS22_MASTER_CLOCK/2, 288)
38343834   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
38353835   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
38363836   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
trunk/src/mame/drivers/namcos23.c
r249095r249096
12341234
12351235#include "emu.h"
12361236#include <float.h>
1237#include "video/polylgcy.h"
1237#include "video/poly.h"
12381238#include "cpu/mips/mips3.h"
12391239#include "cpu/h8/h83002.h"
12401240#include "cpu/h8/h83337.h"
r249095r249096
12471247#define JVSCLOCK    (XTAL_14_7456MHz)
12481248#define H8CLOCK     (16737350)      /* from 2061 */
12491249#define BUSCLOCK    (16737350*2)    /* 33MHz CPU bus clock / input */
1250#define C352CLOCK   (25992000)  /* measured at 25.992MHz from 2061 pin 9 (System 12 uses a divider of 332) */
1250#define C352CLOCK   (25992000)  /* measured at 25.992MHz from 2061 pin 9  */
1251#define C352DIV      (296)
12511252#define VSYNC1      (59.8824)
12521253#define VSYNC2      (59.915)
12531254#define HSYNC       (16666150)
r249095r249096
12631264
12641265enum { MODEL, FLUSH };
12651266
1267enum { RENDER_MAX_ENTRIES = 1000, POLY_MAX_ENTRIES = 10000 };
1268
12661269struct namcos23_render_entry
12671270{
12681271   int type;
r249095r249096
12861289   UINT32 (*texture_lookup)(running_machine &machine, const pen_t *pens, float x, float y);
12871290};
12881291
1292class namcos23_state;
1293
1294class namcos23_renderer : public poly_manager<float, namcos23_render_data, 4, POLY_MAX_ENTRIES>
1295{
1296public:
1297    namcos23_renderer(namcos23_state &state);
1298   
1299    void render_flush(bitmap_rgb32& bitmap);
1300    void render_scanline(INT32 scanline, const extent_t& extent, const namcos23_render_data& object, int threadid);
1301   
1302private:
1303    namcos23_state& m_state;
1304    bitmap_rgb32 m_bitmap;
1305};
1306
1307typedef namcos23_renderer::vertex_t poly_vertex;
1308
12891309struct namcos23_poly_entry
12901310{
12911311   namcos23_render_data rd;
r249095r249096
12951315   poly_vertex pv[16];
12961316};
12971317
1298enum { RENDER_MAX_ENTRIES = 1000, POLY_MAX_ENTRIES = 10000 };
12991318
1300
13011319struct c417_t
13021320{
13031321   UINT16 ram[0x10000];
r249095r249096
13431361
13441362struct render_t
13451363{
1346   legacy_poly_manager *polymgr;
1364    namcos23_renderer *polymgr;
13471365   int cur;
13481366   int poly_count;
13491367   int count[2];
r249095r249096
15391557   void render_apply_matrot(INT32 xi, INT32 yi, INT32 zi, const namcos23_render_entry *re, INT32 &x, INT32 &y, INT32 &z);
15401558   void render_project(poly_vertex &pv);
15411559   void render_one_model(const namcos23_render_entry *re);
1542   void render_flush(bitmap_rgb32 &bitmap);
15431560   void render_run(bitmap_rgb32 &bitmap);
15441561};
15451562
r249095r249096
15661583
15671584***************************************************************************/
15681585
1586namcos23_renderer::namcos23_renderer(namcos23_state &state)
1587    : poly_manager<float, namcos23_render_data, 4, POLY_MAX_ENTRIES>(state.machine()),
1588      m_state(state),
1589      m_bitmap(state.m_screen->width(), state.m_screen->height())
1590{}
1591
15691592// 3D hardware, to throw at least in part in video/namcos23.c
15701593
15711594inline INT32 namcos23_state::u32_to_s24(UINT32 v)
r249095r249096
18561879
18571880
18581881
1859static void render_scanline(void *dest, INT32 scanline, const poly_extent *extent, const void *extradata, int threadid)
1882void namcos23_renderer::render_scanline(INT32 scanline, const extent_t& extent, const namcos23_render_data& object, int threadid)
18601883{
1861   const namcos23_render_data *rd = (const namcos23_render_data *)extradata;
1884   const namcos23_render_data& rd = object;
18621885
1863   float w = extent->param[0].start;
1864   float u = extent->param[1].start;
1865   float v = extent->param[2].start;
1866   float l = extent->param[3].start;
1867   float dw = extent->param[0].dpdx;
1868   float du = extent->param[1].dpdx;
1869   float dv = extent->param[2].dpdx;
1870   float dl = extent->param[3].dpdx;
1871   bitmap_rgb32 *bitmap = (bitmap_rgb32 *)dest;
1872   UINT32 *img = &bitmap->pix32(scanline, extent->startx);
1886   float w = extent.param[0].start;
1887   float u = extent.param[1].start;
1888   float v = extent.param[2].start;
1889   float l = extent.param[3].start;
1890   float dw = extent.param[0].dpdx;
1891   float du = extent.param[1].dpdx;
1892   float dv = extent.param[2].dpdx;
1893   float dl = extent.param[3].dpdx;
1894   UINT32 *img = &m_bitmap.pix32(scanline, extent.startx);
18731895
1874   for(int x = extent->startx; x < extent->stopx; x++) {
1896   for(int x = extent.startx; x < extent.stopx; x++) {
18751897      float z = w ? 1/w : 0;
1876      UINT32 pcol = rd->texture_lookup(*rd->machine, rd->pens, u*z, v*z);
1898      UINT32 pcol = rd.texture_lookup(*rd.machine, rd.pens, u*z, v*z);
18771899      float ll = l*z;
18781900      *img = (light(pcol >> 16, ll) << 16) | (light(pcol >> 8, ll) << 8) | light(pcol, ll);
18791901
r249095r249096
20122034
20132035      namcos23_poly_entry *p = render.polys + render.poly_count;
20142036
2015      p->vertex_count = poly_zclip_if_less(ne, pv, p->pv, 4, 0.001f);
2037      p->vertex_count = render.polymgr->zclip_if_less(ne, pv, p->pv, 4, 0.001f);
20162038
20172039      if(p->vertex_count >= 3) {
20182040         for(int i=0; i<p->vertex_count; i++) {
r249095r249096
20462068   return p1->zkey < p2->zkey ? 1 : p1->zkey > p2->zkey ? -1 : 0;
20472069}
20482070
2049void namcos23_state::render_flush(bitmap_rgb32 &bitmap)
2071void namcos23_renderer::render_flush(bitmap_rgb32& bitmap)
20502072{
2051   render_t &render = m_render;
2073   render_t &render = m_state.m_render;
20522074
20532075   if(!render.poly_count)
20542076      return;
r249095r249096
20622084
20632085   for(int i=0; i<render.poly_count; i++) {
20642086      const namcos23_poly_entry *p = render.poly_order[i];
2065      namcos23_render_data *rd = (namcos23_render_data *)poly_get_extra_data(render.polymgr);
2066      *rd = p->rd;
2067      poly_render_triangle_fan(render.polymgr, &bitmap, scissor, render_scanline, 4, p->vertex_count, p->pv);
2087        namcos23_render_data& extra = render.polymgr->object_data_alloc();
2088        extra = p->rd;
2089       
2090        if (p->vertex_count == 3)
2091            render_triangle(scissor, render_delegate(FUNC(namcos23_renderer::render_scanline), this), 4, p->pv[0], p->pv[1], p->pv[2]);
2092        else if (p->vertex_count == 4)
2093            render_polygon<4>(scissor, render_delegate(FUNC(namcos23_renderer::render_scanline), this), 4, p->pv);
2094        else if (p->vertex_count == 5)
2095            render_polygon<5>(scissor, render_delegate(FUNC(namcos23_renderer::render_scanline), this), 4, p->pv);
20682096   }
20692097   render.poly_count = 0;
2098   
2099    copybitmap(bitmap, m_bitmap, 0, 0, 0, 0, scissor);
20702100}
20712101
20722102void namcos23_state::render_run(bitmap_rgb32 &bitmap)
r249095r249096
20812111         render_one_model(re);
20822112         break;
20832113      case FLUSH:
2084         render_flush(bitmap);
2114         render.polymgr->render_flush(bitmap);
20852115         break;
20862116      }
20872117      re++;
20882118   }
2089   render_flush(bitmap);
2090
2091   poly_wait(render.polymgr, "render_run");
2119   render.polymgr->render_flush(bitmap);
2120    render.polymgr->wait();
20922121}
20932122
20942123
r249095r249096
21602189   m_bgtilemap = &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(namcos23_state::TextTilemapGetInfo),this), TILEMAP_SCAN_ROWS, 16, 16, 64, 64);
21612190   m_bgtilemap->set_transparent_pen(0xf);
21622191   m_bgtilemap->set_scrolldx(860, 860);
2163   m_render.polymgr = poly_alloc(machine(), 10000, sizeof(namcos23_render_data), 0);
2192    m_render.polymgr = auto_alloc(machine(), namcos23_renderer(*this));
21642193}
21652194
21662195
r249095r249096
33203349   /* sound hardware */
33213350   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
33223351
3323   MCFG_C352_ADD("c352", C352CLOCK, C352_DIVIDER_332)
3352   MCFG_C352_ADD("c352", C352CLOCK, C352DIV)
33243353   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
33253354   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
33263355   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
r249095r249096
33893418   /* sound hardware */
33903419   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
33913420
3392   MCFG_C352_ADD("c352", C352CLOCK, C352_DIVIDER_332)
3421   MCFG_C352_ADD("c352", C352CLOCK, C352DIV)
33933422   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
33943423   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
33953424   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
r249095r249096
34693498   /* sound hardware */
34703499   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
34713500
3472   MCFG_C352_ADD("c352", C352CLOCK, C352_DIVIDER_332)
3501   MCFG_C352_ADD("c352", C352CLOCK, C352DIV)
34733502   MCFG_SOUND_ROUTE(0, "rspeaker", 1.00)
34743503   MCFG_SOUND_ROUTE(1, "lspeaker", 1.00)
34753504   MCFG_SOUND_ROUTE(2, "rspeaker", 1.00)
trunk/src/mame/drivers/quantum.c
r249095r249096
1212    Known bugs:
1313        * none at this time
1414
15NOTE: The Atari 136002-125 PROM in the sets below wasn't dumped from an actual
16     Quantum PCB. It is assumed all Atari 136002-125 PROMs are the same data.
17
1518****************************************************************************
1619
1720    Memory map
r249095r249096
333336   ROM_LOAD16_BYTE( "136016.110",   0x010001, 0x002000, CRC(acb50363) SHA1(9efa9ca88efdd2d5e212bd537903892b67b4fe53) )
334337   /* AVG PROM */
335338   ROM_REGION( 0x100, "user1", 0 )
336   ROM_LOAD( "136002-125.6h",   0x0000, 0x0100, BAD_DUMP CRC(5903af03) SHA1(24bc0366f394ad0ec486919212e38be0f08d0239) )
339   ROM_LOAD( "136002-125.6h",   0x0000, 0x0100, CRC(5903af03) SHA1(24bc0366f394ad0ec486919212e38be0f08d0239) )
340
341   ROM_REGION( 0x200, "plds", 0 )
342   ROM_LOAD( "cf2038n.1b",   0x0000, 0x00eb, CRC(b372fa4f) SHA1(a60b51849e9f691b412ae4c4afc834ff93d8a30f) ) /* Original chip is a 82S153, schematics refer to this chip as 137290-001 */
337343ROM_END
338344
339345
r249095r249096
351357   ROM_LOAD16_BYTE( "136016.110",   0x010001, 0x002000, CRC(acb50363) SHA1(9efa9ca88efdd2d5e212bd537903892b67b4fe53) )
352358   /* AVG PROM */
353359   ROM_REGION( 0x100, "user1", 0 )
354   ROM_LOAD( "136002-125.6h",   0x0000, 0x0100, BAD_DUMP CRC(5903af03) SHA1(24bc0366f394ad0ec486919212e38be0f08d0239) )
360   ROM_LOAD( "136002-125.6h",   0x0000, 0x0100, CRC(5903af03) SHA1(24bc0366f394ad0ec486919212e38be0f08d0239) )
361
362   ROM_REGION( 0x200, "plds", 0 )
363   ROM_LOAD( "cf2038n.1b",   0x0000, 0x00eb, CRC(b372fa4f) SHA1(a60b51849e9f691b412ae4c4afc834ff93d8a30f) ) /* Original chip is a 82S153, schematics refer to this chip as 137290-001 */
355364ROM_END
356365
357366
r249095r249096
369378   ROM_LOAD16_BYTE( "quantump.3l",  0x010001, 0x002000, CRC(e19de844) SHA1(cb4f9d80807b26d6b95405b2d830799984667f54) )
370379   /* AVG PROM */
371380   ROM_REGION( 0x100, "user1", 0 )
372   ROM_LOAD( "136002-125.6h",   0x0000, 0x0100, BAD_DUMP CRC(5903af03) SHA1(24bc0366f394ad0ec486919212e38be0f08d0239) )
381   ROM_LOAD( "136002-125.6h",   0x0000, 0x0100, CRC(5903af03) SHA1(24bc0366f394ad0ec486919212e38be0f08d0239) )
382
383   ROM_REGION( 0x200, "plds", 0 )
384   ROM_LOAD( "cf2038n.1b",   0x0000, 0x00eb, CRC(b372fa4f) SHA1(a60b51849e9f691b412ae4c4afc834ff93d8a30f) ) /* Original chip is a 82S153, schematics refer to this chip as 137290-001 */
373385ROM_END
374386
375387
trunk/src/mame/drivers/yunsun16.c
r249095r249096
928928
929929ROM_END
930930
931ROM_START( shockingko )
931932
933   ROM_REGION( 0x080000, "maincpu", 0 )        /* 68000 Code */
934   ROM_LOAD16_BYTE( "shoc_kor.u33", 0x000000, 0x040000, CRC(646303ec) SHA1(d01264f8495fdea882a9d75129665a67a9acfc42) )
935   ROM_LOAD16_BYTE( "shoc_kor.u32", 0x000001, 0x040000, CRC(6d9ac2f2) SHA1(2374cc053233940d5da610ec95539b43dfbeef3b) )
936
937   ROM_REGION( 0x200000*8, "gfx1", ROMREGION_ERASEFF ) /* 16x16x8 */
938   ROMX_LOAD( "shoc_kor.u67", 0x000000, 0x080000, CRC(e30fb2c4) SHA1(0d33a1593d7ebcd5da6971a04c3300c0b4eef219) , ROM_GROUPWORD | ROM_SKIP(6))
939   ROMX_LOAD( "shoc_kor.u68", 0x000002, 0x080000, CRC(7d702538) SHA1(ae4c8ca6f172e204589f2f70ca114f7c38e7cabd) , ROM_GROUPWORD | ROM_SKIP(6))
940   ROMX_LOAD( "shoc_kor.u69", 0x000004, 0x080000, CRC(97447fec) SHA1(e52184f96b2337ccbef130ada21a959c8bc1d73b) , ROM_GROUPWORD | ROM_SKIP(6))
941   ROMX_LOAD( "shoc_kor.u70", 0x000006, 0x080000, CRC(1b1f7895) SHA1(939c386dbef82e4833b7038e7c603d2ec67fa23e) , ROM_GROUPWORD | ROM_SKIP(6))
942
943   ROM_REGION( 0x100000, "gfx2", 0 )   /* 16x16x4 */
944   ROM_LOAD( "shoc_kor.u20", 0x000000, 0x040000, CRC(9f729220) SHA1(3206c87c7aebd8912d3486225ccae0a6e3b2061e) )
945   ROM_LOAD( "shoc_kor.u21", 0x040000, 0x040000, CRC(cde84679) SHA1(261a6570449bce22458c49edee427dda6dc504b7) )
946   ROM_LOAD( "shoc_kor.u22", 0x080000, 0x040000, CRC(61fe98ab) SHA1(745fe3b9d513b8e10c405d9ba2e055de1a261e33) )
947   ROM_LOAD( "shoc_kor.u23", 0x0c0000, 0x040000, CRC(50c29191) SHA1(bb2c22f2f452ca0940e98df6efc754c7522696bd) )
948
949   ROM_REGION( 0x080000, "oki", 0 )    /* Samples */
950   ROM_LOAD( "yunsun16.131", 0x000000, 0x080000, CRC(d0a1bb8c) SHA1(10f33521bd6031ed73ee5c7be1382165925aa8f8) )
951
952ROM_END
953
954
932955/***************************************************************************
933956
934957                       Bomb Kick  -  Yun Sung, 1998
r249095r249096
9911014
9921015***************************************************************************/
9931016
994GAME( 199?, magicbub,  0,        magicbub, magicbub, yunsun16_state, magicbub, ROT0,   "Yun Sung", "Magic Bubble",                              MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
995GAME( 199?, magicbuba, magicbub, magicbub, magicbua, yunsun16_state, magicbub, ROT0,   "Yun Sung", "Magic Bubble (Adult version, YS-1302 PCB)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
996GAME( 199?, magicbubb, magicbub, shocking, magicbua, driver_device,  0,        ROT0,   "Yun Sung", "Magic Bubble (Adult version, YS-0211 PCB)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
997GAME( 1996, paprazzi,  0,        shocking, paprazzi, driver_device,  0,        ROT270, "Yun Sung", "Paparazzi",                                 MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
998GAME( 1997, shocking,  0,        shocking, shocking, driver_device,  0,        ROT0,   "Yun Sung", "Shocking",                                  MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
999GAME( 1997, shockingk, shocking, shocking, shocking, driver_device,  0,        ROT0,   "Yun Sung", "Shocking (Korea)",                          MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1000GAME( 1998, bombkick,  0,        shocking, bombkick, driver_device,  0,        ROT0,   "Yun Sung", "Bomb Kick (set 1)",                         MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1001GAME( 1998, bombkicka, bombkick, shocking, bombkick, driver_device,  0,        ROT0,   "Yun Sung", "Bomb Kick (set 2)",                         MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1017GAME( 199?, magicbub,   0,        magicbub, magicbub, yunsun16_state, magicbub, ROT0,   "Yun Sung", "Magic Bubble",                              MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1018GAME( 199?, magicbuba,  magicbub, magicbub, magicbua, yunsun16_state, magicbub, ROT0,   "Yun Sung", "Magic Bubble (Adult version, YS-1302 PCB)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1019GAME( 199?, magicbubb,  magicbub, shocking, magicbua, driver_device,  0,        ROT0,   "Yun Sung", "Magic Bubble (Adult version, YS-0211 PCB)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1020GAME( 1996, paprazzi,   0,        shocking, paprazzi, driver_device,  0,        ROT270, "Yun Sung", "Paparazzi",                                 MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1021GAME( 1997, shocking,   0,        shocking, shocking, driver_device,  0,        ROT0,   "Yun Sung", "Shocking",                                  MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1022GAME( 1997, shockingk,  shocking, shocking, shocking, driver_device,  0,        ROT0,   "Yun Sung", "Shocking (Korea, set 1)",                   MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1023GAME( 1997, shockingko, shocking, shocking, shocking, driver_device,  0,        ROT0,   "Yun Sung", "Shocking (Korea, set 2)",                   MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1024GAME( 1998, bombkick,   0,        shocking, bombkick, driver_device,  0,        ROT0,   "Yun Sung", "Bomb Kick (set 1)",                         MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
1025GAME( 1998, bombkicka,  bombkick, shocking, bombkick, driver_device,  0,        ROT0,   "Yun Sung", "Bomb Kick (set 2)",                         MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
trunk/src/mame/drivers/zaccaria.c
r249095r249096
506506   MCFG_CPU_ADD("maincpu", Z80,XTAL_18_432MHz/6)   /* verified on pcb */
507507   MCFG_CPU_PROGRAM_MAP(main_map)
508508   MCFG_CPU_VBLANK_INT_DRIVER("screen", zaccaria_state,  vblank_irq)
509   MCFG_QUANTUM_TIME(attotime::from_hz(1000000))
509//   MCFG_QUANTUM_TIME(attotime::from_hz(1000000))
510510
511511   MCFG_CPU_ADD("audiocpu", M6802,XTAL_3_579545MHz) /* verified on pcb */
512512   MCFG_CPU_PROGRAM_MAP(sound_map_1)
513513   MCFG_CPU_PERIODIC_INT_DRIVER(zaccaria_state, cb1_toggle, (double)XTAL_3_579545MHz/4096)
514   MCFG_QUANTUM_TIME(attotime::from_hz(1000000))
514//   MCFG_QUANTUM_TIME(attotime::from_hz(1000000))
515515
516516   MCFG_CPU_ADD("audio2", M6802,XTAL_3_579545MHz) /* verified on pcb */
517517   MCFG_CPU_PROGRAM_MAP(sound_map_2)
518   MCFG_QUANTUM_TIME(attotime::from_hz(1000000))
518//   MCFG_QUANTUM_TIME(attotime::from_hz(1000000))
519519
520520   MCFG_DEVICE_ADD("ppi8255", I8255A, 0)
521521   MCFG_I8255_IN_PORTA_CB(IOPORT("P1"))
trunk/src/mame/includes/chihiro.h
r249095r249096
185185      memset(pfifo, 0, sizeof(pfifo));
186186      memset(pcrtc, 0, sizeof(pcrtc));
187187      memset(pmc, 0, sizeof(pmc));
188      memset(pgraph, 0, sizeof(pgraph));
188189      memset(ramin, 0, sizeof(ramin));
189190      computedilated();
190191      objectdata = &(object_data_alloc());
r249095r249096
194195      enabled_vertex_attributes = 0;
195196      indexesleft_count = 0;
196197      vertex_pipeline = 4;
198      color_mask = 0xffffffff;
197199      alpha_test_enabled = false;
198200      alpha_reference = 0;
199201      alpha_func = nv2a_renderer::ALWAYS;
r249095r249096
238240   }
239241   DECLARE_READ32_MEMBER(geforce_r);
240242   DECLARE_WRITE32_MEMBER(geforce_w);
241   bool vblank_callback(screen_device &screen, bool state);
243   void vblank_callback(screen_device &screen, bool state);
242244   UINT32 screen_update_callback(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);
245   bool update_interrupts();
246   void set_interrupt_device(pic8259_device *device);
243247
244248   void render_texture_simple(INT32 scanline, const extent_t &extent, const nvidia_object_data &extradata, int threadid);
245249   void render_color(INT32 scanline, const extent_t &extent, const nvidia_object_data &extradata, int threadid);
r249095r249096
303307   UINT32 pfifo[0x2000 / 4];
304308   UINT32 pcrtc[0x1000 / 4];
305309   UINT32 pmc[0x1000 / 4];
310   UINT32 pgraph[0x2000 / 4];
306311   UINT32 ramin[0x100000 / 4];
307312   UINT32 dma_offset[2];
308313   UINT32 dma_size[2];
309314   UINT8 *basemempointer;
315   pic8259_device *interruptdevice;
310316   rectangle limits_rendertarget;
311317   UINT32 pitch_rendertarget;
312318   UINT32 pitch_depthbuffer;
r249095r249096
441447      int used;
442448      osd_lock *lock;
443449   } combiner;
450   UINT32 color_mask;
444451   bool alpha_test_enabled;
445452   int alpha_func;
446453   int alpha_reference;
trunk/src/mame/includes/galastrm.h
r249095r249096
11// license:???
22// copyright-holders:Hau
33#include "machine/eepromser.h"
4#include "video/polylgcy.h"
4
5#include "video/poly.h"
56#include "video/tc0100scn.h"
67#include "video/tc0480scp.h"
78
9
10class galastrm_state;
11
12struct gs_poly_data
13{
14   bitmap_ind16* texbase;
15};
16
17class galastrm_renderer : public poly_manager<float, gs_poly_data, 2, 10000>
18{
19public:
20   galastrm_renderer(galastrm_state &state);
21
22    void tc0610_draw_scanline(INT32 scanline, const extent_t& extent, const gs_poly_data& object, int threadid);
23    void tc0610_rotate_draw(bitmap_ind16 &srcbitmap, const rectangle &clip);
24   
25    bitmap_ind16 &screenbits() { return m_screenbits; }
26   
27private:
28   galastrm_state& m_state;
29    bitmap_ind16 m_screenbits;
30};
31
32
833struct gs_tempsprite
934{
1035   int gfx;
r249095r249096
5681   struct gs_tempsprite *m_spritelist;
5782   struct gs_tempsprite *m_sprite_ptr_pre;
5883   bitmap_ind16 m_tmpbitmaps;
59   bitmap_ind16 m_polybitmap;
60   legacy_poly_manager *m_poly;
84    galastrm_renderer *m_poly;
85   
6186   int m_rsxb;
6287   int m_rsyb;
6388   int m_rsxoffs;
r249095r249096
7499   virtual void video_start();
75100   UINT32 screen_update_galastrm(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
76101   INTERRUPT_GEN_MEMBER(galastrm_interrupt);
77   void galastrm_exit();
78102   void draw_sprites_pre(int x_offs, int y_offs);
79103   void draw_sprites(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect, const int *primasks, int priority);
80104   void tc0610_rotate_draw(bitmap_ind16 &bitmap, bitmap_ind16 &srcbitmap, const rectangle &clip);
trunk/src/mame/includes/hng64.h
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner
33#include "machine/msm6242.h"
44#include "cpu/mips/mips3.h"
55#include "cpu/nec/v53.h"
trunk/src/mame/includes/model2.h
r249095r249096
11// license:BSD-3-Clause
22// copyright-holders:R. Belmont, Olivier Galibert, ElSemi, Angelo Salese
3#include "video/polylgcy.h"
3#include "video/poly.h"
44#include "audio/dsbz80.h"
55#include "audio/segam1audio.h"
66#include "machine/eepromser.h"
r249095r249096
99#include "machine/315-5881_crypt.h"
1010#include "machine/315-5838_317-0229_comp.h"
1111
12class model2_renderer;
1213struct raster_state;
1314struct geo_state;
1415
15
1616class model2_state : public driver_device
1717{
1818public:
r249095r249096
107107   int m_jnet_time_out;
108108   UINT32 m_geo_read_start_address;
109109   UINT32 m_geo_write_start_address;
110   legacy_poly_manager *m_poly;
110   model2_renderer *m_poly;
111111   raster_state *m_raster;
112112   geo_state *m_geo;
113113   bitmap_rgb32 m_sys24_bitmap;
r249095r249096
219219   TIMER_DEVICE_CALLBACK_MEMBER(model2_timer_cb);
220220   TIMER_DEVICE_CALLBACK_MEMBER(model2_interrupt);
221221   TIMER_DEVICE_CALLBACK_MEMBER(model2c_interrupt);
222   void model2_exit();
223222   DECLARE_WRITE8_MEMBER(scsp_irq);
224223   DECLARE_READ_LINE_MEMBER(copro_tgp_fifoin_pop_ok);
225224   DECLARE_READ32_MEMBER(copro_tgp_fifoin_pop);
r249095r249096
237236   void model2_3d_frame_end( bitmap_rgb32 &bitmap, const rectangle &cliprect );
238237};
239238
239
240/*****************************
241 *
242 * Modern polygon renderer
243 *
244 *****************************/
245
246struct m2_poly_extra_data
247{
248   model2_state *  state;
249   UINT32      lumabase;
250   UINT32      colorbase;
251   UINT32 *    texsheet;
252   UINT32      texwidth;
253   UINT32      texheight;
254   UINT32      texx, texy;
255   UINT8       texmirrorx;
256   UINT8       texmirrory;
257};
258
259
260INLINE UINT16 get_texel( UINT32 base_x, UINT32 base_y, int x, int y, UINT32 *sheet )
261{
262   UINT32  baseoffs = ((base_y/2)*512)+(base_x/2);
263   UINT32  texeloffs = ((y/2)*512)+(x/2);
264   UINT32  offset = baseoffs + texeloffs;
265   UINT32  texel = sheet[offset>>1];
266
267   if ( offset & 1 )
268      texel >>= 16;
269
270   if ( (y & 1) == 0 )
271      texel >>= 8;
272
273   if ( (x & 1) == 0 )
274      texel >>= 4;
275
276   return (texel & 0x0f);
277}
278
279struct triangle;
280
281class model2_renderer : public poly_manager<float, m2_poly_extra_data, 4, 4000>
282{
283   
284public:
285    typedef void (model2_renderer::*scanline_render_func)(INT32 scanline, const extent_t& extent, const m2_poly_extra_data& object, int threadid);
286   
287public:
288    model2_renderer(model2_state& state)
289        : poly_manager<float, m2_poly_extra_data, 4, 4000>(state.machine())
290        , m_state(state)
291        , m_destmap(state.m_screen->width(), state.m_screen->height())
292    {
293        m_renderfuncs[0] = &model2_renderer::model2_3d_render_0;
294        m_renderfuncs[1] = &model2_renderer::model2_3d_render_1;
295        m_renderfuncs[2] = &model2_renderer::model2_3d_render_2;
296        m_renderfuncs[3] = &model2_renderer::model2_3d_render_3;
297        m_renderfuncs[4] = &model2_renderer::model2_3d_render_4;
298        m_renderfuncs[5] = &model2_renderer::model2_3d_render_5;
299        m_renderfuncs[6] = &model2_renderer::model2_3d_render_6;
300        m_renderfuncs[7] = &model2_renderer::model2_3d_render_7;
301    }
302   
303    bitmap_rgb32& destmap() { return m_destmap; }
304   
305    void model2_3d_render(triangle *tri, const rectangle &cliprect);
306   
307    /* checker = 0, textured = 0, transparent = 0 */
308    #define MODEL2_FUNC 0
309    #define MODEL2_FUNC_NAME    model2_3d_render_0
310    #include "video/model2rd.inc"
311    #undef MODEL2_FUNC
312    #undef MODEL2_FUNC_NAME
313   
314    /* checker = 0, textured = 0, translucent = 1 */
315    #define MODEL2_FUNC 1
316    #define MODEL2_FUNC_NAME    model2_3d_render_1
317    #include "video/model2rd.inc"
318    #undef MODEL2_FUNC
319    #undef MODEL2_FUNC_NAME
320   
321    /* checker = 0, textured = 1, translucent = 0 */
322    #define MODEL2_FUNC 2
323    #define MODEL2_FUNC_NAME    model2_3d_render_2
324    #include "video/model2rd.inc"
325    #undef MODEL2_FUNC
326    #undef MODEL2_FUNC_NAME
327   
328    /* checker = 0, textured = 1, translucent = 1 */
329    #define MODEL2_FUNC 3
330    #define MODEL2_FUNC_NAME    model2_3d_render_3
331    #include "video/model2rd.inc"
332    #undef MODEL2_FUNC
333    #undef MODEL2_FUNC_NAME
334   
335    /* checker = 1, textured = 0, translucent = 0 */
336    #define MODEL2_FUNC 4
337    #define MODEL2_FUNC_NAME    model2_3d_render_4
338    #include "video/model2rd.inc"
339    #undef MODEL2_FUNC
340    #undef MODEL2_FUNC_NAME
341   
342    /* checker = 1, textured = 0, translucent = 1 */
343    #define MODEL2_FUNC 5
344    #define MODEL2_FUNC_NAME    model2_3d_render_5
345    #include "video/model2rd.inc"
346    #undef MODEL2_FUNC
347    #undef MODEL2_FUNC_NAME
348   
349    /* checker = 1, textured = 1, translucent = 0 */
350    #define MODEL2_FUNC 6
351    #define MODEL2_FUNC_NAME    model2_3d_render_6
352    #include "video/model2rd.inc"
353    #undef MODEL2_FUNC
354    #undef MODEL2_FUNC_NAME
355   
356    /* checker = 1, textured = 1, translucent = 1 */
357    #define MODEL2_FUNC 7
358    #define MODEL2_FUNC_NAME    model2_3d_render_7
359    #include "video/model2rd.inc"
360    #undef MODEL2_FUNC
361    #undef MODEL2_FUNC_NAME
362
363    scanline_render_func m_renderfuncs[8];
364   
365private:
366    model2_state& m_state;
367    bitmap_rgb32 m_destmap;
368};
369
370typedef model2_renderer::vertex_t poly_vertex;
371
372
373/*******************************************
374 *
375 *  Basic Data Types
376 *
377 *******************************************/
378
379struct plane
380{
381   poly_vertex normal;
382   float       distance;
383};
384
385struct texture_parameter
386{
387   float   diffuse;
388   float   ambient;
389   UINT32  specular_control;
390   float   specular_scale;
391};
392
393struct triangle
394{
395   void *              next;
396   poly_vertex         v[3];
397   UINT16              z;
398   UINT16              texheader[4];
399   UINT8               luma;
400   INT16               viewport[4];
401   INT16               center[2];
402};
403
404struct quad_m2
405{
406   poly_vertex         v[4];
407   UINT16              z;
408   UINT16              texheader[4];
409   UINT8               luma;
410};
411
412
413
240414/*----------- defined in video/model2.c -----------*/
241415void model2_3d_set_zclip( running_machine &machine, UINT8 clip );
trunk/src/mame/includes/model3.h
r249095r249096
11// license:BSD-3-Clause
2// copyright-holders:Andrew Gardner, R. Belmont, Ville Linde
2// copyright-holders:R. Belmont, Ville Linde
33#include "video/poly.h"
44#include "bus/scsi/scsi.h"
55#include "machine/53c810.h"
trunk/src/mame/machine/hng64_net.c
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner
33/* HNG64 Communication / Network CPU */
44
55// this is driven by a KL5C80A12CFP which is basically a super-charged Z80
trunk/src/mame/machine/model3.c
r249095r249096
11// license:BSD-3-Clause
2// copyright-holders:Andrew Gardner, R. Belmont, Ville Linde
2// copyright-holders:R. Belmont, Ville Linde
33/*
44
55  machine/model3.c: functions emulating various aspects of the Model 3 hardware
trunk/src/mame/machine/namco62.c
r249095r249096
11// license:BSD-3-Clause
2// copyright-holders:Philip Bennett, Andrew Gardner
2// copyright-holders:Philip Bennett
33/***************************************************************************
44
55    Namco 62XX
trunk/src/mame/machine/namco62.h
r249095r249096
11// license:BSD-3-Clause
2// copyright-holders:Philip Bennett, Andrew Gardner
2// copyright-holders:Philip Bennett
33#ifndef NAMCO62_H
44#define NAMCO62_H
55
trunk/src/mame/machine/xbox.c
r249095r249096
465465
466466void xbox_base_state::vblank_callback(screen_device &screen, bool state)
467467{
468   if (nvidia_nv2a->vblank_callback(screen, state))
469      xbox_base_devs.pic8259_1->ir3_w(1); // IRQ 3
470   else
471      xbox_base_devs.pic8259_1->ir3_w(0); // IRQ 3
468   nvidia_nv2a->vblank_callback(screen, state);
472469}
473470
474471UINT32 xbox_base_state::screen_update_callback(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
r249095r249096
14601457   if (machine().debug_flags & DEBUG_FLAG_ENABLED)
14611458      debug_console_register_command(machine(), "xbox", CMDFLAG_NONE, 0, 1, 4, xbox_debug_commands);
14621459   memset(&ohcist, 0, sizeof(ohcist));
1460   // PIC challenge handshake data
1461   pic16lc_buffer[0x1c] = 0x0c;
1462   pic16lc_buffer[0x1d] = 0x0d;
1463   pic16lc_buffer[0x1e] = 0x0e;
1464   pic16lc_buffer[0x1f] = 0x0f;
14631465#ifdef USB_ENABLED
14641466   ohcist.hc_regs[HcRevision] = 0x10;
14651467   ohcist.hc_regs[HcFmInterval] = 0x2edf;
r249095r249096
14831485   save_item(NAME(smbusst.rw));
14841486   save_item(NAME(smbusst.words));
14851487   save_item(NAME(pic16lc_buffer));
1488   nvidia_nv2a->set_interrupt_device(xbox_base_devs.pic8259_1);
14861489   nvidia_nv2a->start(&m_maincpu->space());
14871490   nvidia_nv2a->savestate_items();
14881491}
trunk/src/mame/mess.lst
r249095r249096
13411341canonv20f
13421342canonv20g
13431343canonv20s
1344canons80
13441345mx10
13451346mx101
13461347mx15
r249095r249096
26522653vax785
26532654ms0515
26542655ie15
2656dvk_kcgd
26552657dvk_ksm
26562658dvk_ksm01
26572659asmapro
trunk/src/mame/video/chihiro.c
r249095r249096
33#include "emu.h"
44#include "video/poly.h"
55#include "bitmap.h"
6#include "machine/pic8259.h"
67#include "includes/chihiro.h"
78
89//#define LOG_NV2A
r249095r249096
945946UINT32 nv2a_renderer::geforce_object_offset(UINT32 handle)
946947{
947948   UINT32 h = ((((handle >> 11) ^ handle) >> 11) ^ handle) & 0x7ff;
948   UINT32 o = (pfifo[0x210 / 4] & 0x1f) << 8; // or 12 ?
949   UINT32 o = (pfifo[0x210 / 4] & 0x1ff) << 8; // 0x1ff is not certain
949950   UINT32 e = o + h * 8; // at 0xfd000000+0x00700000
950951   UINT32 w;
951952
952   if (ramin[e / 4] != handle)
953      e = 0;
953   if (ramin[e / 4] != handle) {
954      // this should never happen
955      for (UINT32 aa = o / 4; aa < (sizeof(ramin) / 4); aa = aa + 2) {
956         if (ramin[aa] == handle) {
957            e = aa * 4;
958         }
959      }
960   }
954961   w = ramin[e / 4 + 1];
955   return (w & 0xffff) * 0x10;
962   return (w & 0xffff) * 0x10; // 0xffff is not certain
956963}
957964
958965void nv2a_renderer::geforce_read_dma_object(UINT32 handle, UINT32 &offset, UINT32 &size)
r249095r249096
12461253      addr = rendertarget + (dilated0[dilate_rendertarget][x] + dilated1[dilate_rendertarget][y]);
12471254   else // type_rendertarget == LINEAR*/
12481255      addr = rendertarget + (pitch_rendertarget / 4)*y + x;
1249   fbcolor = *addr;
1256   fbcolor = 0;
1257   if (color_mask != 0)
1258      fbcolor = *addr;
12501259   daddr=depthbuffer + (pitch_depthbuffer / 4)*y + x;
12511260   deptsten = *daddr;
12521261   c[3] = color >> 24;
r249095r249096
17721781            break;
17731782      }
17741783   }
1775   fbcolor = (c[3] << 24) | (c[2] << 16) | (c[1] << 8) | c[0];
1776   *addr = fbcolor;
1784   if (color_mask != 0) {
1785      UINT32 fbcolor_tmp;
1786
1787      fbcolor_tmp = (c[3] << 24) | (c[2] << 16) | (c[1] << 8) | c[0];
1788      *addr = (fbcolor & ~color_mask) | (fbcolor_tmp & color_mask);
1789   }
17771790   if (depth_write_enabled)
17781791      dep = depth;
17791792   deptsten = (dep << 8) | sten;
r249095r249096
22332246   maddress = method * 4;
22342247   data = space.read_dword(address);
22352248   channel[chanel][subchannel].object.method[method] = data;
2249#ifdef LOG_NV2A
2250   printf("A:%08X MTHD:%08X D:%08X\n\r",address,maddress,data);
2251#endif
22362252   if (maddress == 0x17fc) {
22372253      indexesleft_count = 0;
22382254      indexesleft_first = 0;
r249095r249096
22702286         }
22712287         wait();
22722288      }
2289      else if (type == nv2a_renderer::TRIANGLE_FAN) {
2290         vertex_nv vert[3];
2291         vertex_t xy[3];
2292
2293         read_vertices_0x1810(space, vert, offset, 2);
2294         convert_vertices_poly(vert, xy, 2);
2295         count = count - 2;
2296         offset = offset + 2;
2297         for (n = 0; n <= count; n++) {
2298            read_vertices_0x1810(space, vert + (((n + 1) & 1) + 1), offset + n, 1);
2299            convert_vertices_poly(vert + (((n + 1) & 1) + 1), xy + (((n + 1) & 1) + 1), 1);
2300            render_triangle(limits_rendertarget, renderspans, 4 + 4 * 2, xy[0], xy[(~(n + 1) & 1) + 1], xy[((n + 1) & 1) + 1]);
2301         }
2302         wait();
2303      }
22732304      else if (type == nv2a_renderer::TRIANGLE_STRIP) {
22742305         vertex_nv vert[4];
22752306         vertex_t xy[4];
r249095r249096
23112342      // each dword after 1800 contains two 16 bit index values to select the vartices
23122343      // each dword after 1808 contains a 32 bit index value to select the vartices
23132344      type = channel[chanel][subchannel].object.method[0x17fc / 4];
2314#ifdef LOG_NV2A
2315      printf("vertex %d %d %d\n\r", type, offset, count);
2316#endif
23172345      if (type == nv2a_renderer::QUADS) {
23182346         while (1) {
23192347            vertex_nv vert[4];
r249095r249096
23322360            render_polygon<4>(limits_rendertarget, renderspans, 4 + 4 * 2, xy); // 4 rgba, 4 texture units 2 uv
23332361         }
23342362      }
2363      else if (type == nv2a_renderer::TRIANGLE_FAN) {
2364         if ((countlen * mult + indexesleft_count) >= 3) {
2365            vertex_nv vert[3];
2366            vertex_t xy[3];
2367            int c, count;
2368
2369            if (mult == 1)
2370               c = read_vertices_0x1808(space, vert, address, 2);
2371            else
2372               c = read_vertices_0x1800(space, vert, address, 2);
2373            convert_vertices_poly(vert, xy, 2);
2374            address = address + c * 4;
2375            countlen = countlen - c;
2376            count = countlen * mult + indexesleft_count;
2377            for (n = 1; n <= count; n++) {
2378               if (mult == 1)
2379                  c = read_vertices_0x1808(space, vert + ((n & 1) + 1), address, 1);
2380               else
2381                  c = read_vertices_0x1800(space, vert + ((n & 1) + 1), address, 1);
2382
2383               convert_vertices_poly(vert + ((n & 1) + 1), xy + ((n & 1) + 1), 1);
2384               address = address + c * 4;
2385               countlen = countlen - c;
2386               render_triangle(limits_rendertarget, renderspans, 4 + 4 * 2, xy[0], xy[(~n & 1) + 1], xy[(n & 1) + 1]);
2387            }
2388            wait();
2389         }
2390      }
23352391      else if (type == nv2a_renderer::TRIANGLES) {
23362392         while (1) {
23372393            vertex_nv vert[3];
r249095r249096
24462502         }
24472503         wait();
24482504      }
2505      else if (type == nv2a_renderer::TRIANGLES) {
2506         while (countlen > 0) {
2507            vertex_nv vert[3];
2508            vertex_t xy[3];
2509            int c;
2510
2511            c = read_vertices_0x1818(space, vert, address, 3);
2512            convert_vertices_poly(vert, xy, 3);
2513            countlen = countlen - c;
2514            if (countlen < 0) {
2515               logerror("Method 0x1818 missing %d words to draw a complete primitive\n", -countlen);
2516               countlen = 0;
2517               break;
2518            }
2519            address = address + c * 3;
2520            render_triangle(limits_rendertarget, renderspans, 4 + 4 * 2, xy[0], xy[1], xy[2]); // 4 rgba, 4 texture units 2 uv
2521         }
2522      }
24492523      else if (type == nv2a_renderer::TRIANGLE_STRIP) {
24502524         vertex_nv vert[4];
24512525         vertex_t xy[4];
r249095r249096
26132687         // clear colors
26142688         UINT32 color = channel[chanel][subchannel].object.method[0x1d90 / 4];
26152689         bm.fill(color);
2616         //printf("clearscreen\n\r");
2690#ifdef LOG_NV2A
2691         printf("clearscreen\n\r");
2692#endif
26172693      }
26182694      if ((data & 0x03) == 3) {
26192695         bitmap_rgb32 bm(depthbuffer, (limits_rendertarget.right() + 1) * m, (limits_rendertarget.bottom() + 1) * m, pitch_rendertarget / 4); // why *2 ?
r249095r249096
26492725      dilate_rendertarget = dilatechose[(log2width_rendertarget << 4) + log2height_rendertarget];
26502726   }
26512727   if (maddress == 0x020c) {
2652      // line size ?
26532728      pitch_rendertarget=data & 0xffff;
26542729      pitch_depthbuffer=(data >> 16) & 0xffff;
2655      //printf("Pitch color %04X zbuffer %04X\n\r",pitch_rendertarget,pitch_depthbuffer);
2730#ifdef LOG_NV2A
2731      printf("Pitch color %04X zbuffer %04X\n\r",pitch_rendertarget,pitch_depthbuffer);
2732#endif
26562733      countlen--;
26572734   }
26582735   if (maddress == 0x0100) {
2659      // just temporarily
2660      if ((data & 0x1f) == 1) {
2661         data = data >> 5;
2662         data = data & 0x0ffffff0;
2663         displayedtarget = (UINT32 *)direct_access_ptr(data);
2736      countlen--;
2737      if (data != 0) {
2738         pgraph[0x704 / 4] = 0x100;
2739         pgraph[0x708 / 4] = data;
2740         pgraph[0x100 / 4] |= 1;
2741         pgraph[0x108 / 4] |= 1;
2742         if (update_interrupts() == true)
2743            interruptdevice->ir3_w(1); // IRQ 3
2744         else
2745            interruptdevice->ir3_w(0); // IRQ 3
2746         return 2;
26642747      }
2748      else
2749         return 0;
26652750   }
26662751   if (maddress == 0x0130) {
26672752      countlen--;
r249095r249096
26702755      else
26712756         return 0;
26722757   }
2758   if (maddress == 0x1d8c) {
2759      countlen--;
2760      // it is used to specify the clear value for the depth buffer (zbuffer)
2761      // but also as a parameter for interrupt routines
2762      pgraph[0x1a88 / 4] = data;
2763   }
2764   if (maddress == 0x1d90) {
2765      countlen--;
2766      // it is used to specify the clear value for the color buffer
2767      // but also as a parameter for interrupt routines
2768      pgraph[0x186c / 4] = data;
2769   }
26732770   if (maddress == 0x0210) {
26742771      // framebuffer offset ?
26752772      rendertarget = (UINT32 *)direct_access_ptr(data);
2676      //printf("Render target at %08X\n\r",data);
2773#ifdef LOG_NV2A
2774      printf("Render target at %08X\n\r", data);
2775#endif
26772776      countlen--;
26782777   }
26792778   if (maddress == 0x0214) {
26802779      // zbuffer offset ?
26812780      depthbuffer = (UINT32 *)direct_access_ptr(data);
2682      //printf("Depth buffer at %08X\n\r",data);
2781#ifdef LOG_NV2A
2782      printf("Depth buffer at %08X\n\r",data);
2783#endif
26832784      if ((data == 0) || (data > 0x7ffffffc))
26842785         depth_write_enabled = false;
26852786      else if (channel[chanel][subchannel].object.method[0x035c / 4] != 0)
r249095r249096
27092810   if (maddress == 0x0354) {
27102811      depth_function = data;
27112812   }
2813   if (maddress == 0x0358) {
2814      //color_mask = data;
2815      if (data & 0x000000ff)
2816         data |= 0x000000ff;
2817      if (data & 0x0000ff00)
2818         data |= 0x0000ff00;
2819      if (data & 0x00ff0000)
2820         data |= 0x00ff0000;
2821      if (data & 0xff000000)
2822         data |= 0xff000000;
2823      color_mask = data;
2824   }
27122825   if (maddress == 0x035c) {
27132826      UINT32 g = channel[chanel][subchannel].object.method[0x0214 / 4];
27142827      depth_write_enabled = data != 0;
r249095r249096
36483761   combiner.function_Aop3 = MAX(MIN((combiner.function_Aop3 + biasa) * scalea, 1.0f), -1.0f);
36493762}
36503763
3651bool nv2a_renderer::vblank_callback(screen_device &screen, bool state)
3764void nv2a_renderer::vblank_callback(screen_device &screen, bool state)
36523765{
3653   //printf("vblank_callback\n\r");
3654   if (state == true)
3766#ifdef LOG_NV2A
3767   printf("vblank_callback\n\r");
3768#endif
3769   if ((state == true) && (puller_waiting == 1)) {
3770      puller_waiting = 0;
3771      puller_timer_work(NULL, 0);
3772   }
3773   if (state == true) {
36553774      pcrtc[0x100 / 4] |= 1;
3775      pcrtc[0x808 / 4] |= 0x10000;
3776   }
3777   else {
3778      pcrtc[0x100 / 4] &= ~1;
3779      pcrtc[0x808 / 4] &= ~0x10000;
3780   }
3781   if (update_interrupts() == true)
3782      interruptdevice->ir3_w(1); // IRQ 3
36563783   else
3657      pcrtc[0x100 / 4] &= ~1;
3784      interruptdevice->ir3_w(0); // IRQ 3
3785}
3786
3787bool nv2a_renderer::update_interrupts()
3788{
36583789   if (pcrtc[0x100 / 4] & pcrtc[0x140 / 4])
36593790      pmc[0x100 / 4] |= 0x1000000;
36603791   else
36613792      pmc[0x100 / 4] &= ~0x1000000;
3662   if ((state == true) && (puller_waiting == 1)) {
3663      puller_waiting = 0;
3664      puller_timer_work(NULL, 0);
3665   }
3666   if ((pmc[0x100 / 4] != 0) && (pmc[0x140 / 4] != 0)) {
3793   if (pgraph[0x100 / 4] & pgraph[0x140 / 4])
3794      pmc[0x100 / 4] |= 0x1000;
3795   else
3796      pmc[0x100 / 4] &= ~0x1000;
3797   if (((pmc[0x100 / 4] & 0x7fffffff) && (pmc[0x140 / 4] & 1)) || ((pmc[0x100 / 4] & 0x80000000) && (pmc[0x140 / 4] & 2))) {
36673798      // send interrupt
36683799      return true;
36693800   }
r249095r249096
36923823   int countlen;
36933824   int ret;
36943825   address_space *space = puller_space;
3826#ifdef LOG_NV2A
3827   UINT32 subch;
3828#endif
36953829
36963830   chanel = puller_channel;
36973831   subchannel = puller_subchannel;
r249095r249096
37483882            }
37493883            if (ret != 0) {
37503884               puller_timer->enable(false);
3751               puller_waiting = 1;
3885               puller_waiting = ret;
37523886               return;
37533887            }
37543888         }
r249095r249096
38473981      //logerror("NV_2A: read PRAMIN[%06X] value %08X\n",offset*4-0x00700000,ret);
38483982   }
38493983   else if ((offset >= 0x00400000 / 4) && (offset < 0x00402000 / 4)) {
3984      ret = pgraph[offset - 0x00400000 / 4];
38503985      //logerror("NV_2A: read PGRAPH[%06X] value %08X\n",offset*4-0x00400000,ret);
38513986   }
38523987   else if ((offset >= 0x00600000 / 4) && (offset < 0x00601000 / 4)) {
r249095r249096
38704005      //logerror("NV_2A: read channel[%02X,%d,%04X]=%08X\n",chanel,subchannel,suboffset*4,ret);
38714006      return ret;
38724007   }
3873   else
3874   {
3875      /* nothing */
3876   }
38774008   //logerror("NV_2A: read at %08X mask %08X value %08X\n",0xfd000000+offset*4,mem_mask,ret);
38784009   return ret;
38794010}
38804011
38814012WRITE32_MEMBER(nv2a_renderer::geforce_w)
38824013{
4014   UINT32 old;
4015   bool update_int;
4016
4017   update_int = false;
38834018   if ((offset >= 0x00101000 / 4) && (offset < 0x00102000 / 4)) {
38844019      //logerror("NV_2A: write STRAPS[%06X] mask %08X value %08X\n",offset*4-0x00101000,mem_mask,data);
38854020   }
r249095r249096
38984033      //logerror("NV_2A: write PRAMIN[%06X]=%08X\n",offset*4-0x00700000,data & mem_mask);
38994034   }
39004035   else if ((offset >= 0x00400000 / 4) && (offset < 0x00402000 / 4)) {
4036      int e = offset - 0x00400000 / 4;
4037      if (e >= (sizeof(pgraph) / sizeof(UINT32)))
4038         return;
4039      old = pgraph[e];
4040      COMBINE_DATA(pgraph + e);
4041      if (e == 0x100 / 4) {
4042         pgraph[e] = old & ~data;
4043         if (data & 1)
4044            pgraph[0x108 / 4] = 0;
4045         update_int = true;
4046      }
4047      if (e == 0x140 / 4)
4048         update_int = true;
4049      if (e == 0x720 / 4) {
4050         if ((data & 1) && (puller_waiting == 2)) {
4051            puller_waiting = 0;
4052            puller_timer->enable();
4053            puller_timer->adjust(attotime::zero);
4054         }
4055      }
4056      if ((e >= 0x900 / 4) && (e < 0xa00 / 4))
4057         pgraph[e] = 0;
39014058      //logerror("NV_2A: write PGRAPH[%06X]=%08X\n",offset*4-0x00400000,data & mem_mask);
39024059   }
39034060   else if ((offset >= 0x00600000 / 4) && (offset < 0x00601000 / 4)) {
39044061      int e = offset - 0x00600000 / 4;
39054062      if (e >= (sizeof(pcrtc) / sizeof(UINT32)))
39064063         return;
4064      old = pcrtc[e];
39074065      COMBINE_DATA(pcrtc + e);
4066      if (e == 0x100 / 4) {
4067         pcrtc[e] = old & ~data;
4068         update_int = true;
4069      }
4070      if (e == 0x140 / 4)
4071         update_int = true;
39084072      if (e == 0x800 / 4) {
3909         displayedtarget = (UINT32 *)direct_access_ptr(data);
3910         //printf("crtc buffer %08X\n\r", data);
4073         displayedtarget = (UINT32 *)direct_access_ptr(pcrtc[e]);
4074#ifdef LOG_NV2A
4075         printf("crtc buffer %08X\n\r", data);
4076#endif
39114077      }
39124078      //logerror("NV_2A: write PCRTC[%06X]=%08X\n",offset*4-0x00600000,data & mem_mask);
39134079   }
r249095r249096
39224088      // 32 channels size 0x10000 each, 8 subchannels per channel size 0x2000 each
39234089      int chanel, subchannel, suboffset;
39244090      //int method, count, handle, objclass;
3925#ifdef LOG_NV2A
3926      int subch;
3927#endif
39284091
39294092      suboffset = offset - 0x00800000 / 4;
39304093      chanel = (suboffset >> (16 - 2)) & 31;
r249095r249096
39594122   }
39604123   //else
39614124   //      logerror("NV_2A: write at %08X mask %08X value %08X\n",0xfd000000+offset*4,mem_mask,data);
4125   if (update_int == true) {
4126      if (update_interrupts() == true)
4127         interruptdevice->ir3_w(1); // IRQ 3
4128      else
4129         interruptdevice->ir3_w(0); // IRQ 3
4130   }
39624131}
39634132
39644133void nv2a_renderer::savestate_items()
r249095r249096
39714140   puller_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(nv2a_renderer::puller_timer_work), this), (void *)"NV2A Puller Timer");
39724141   puller_timer->enable(false);
39734142}
4143
4144void nv2a_renderer::set_interrupt_device(pic8259_device *device)
4145{
4146   interruptdevice = device;
4147}
trunk/src/mame/video/deco16ic.c
r249095r249096
3636    Pocket Gal DX               MAZ     102     52,71           56              104         153
3737    Boogie Wings                MBD     102     52,52,71,71     141, 141        104         113,99,200
38381   Double Wings                MBE     102     52              141             104
393   Fighter's History DE-0380-0 MBF     156     52              56, 74          [Scratched] 153,153,200,170
393   Fighter's History DE-0380-0 MBF     156     52              56, 74          75          153,153,200,170
40403   Fighter's History DE-0395-1 MBF     156     52              56, 74          75          113,113,200
41413   Fighter's History DE-0396-0 MBF     156     52              74, 141         75          153,153,200
4242    Heavy Smash                 MBG     156     52              141                         153,153,153
43    Night Slashers              MBH     156     52(*3)          74, 141         104         153(*3),99,200
43    Night Slashers DE-0397-0    MBH     156     52,52,52        74, 141         104         153,153,153,99,200
44    Night Slashers DE-0395-1    MBH     156     52,52,52        74, 141         104         113,113,153,99,200
4445    Locked N Loaded             MBM     101     ?               74, 74          146         113,186,187
4546    Joe & Mac Return            MBN     156     52              141                         223,223
46472   Charlie Ninja               MBR     156     52              141                         223,223
4748    World Cup Volleyball 95     MBX     156     52              141             ?
4849    Backfire!                   MBZ     156     52,52           141, 141        ?           153,153,223
492*  Ganbare Gonta               MCB     156     52              141                         223,223
502*  Ganbare! Gonta!! 2          MCB     156     52              141                         223,223
5051    Chain Reaction/Magical Drop MCC     156     52              141                         223,223
5152    Dunk Dream 95               MCE     156     [MLC]           [MLC]
52532   Osman/Cannon Dancer         MCF     156     52              141                         223,223
r249095r249096
6061
6162Note 1: Mitchell game on DECO PCB board number DEC-22V0 (S-NK-3220)
6263Note 2: Mitchell games on DECO PCB board number MT5601-0
63Note 3: Fighter's History was released on 3 different PCBs, DE-0396-0, DE-0395-1 & DE-0380-2
64        Fighter's History seems to use the 156 Encrypted ARM cpu with the encryption disabled
64Note 3: Fighter's History uses the 156 Encrypted ARM cpu with the encryption disabled
6565Note *: Ganbare! Gonta!! 2 / Lady Killer Part 2 - Party Time
6666
67Note: A version of Night Slashers runs on the DE-0395-1 using the 156 encryption, while a version
68      of Fighter's History also runs on the DE-0395-1 PCB without using the 156 encryption
69
6770    Custom chip 59  = 68000 cpu
6871    Custom chip 101 = Arm6 cpu
6972    Custom chip 113 = Alpha blending
trunk/src/mame/video/galastrm.c
r249095r249096
11// license:???
22// copyright-holders:Hau
33#include "emu.h"
4#include "video/polylgcy.h"
54#include "includes/galastrm.h"
65
76#define X_OFFSET 96
87#define Y_OFFSET 60
98
10struct gs_poly_extra_data
9struct polyVert
1110{
12   bitmap_ind16 *texbase;
13};
14
15struct polygon
16{
1711   float x;
1812   float y;
1913   float z;
2014};
2115
22/******************************************************************/
2316
24void galastrm_state::galastrm_exit()
17galastrm_renderer::galastrm_renderer(galastrm_state& state)
18    : poly_manager<float, gs_poly_data, 2, 10000>(state.machine())
19    , m_state(state)
20    , m_screenbits(state.m_screen->width(), state.m_screen->height())
2521{
26   poly_free(m_poly);
22   
2723}
2824
25
26/******************************************************************/
27
2928void galastrm_state::video_start()
3029{
3130   m_spritelist = auto_alloc_array(machine(), struct gs_tempsprite, 0x4000);
3231
33   m_screen->register_screen_bitmap(m_tmpbitmaps);
34   m_screen->register_screen_bitmap(m_polybitmap);
32    m_poly = auto_alloc(machine(), galastrm_renderer(*this));
3533
36   m_poly = poly_alloc(machine(), 16, sizeof(gs_poly_extra_data), POLYFLAG_ALLOW_QUADS);
37   machine().add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(galastrm_state::galastrm_exit), this));
34    m_screen->register_screen_bitmap(m_tmpbitmaps);
35    m_screen->register_screen_bitmap(m_poly->screenbits());
3836}
3937
38
4039/************************************************************
4140            SPRITE DRAW ROUTINES
4241
r249095r249096
185184         m_sprite_ptr_pre++;
186185      }
187186      if (bad_chunks)
188logerror("Sprite number %04x had %02x invalid chunks\n",tilenum,bad_chunks);
187            logerror("Sprite number %04x had %02x invalid chunks\n",tilenum,bad_chunks);
189188   }
190189}
191190
r249095r249096
215214                POLYGON RENDERER
216215**************************************************************/
217216
218static void tc0610_draw_scanline(void *dest, INT32 scanline, const poly_extent *extent, const void *extradata, int threadid)
217void galastrm_renderer::tc0610_draw_scanline(INT32 scanline, const extent_t& extent, const gs_poly_data& object, int threadid)
219218{
220   const gs_poly_extra_data *extra = (const gs_poly_extra_data *)extradata;
221   bitmap_ind16 *destmap = (bitmap_ind16 *)dest;
222   UINT16 *framebuffer = &destmap->pix16(scanline);
223   bitmap_ind16 *texbase = extra->texbase;
224   int startx = extent->startx;
225   int stopx = extent->stopx;
226   INT32 u = extent->param[0].start;
227   INT32 v = extent->param[1].start;
228   INT32 dudx = extent->param[0].dpdx;
229   INT32 dvdx = extent->param[1].dpdx;
230   int x;
219    UINT16 *framebuffer = &m_screenbits.pix16(scanline);
220   const INT32 dudx = extent.param[0].dpdx;
221   const INT32 dvdx = extent.param[1].dpdx;
231222
232   for (x = startx; x < stopx; x++)
223    INT32 u = extent.param[0].start;
224   INT32 v = extent.param[1].start;
225   for (int x = extent.startx; x < extent.stopx; x++)
233226   {
234      framebuffer[x] = texbase->pix16(v >> 16, u >> 16);
227      framebuffer[x] = object.texbase->pix16(v >> 16, u >> 16);
235228      u += dudx;
236229      v += dvdx;
237230   }
238231}
239232
240void galastrm_state::tc0610_rotate_draw(bitmap_ind16 &bitmap, bitmap_ind16 &srcbitmap, const rectangle &clip)
233void galastrm_renderer::tc0610_rotate_draw(bitmap_ind16 &srcbitmap, const rectangle &clip)
241234{
242   gs_poly_extra_data *extra = (gs_poly_extra_data *)poly_get_extra_data(m_poly);
243   poly_draw_scanline_func callback;
244   poly_vertex vert[4];
245   int rsx = m_tc0610_ctrl_reg[1][0];
246   int rsy = m_tc0610_ctrl_reg[1][1];
247   const int rzx = m_tc0610_ctrl_reg[1][2];
248   const int rzy = m_tc0610_ctrl_reg[1][3];
249   const int ryx = m_tc0610_ctrl_reg[1][5];
250   const int ryy = m_tc0610_ctrl_reg[1][4];
235   vertex_t vert[4];
236   int rsx = m_state.m_tc0610_ctrl_reg[1][0];
237   int rsy = m_state.m_tc0610_ctrl_reg[1][1];
238   const int rzx = m_state.m_tc0610_ctrl_reg[1][2];
239   const int rzy = m_state.m_tc0610_ctrl_reg[1][3];
240   const int ryx = m_state.m_tc0610_ctrl_reg[1][5];
241   const int ryy = m_state.m_tc0610_ctrl_reg[1][4];
251242   const int lx  = srcbitmap.width();
252243   const int ly  = srcbitmap.height();
253244
254245   int yx, /*yy,*/ zx, zy, pxx, pxy, pyx, pyy;
255246   float /*ssn, scs, ysn, ycs,*/ zsn, zcs;
256247
257
258248   pxx = 0;
259249   pxy = 0;
260250   pyx = 0;
r249095r249096
281271   zcs = ((float)pxx/4096.0f) / (float)(lx / 2);
282272
283273
284   if ((rsx == -240 && rsy == 1072) || !m_tc0610_ctrl_reg[1][7])
274   if ((rsx == -240 && rsy == 1072) || !m_state.m_tc0610_ctrl_reg[1][7])
285275   {
286      m_rsxoffs = 0;
287      m_rsyoffs = 0;
276      m_state.m_rsxoffs = 0;
277      m_state.m_rsyoffs = 0;
288278   }
289279   else
290280   {
291      if (rsx > m_rsxb && m_rsxb < 0 && rsx-m_rsxb > 0x8000)
281      if (rsx > m_state.m_rsxb && m_state.m_rsxb < 0 && rsx-m_state.m_rsxb > 0x8000)
292282      {
293         if (m_rsxoffs == 0)
294            m_rsxoffs = -0x10000;
283         if (m_state.m_rsxoffs == 0)
284            m_state.m_rsxoffs = -0x10000;
295285         else
296            m_rsxoffs = 0;
286            m_state.m_rsxoffs = 0;
297287      }
298      if (rsx < m_rsxb && m_rsxb > 0 && m_rsxb-rsx > 0x8000)
288      if (rsx < m_state.m_rsxb && m_state.m_rsxb > 0 && m_state.m_rsxb-rsx > 0x8000)
299289      {
300         if (m_rsxoffs == 0)
301            m_rsxoffs = 0x10000-1;
290         if (m_state.m_rsxoffs == 0)
291            m_state.m_rsxoffs = 0x10000-1;
302292         else
303            m_rsxoffs = 0;
293            m_state.m_rsxoffs = 0;
304294      }
305      if (rsy > m_rsyb && m_rsyb < 0 && rsy-m_rsyb > 0x8000)
295      if (rsy > m_state.m_rsyb && m_state.m_rsyb < 0 && rsy-m_state.m_rsyb > 0x8000)
306296      {
307         if (m_rsyoffs == 0)
308            m_rsyoffs = -0x10000;
297         if (m_state.m_rsyoffs == 0)
298            m_state.m_rsyoffs = -0x10000;
309299         else
310            m_rsyoffs = 0;
300            m_state.m_rsyoffs = 0;
311301      }
312      if (rsy < m_rsyb && m_rsyb > 0 && m_rsyb-rsy > 0x8000)
302      if (rsy < m_state.m_rsyb && m_state.m_rsyb > 0 && m_state.m_rsyb-rsy > 0x8000)
313303      {
314         if (m_rsyoffs == 0)
315            m_rsyoffs = 0x10000-1;
304         if (m_state.m_rsyoffs == 0)
305            m_state.m_rsyoffs = 0x10000-1;
316306         else
317            m_rsyoffs = 0;
307            m_state.m_rsyoffs = 0;
318308      }
319309   }
320   m_rsxb = rsx;
321   m_rsyb = rsy;
322   if (m_rsxoffs) rsx += m_rsxoffs;
323   if (m_rsyoffs) rsy += m_rsyoffs;
324   if (rsx < -0x14000 || rsx >= 0x14000) m_rsxoffs = 0;
325   if (rsy < -0x14000 || rsy >= 0x14000) m_rsyoffs = 0;
310   m_state.m_rsxb = rsx;
311   m_state.m_rsyb = rsy;
312   if (m_state.m_rsxoffs) rsx += m_state.m_rsxoffs;
313   if (m_state.m_rsyoffs) rsy += m_state.m_rsyoffs;
314   if (rsx < -0x14000 || rsx >= 0x14000) m_state.m_rsxoffs = 0;
315   if (rsy < -0x14000 || rsy >= 0x14000) m_state.m_rsyoffs = 0;
326316
327317
328318   pxx = 0;
r249095r249096
336326   //ysn = 0.0;
337327   //ycs = 0.0;
338328
339   if (m_tc0610_ctrl_reg[1][7])
329   if (m_state.m_tc0610_ctrl_reg[1][7])
340330   {
341331      if (ryx != 0 || ryy != 0)
342332      {
r249095r249096
382372      //scs = ((float)pyy/65536.0) / (float)(ly / 2);
383373   }
384374
385
386375   {
387      polygon tmpz[4];
388
376      polyVert tmpz[4];
389377      tmpz[0].x = ((float)(-zx)  * zcs) - ((float)(-zy)  * zsn);
390378      tmpz[0].y = ((float)(-zx)  * zsn) + ((float)(-zy)  * zcs);
391379      tmpz[0].z = 0.0;
r249095r249096
399387      tmpz[3].y = ((float)(zx-1) * zsn) + ((float)(-zy)  * zcs);
400388      tmpz[3].z = 0.0;
401389
402
403390      vert[0].x = tmpz[0].x + (float)(lx / 2);
404391      vert[0].y = tmpz[0].y + (float)(ly / 2);
405392      vert[1].x = tmpz[1].x + (float)(lx / 2);
r249095r249096
419406   vert[3].p[0] = (float)(lx - 1) * 65536.0f;
420407   vert[3].p[1] = 0.0;
421408
422   extra->texbase = &srcbitmap;
423   callback = tc0610_draw_scanline;
424   poly_render_quad(m_poly, &bitmap, clip, callback, 2, &vert[0], &vert[1], &vert[2], &vert[3]);
409    gs_poly_data& extra = object_data_alloc();
410    extra.texbase = &srcbitmap;
411   
412    render_polygon<4>(clip, render_delegate(FUNC(galastrm_renderer::tc0610_draw_scanline), this), 2, vert);
413    wait();
425414}
426415
427416/**************************************************************
r249095r249096
533522         {
534523            pri = &priority_bitmap.pix8(y, x);
535524            if (!(*pri & 0x02) && m_tmpbitmaps.pix16(y, x))
536                  *pri |= 0x04;
525               *pri |= 0x04;
537526         }
538527      }
539528   }
r249095r249096
541530   draw_sprites_pre(42-X_OFFSET, -571+Y_OFFSET);
542531   draw_sprites(screen,m_tmpbitmaps,clip,primasks,1);
543532
544   copybitmap_trans(bitmap,m_polybitmap,0,0, 0,0,cliprect,0);
545   m_polybitmap.fill(0, clip);
546   tc0610_rotate_draw(m_polybitmap,m_tmpbitmaps,cliprect);
547
533    copybitmap_trans(bitmap, m_poly->screenbits(), 0,0, 0,0, cliprect, 0);
534   m_poly->screenbits().fill(0, clip);
535    m_poly->tc0610_rotate_draw(m_tmpbitmaps, cliprect);
536   
548537   priority_bitmap.fill(0, cliprect);
549538   draw_sprites(screen,bitmap,cliprect,primasks,0);
550539
trunk/src/mame/video/hng64.c
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner
33#include "emu.h"
44#include "drawgfxm.h"
55#include "includes/hng64.h"
trunk/src/mame/video/hng64_sprite.c
r249095r249096
11// license:LGPL-2.1+
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner, Andrew Zaferakis
2// copyright-holders:David Haywood, Angelo Salese, ElSemi, Andrew Gardner
33
44/* Hyper NeoGeo 64 Sprite bits */
55
trunk/src/mame/video/midzeus2.c
r249095r249096
99#include "emu.h"
1010#include "cpu/tms32031/tms32031.h"
1111#include "includes/midzeus.h"
12#include "video/polylgcy.h"
12#include "video/poly.h"
1313#include "video/rgbutil.h"
1414
1515
r249095r249096
5050};
5151
5252
53/*************************************
54 *
55 *  Polygon renderer
56 *
57 *************************************/
5358
59class midzeus2_renderer : public poly_manager<float, mz2_poly_extra_data, 4, 10000>
60{
61public:
62   midzeus2_renderer(midzeus2_state &state);
63
64    void render_poly_8bit(INT32 scanline, const extent_t& extent, const mz2_poly_extra_data& object, int threadid);
65   
66    void zeus2_draw_quad(const UINT32 *databuffer, UINT32 texoffs, int logit);
67   
68private:
69   midzeus2_state& m_state;
70};
71
72typedef midzeus2_renderer::vertex_t poly_vertex;
73typedef midzeus2_renderer::extent_t poly_extent;
74
75midzeus2_renderer::midzeus2_renderer(midzeus2_state &state)
76    : poly_manager<float, mz2_poly_extra_data, 4, 10000>(state.machine())
77    , m_state(state)
78{
79   
80}
81
82
5483/*************************************
5584 *
5685 *  Global variables
5786 *
5887 *************************************/
5988
60static legacy_poly_manager *poly;
89static midzeus2_renderer* poly;
6190static UINT8 log_fifo;
6291
6392static UINT32 zeus_fifo[20];
r249095r249096
99128
100129/*************************************
101130 *
102 *  Function prototypes
103 *
104 *************************************/
105
106static void render_poly_8bit(void *dest, INT32 scanline, const poly_extent *extent, const void *extradata, int threadid);
107
108/*************************************
109 *
110131 *  Macros
111132 *
112133 *************************************/
r249095r249096
258279   waveram[1] = auto_alloc_array(machine(), UINT32, WAVERAM1_WIDTH * WAVERAM1_HEIGHT * 12/4);
259280
260281   /* initialize polygon engine */
261   poly = poly_alloc(machine(), 10000, sizeof(mz2_poly_extra_data), POLYFLAG_ALLOW_QUADS);
262
282    poly = auto_alloc(machine(), midzeus2_renderer(*this));
283   
263284   /* we need to cleanup on exit */
264285   machine().add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(midzeus2_state::exit_handler2), this));
265286
r249095r249096
335356}
336357#endif
337358
338   poly_free(poly);
339359}
340360
341361
r249095r249096
350370{
351371   int x, y;
352372
353   poly_wait(poly, "VIDEO_UPDATE");
354
373    poly->wait();
374   
355375if (machine().input().code_pressed(KEYCODE_UP)) { zbase += 1.0f; popmessage("Zbase = %f", (double) zbase); }
356376if (machine().input().code_pressed(KEYCODE_DOWN)) { zbase -= 1.0f; popmessage("Zbase = %f", (double) zbase); }
357377
r249095r249096
10071027                  break;
10081028
10091029               case 0x38:  /* crusnexo/thegrid */
1010                  zeus2_draw_quad(databuffer, texoffs, logit);
1030                  poly->zeus2_draw_quad(databuffer, texoffs, logit);
10111031                  break;
10121032
10131033               default:
r249095r249096
10361056 *
10371057 *************************************/
10381058
1039void midzeus2_state::zeus2_draw_quad(const UINT32 *databuffer, UINT32 texoffs, int logit)
1059void midzeus2_renderer::zeus2_draw_quad(const UINT32 *databuffer, UINT32 texoffs, int logit)
10401060{
1041   poly_draw_scanline_func callback;
1042   mz2_poly_extra_data *extra;
10431061   poly_vertex clipvert[8];
10441062   poly_vertex vert[4];
10451063//  float uscale, vscale;
r249095r249096
10641082//if (machine().input().code_pressed(KEYCODE_O) && (texoffs & 0xffff) == 0x119) return;
10651083//if (machine().input().code_pressed(KEYCODE_L) && (texoffs & 0x100)) return;
10661084
1067   callback = render_poly_8bit;
1068
10691085/*
107010860   38800000
107110871   x2 | x1
r249095r249096
11791195      }
11801196   }
11811197
1182   numverts = poly_zclip_if_less(4, &vert[0], &clipvert[0], 4, 1.0f / 512.0f / 4.0f);
1198   numverts = poly->zclip_if_less(4, &vert[0], &clipvert[0], 4, 1.0f / 512.0f / 4.0f);
11831199   if (numverts < 3)
11841200      return;
11851201
r249095r249096
12101226         clipvert[i].y += 0.0005f;
12111227   }
12121228
1213   extra = (mz2_poly_extra_data *)poly_get_extra_data(poly);
1229    mz2_poly_extra_data& extra = poly->object_data_alloc();
12141230   switch (texmode)
12151231   {
12161232      case 0x01d:     /* crusnexo: RHS of score bar */
r249095r249096
12221238      case 0x95d:     /* crusnexo */
12231239      case 0xc1d:     /* crusnexo */
12241240      case 0xc5d:     /* crusnexo */
1225         extra->texwidth = 256;
1241         extra.texwidth = 256;
12261242         break;
12271243
12281244      case 0x059:     /* crusnexo */
12291245      case 0x0d9:     /* crusnexo */
12301246      case 0x119:     /* crusnexo: license plates */
12311247      case 0x159:     /* crusnexo */
1232         extra->texwidth = 128;
1248         extra.texwidth = 128;
12331249         break;
12341250
12351251      case 0x055:     /* crusnexo */
12361252      case 0x155:     /* crusnexo */
1237         extra->texwidth = 64;
1253         extra.texwidth = 64;
12381254         break;
12391255
12401256      default:
r249095r249096
12491265      }
12501266   }
12511267
1252   extra->solidcolor = 0;//m_zeusbase[0x00] & 0x7fff;
1253   extra->zoffset = 0;//m_zeusbase[0x7e] >> 16;
1254   extra->alpha = 0;//m_zeusbase[0x4e];
1255   extra->transcolor = 0x100;//((databuffer[1] >> 16) & 1) ? 0 : 0x100;
1256   extra->texbase = WAVERAM_BLOCK0(zeus_texbase);
1257   extra->palbase = waveram0_ptr_from_expanded_addr(m_zeusbase[0x41]);
1268   extra.solidcolor = 0;//m_zeusbase[0x00] & 0x7fff;
1269   extra.zoffset = 0;//m_zeusbase[0x7e] >> 16;
1270   extra.alpha = 0;//m_zeusbase[0x4e];
1271   extra.transcolor = 0x100;//((databuffer[1] >> 16) & 1) ? 0 : 0x100;
1272   extra.texbase = WAVERAM_BLOCK0(zeus_texbase);
1273   extra.palbase = waveram0_ptr_from_expanded_addr(m_state.m_zeusbase[0x41]);
12581274
1259   poly_render_quad_fan(poly, NULL, zeus_cliprect, callback, 4, numverts, &clipvert[0]);
1275    // Note: Before being converted to the "poly.h" interface, this used to call the polylgcy function
1276    //       poly_render_quad_fan.  The behavior seems to be the same as it once was after a few short
1277    //       tests, but the (numverts == 5) statement below may actually be a quad fan instead of a 5-sided
1278    //       polygon.
1279    if (numverts == 3)
1280        render_triangle(zeus_cliprect, render_delegate(FUNC(midzeus2_renderer::render_poly_8bit), this), 4, clipvert[0], clipvert[1], clipvert[2]);
1281    else if (numverts == 4)
1282        render_polygon<4>(zeus_cliprect, render_delegate(FUNC(midzeus2_renderer::render_poly_8bit), this), 4, clipvert);
1283    else if (numverts == 5)
1284        render_polygon<5>(zeus_cliprect, render_delegate(FUNC(midzeus2_renderer::render_poly_8bit), this), 4, clipvert);
12601285}
12611286
12621287
r249095r249096
12671292 *
12681293 *************************************/
12691294
1270static void render_poly_8bit(void *dest, INT32 scanline, const poly_extent *extent, const void *extradata, int threadid)
1295void midzeus2_renderer::render_poly_8bit(INT32 scanline, const extent_t& extent, const mz2_poly_extra_data& object, int threadid)
12711296{
1272   const mz2_poly_extra_data *extra = (const mz2_poly_extra_data *)extradata;
1273   INT32 curz = extent->param[0].start;
1274   INT32 curu = extent->param[1].start;
1275   INT32 curv = extent->param[2].start;
1276//  INT32 curi = extent->param[3].start;
1277   INT32 dzdx = extent->param[0].dpdx;
1278   INT32 dudx = extent->param[1].dpdx;
1279   INT32 dvdx = extent->param[2].dpdx;
1280//  INT32 didx = extent->param[3].dpdx;
1281   const void *texbase = extra->texbase;
1282   const void *palbase = extra->palbase;
1283   UINT16 transcolor = extra->transcolor;
1284   int texwidth = extra->texwidth;
1297   INT32 curz = extent.param[0].start;
1298   INT32 curu = extent.param[1].start;
1299   INT32 curv = extent.param[2].start;
1300//  INT32 curi = extent.param[3].start;
1301   INT32 dzdx = extent.param[0].dpdx;
1302   INT32 dudx = extent.param[1].dpdx;
1303   INT32 dvdx = extent.param[2].dpdx;
1304//  INT32 didx = extent.param[3].dpdx;
1305   const void *texbase = object.texbase;
1306   const void *palbase = object.palbase;
1307   UINT16 transcolor = object.transcolor;
1308   int texwidth = object.texwidth;
12851309   int x;
12861310
1287   for (x = extent->startx; x < extent->stopx; x++)
1311   for (x = extent.startx; x < extent.stopx; x++)
12881312   {
12891313      UINT16 *depthptr = WAVERAM_PTRDEPTH(zeus_renderbase, scanline, x);
1290      INT32 depth = (curz >> 16) + extra->zoffset;
1314      INT32 depth = (curz >> 16) + object.zoffset;
12911315      if (depth > 0x7fff) depth = 0x7fff;
12921316      if (depth >= 0 && depth <= *depthptr)
12931317      {
trunk/src/mame/video/model2.c
r249095r249096
8989*********************************************************************************************************************************/
9090#include "emu.h"
9191#include "video/segaic24.h"
92#include "video/polylgcy.h"
9392#include "includes/model2.h"
9493
9594#define MODEL2_VIDEO_DEBUG 0
r249095r249096
102101
103102/*******************************************
104103 *
105 *  Basic Data Types
106 *
107 *******************************************/
108
109struct plane
110{
111   poly_vertex normal;
112   float       distance;
113};
114
115struct texture_parameter
116{
117   float   diffuse;
118   float   ambient;
119   UINT32  specular_control;
120   float   specular_scale;
121};
122
123struct triangle
124{
125   void *              next;
126   poly_vertex         v[3];
127   UINT16              z;
128   UINT16              texheader[4];
129   UINT8               luma;
130   INT16               viewport[4];
131   INT16               center[2];
132};
133
134struct quad_m2
135{
136   poly_vertex         v[4];
137   UINT16              z;
138   UINT16              texheader[4];
139   UINT8               luma;
140};
141
142struct m2_poly_extra_data
143{
144   model2_state *  state;
145   UINT32      lumabase;
146   UINT32      colorbase;
147   UINT32 *    texsheet;
148   UINT32      texwidth;
149   UINT32      texheight;
150   UINT32      texx, texy;
151   UINT8       texmirrorx;
152   UINT8       texmirrory;
153};
154
155
156/*******************************************
157 *
158104 *  Generic 3D Math Functions
159105 *
160106 *******************************************/
r249095r249096
834780}
835781
836782/***********************************************************************************************/
837
838INLINE UINT16 get_texel( UINT32 base_x, UINT32 base_y, int x, int y, UINT32 *sheet )
839{
840   UINT32  baseoffs = ((base_y/2)*512)+(base_x/2);
841   UINT32  texeloffs = ((y/2)*512)+(x/2);
842   UINT32  offset = baseoffs + texeloffs;
843   UINT32  texel = sheet[offset>>1];
844
845   if ( offset & 1 )
846      texel >>= 16;
847
848   if ( (y & 1) == 0 )
849      texel >>= 8;
850
851   if ( (x & 1) == 0 )
852      texel >>= 4;
853
854   return (texel & 0x0f);
855}
856
857/* checker = 0, textured = 0, transparent = 0 */
858#define MODEL2_FUNC 0
859#define MODEL2_FUNC_NAME    model2_3d_render_0
860#include "model2rd.inc"
861#undef MODEL2_FUNC
862#undef MODEL2_FUNC_NAME
863
864/* checker = 0, textured = 0, translucent = 1 */
865#define MODEL2_FUNC 1
866#define MODEL2_FUNC_NAME    model2_3d_render_1
867#include "model2rd.inc"
868#undef MODEL2_FUNC
869#undef MODEL2_FUNC_NAME
870
871/* checker = 0, textured = 1, translucent = 0 */
872#define MODEL2_FUNC 2
873#define MODEL2_FUNC_NAME    model2_3d_render_2
874#include "model2rd.inc"
875#undef MODEL2_FUNC
876#undef MODEL2_FUNC_NAME
877
878/* checker = 0, textured = 1, translucent = 1 */
879#define MODEL2_FUNC 3
880#define MODEL2_FUNC_NAME    model2_3d_render_3
881#include "model2rd.inc"
882#undef MODEL2_FUNC
883#undef MODEL2_FUNC_NAME
884
885/* checker = 1, textured = 0, translucent = 0 */
886#define MODEL2_FUNC 4
887#define MODEL2_FUNC_NAME    model2_3d_render_4
888#include "model2rd.inc"
889#undef MODEL2_FUNC
890#undef MODEL2_FUNC_NAME
891
892/* checker = 1, textured = 0, translucent = 1 */
893#define MODEL2_FUNC 5
894#define MODEL2_FUNC_NAME    model2_3d_render_5
895#include "model2rd.inc"
896#undef MODEL2_FUNC
897#undef MODEL2_FUNC_NAME
898
899/* checker = 1, textured = 1, translucent = 0 */
900#define MODEL2_FUNC 6
901#define MODEL2_FUNC_NAME    model2_3d_render_6
902#include "model2rd.inc"
903#undef MODEL2_FUNC
904#undef MODEL2_FUNC_NAME
905
906/* checker = 1, textured = 1, translucent = 1 */
907#define MODEL2_FUNC 7
908#define MODEL2_FUNC_NAME    model2_3d_render_7
909#include "model2rd.inc"
910#undef MODEL2_FUNC
911#undef MODEL2_FUNC_NAME
912
783   
913784/***********************************************************************************************/
914785
915static const poly_draw_scanline_func render_funcs[8] =
786void model2_renderer::model2_3d_render(triangle *tri, const rectangle &cliprect)
916787{
917   model2_3d_render_0, /* checker = 0, textured = 0, translucent = 0 */
918   model2_3d_render_1, /* checker = 0, textured = 0, translucent = 1 */
919   model2_3d_render_2, /* checker = 0, textured = 1, translucent = 0 */
920   model2_3d_render_3, /* checker = 0, textured = 1, translucent = 1 */
921   model2_3d_render_4, /* checker = 1, textured = 0, translucent = 0 */
922   model2_3d_render_5, /* checker = 1, textured = 0, translucent = 1 */
923   model2_3d_render_6, /* checker = 1, textured = 1, translucent = 0 */
924   model2_3d_render_7  /* checker = 1, textured = 1, translucent = 1 */
925};
788   model2_renderer *poly = m_state.m_poly;
789    m2_poly_extra_data& extra = poly->object_data_alloc();
790   UINT8 renderer;
926791
927static void model2_3d_render( model2_state *state, bitmap_rgb32 &bitmap, triangle *tri, const rectangle &cliprect )
928{
929   legacy_poly_manager *poly = state->m_poly;
930   m2_poly_extra_data *extra = (m2_poly_extra_data *)poly_get_extra_data(poly);
931   UINT8       renderer;
932
933792   /* select renderer based on attributes (bit15 = checker, bit14 = textured, bit13 = transparent */
934793   renderer = (tri->texheader[0] >> 13) & 7;
935794
r249095r249096
937796   rectangle vp(tri->viewport[0] - 8, tri->viewport[2] - 8, (384-tri->viewport[3])+90, (384-tri->viewport[1])+90);
938797   vp &= cliprect;
939798
940   extra->state = state;
941   extra->lumabase = ((tri->texheader[1] & 0xFF) << 7) + ((tri->luma >> 5) ^ 0x7);
942   extra->colorbase = (tri->texheader[3] >> 6) & 0x3FF;
799   extra.state = &m_state;
800   extra.lumabase = ((tri->texheader[1] & 0xFF) << 7) + ((tri->luma >> 5) ^ 0x7);
801   extra.colorbase = (tri->texheader[3] >> 6) & 0x3FF;
943802
944803   if (renderer & 2)
945804   {
946      extra->texwidth = 32 << ((tri->texheader[0] >> 0) & 0x7);
947      extra->texheight = 32 << ((tri->texheader[0] >> 3) & 0x7);
948      extra->texx = 32 * ((tri->texheader[2] >> 0) & 0x1f);
949      extra->texy = 32 * (((tri->texheader[2] >> 6) & 0x1f) + ( tri->texheader[2] & 0x20 ));
805      extra.texwidth = 32 << ((tri->texheader[0] >> 0) & 0x7);
806      extra.texheight = 32 << ((tri->texheader[0] >> 3) & 0x7);
807      extra.texx = 32 * ((tri->texheader[2] >> 0) & 0x1f);
808      extra.texy = 32 * (((tri->texheader[2] >> 6) & 0x1f) + ( tri->texheader[2] & 0x20 ));
950809      /* TODO: Virtua Striker contradicts with this. */
951      extra->texmirrorx = 0;//(tri->texheader[0] >> 9) & 1;
952      extra->texmirrory = 0;//(tri->texheader[0] >> 8) & 1;
953      extra->texsheet = (tri->texheader[2] & 0x1000) ? state->m_textureram1 : state->m_textureram0;
810      extra.texmirrorx = 0;//(tri->texheader[0] >> 9) & 1;
811      extra.texmirrory = 0;//(tri->texheader[0] >> 8) & 1;
812      extra.texsheet = (tri->texheader[2] & 0x1000) ? m_state.m_textureram1 : m_state.m_textureram0;
954813
955814      tri->v[0].pz = 1.0f / (1.0f + tri->v[0].pz);
956815      tri->v[0].pu = tri->v[0].pu * tri->v[0].pz * (1.0f / 8.0f);
r249095r249096
962821      tri->v[2].pu = tri->v[2].pu * tri->v[2].pz * (1.0f / 8.0f);
963822      tri->v[2].pv = tri->v[2].pv * tri->v[2].pz * (1.0f / 8.0f);
964823
965      poly_render_triangle(poly, &bitmap, vp, render_funcs[renderer], 3, &tri->v[0], &tri->v[1], &tri->v[2]);
824        // Note : The class model2_renderer has an array of function pointers in it named m_renderfuncs, in theory this simply
825        //        needs to be passed into the render_triangle function as such model2_renderer::m_renderfuncs[renderer], but
826        //        I was unable to make it work when converting to the new polygon rasterizer interface.
827        switch (renderer)
828        {
829        case 0: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_0), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
830        case 1: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_1), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
831        case 2: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_2), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
832        case 3: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_3), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
833        case 4: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_4), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
834        case 5: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_5), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
835        case 6: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_6), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
836        case 7: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_7), this), 3, tri->v[0], tri->v[1], tri->v[2]); break;
837        }
966838   }
967839   else
968      poly_render_triangle(poly, &bitmap, vp, render_funcs[renderer], 0, &tri->v[0], &tri->v[1], &tri->v[2]);
840    {
841        switch (renderer)
842        {
843        case 0: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_0), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
844        case 1: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_1), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
845        case 2: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_2), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
846        case 3: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_3), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
847        case 4: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_4), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
848        case 5: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_5), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
849        case 6: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_6), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
850        case 7: render_triangle(vp, render_delegate(FUNC(model2_renderer::model2_3d_render_7), this), 0, tri->v[0], tri->v[1], tri->v[2]); break;
851        }
852    }
969853}
970854
971855/*
r249095r249096
1019903void model2_state::model2_3d_frame_end( bitmap_rgb32 &bitmap, const rectangle &cliprect )
1020904{
1021905   raster_state *raster = m_raster;
1022   INT32       z;
906   INT32 z;
1023907
1024908   /* if we have nothing to render, bail */
1025909   if ( raster->tri_list_index == 0 )
r249095r249096
1063947   }
1064948#endif
1065949
950    m_poly->destmap().fill(0x00000000, cliprect);
951   
1066952   /* go through the Z levels, and render each bucket */
1067953   for( z = raster->max_z; z >= raster->min_z; z-- )
1068954   {
r249095r249096
1077963         {
1078964            /* project and render */
1079965            model2_3d_project( tri );
1080            model2_3d_render( this, bitmap, tri, cliprect );
966            m_poly->model2_3d_render(tri, cliprect);
1081967
1082968            tri = (triangle *)tri->next;
1083969         }
1084970      }
1085971   }
1086   poly_wait(m_poly, "End of frame");
972   m_poly->wait("End of frame");
973   
974    copybitmap_trans(bitmap, m_poly->destmap(), 0, 0, 0, 0, cliprect, 0x00000000);
1087975}
1088976
1089977/* 3D Rasterizer main data input port */
r249095r249096
26942582/***********************************************************************************************/
26952583
26962584
2697void model2_state::model2_exit()
2698{
2699   poly_free(m_poly);
2700}
2701
27022585VIDEO_START_MEMBER(model2_state,model2)
27032586{
27042587   const rectangle &visarea = m_screen->visible_area();
r249095r249096
27072590
27082591   m_sys24_bitmap.allocate(width, height+4);
27092592
2710   m_poly = poly_alloc(machine(), 4000, sizeof(m2_poly_extra_data), 0);
2711   machine().add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(model2_state::model2_exit), this));
2593    m_poly = auto_alloc(machine(), model2_renderer(*this));
27122594
27132595   /* initialize the hardware rasterizer */
27142596   model2_3d_init( machine(), (UINT16*)memregion("user3")->base() );
trunk/src/mame/video/model2rd.inc
r249095r249096
5656
5757#ifndef MODEL2_TEXTURED
5858/* non-textured render path */
59static void MODEL2_FUNC_NAME(void *dest, INT32 scanline, const poly_extent *extent, const void *extradata, int threadid)
59void MODEL2_FUNC_NAME(INT32 scanline, const extent_t& extent, const m2_poly_extra_data& object, int threadid)
6060{
6161#if !defined( MODEL2_TRANSLUCENT)
62   const m2_poly_extra_data *extra = (const m2_poly_extra_data *)extradata;
63   model2_state *state = extra->state;
64   bitmap_rgb32 *destmap = (bitmap_rgb32 *)dest;
62   model2_state *state = object.state;
63   bitmap_rgb32 *destmap = (bitmap_rgb32 *)&m_destmap;
6564   UINT32 *p = &destmap->pix32(scanline);
6665
6766   /* extract color information */
r249095r249096
6968   const UINT16 *colortable_g = (const UINT16 *)&state->m_colorxlat[0x4000/4];
7069   const UINT16 *colortable_b = (const UINT16 *)&state->m_colorxlat[0x8000/4];
7170   const UINT16 *lumaram = (const UINT16 *)state->m_lumaram.target();
72   UINT32  lumabase = extra->lumabase;
73   UINT32  color = extra->colorbase;
71   UINT32  lumabase = object.lumabase;
72   UINT32  color = object.colorbase;
7473   UINT8   luma;
7574   UINT32  tr, tg, tb;
7675   int     x;
r249095r249096
9897   /* build the final color */
9998   color = rgb_t(tr, tg, tb);
10099
101   for(x = extent->startx; x < extent->stopx; x++)
100   for(x = extent.startx; x < extent.stopx; x++)
102101#if defined(MODEL2_CHECKER)
103102      if ((x^scanline) & 1) p[x] = color;
104103#else
r249095r249096
109108
110109#else
111110/* textured render path */
112static void MODEL2_FUNC_NAME(void *dest, INT32 scanline, const poly_extent *extent, const void *extradata, int threadid)
111void MODEL2_FUNC_NAME(INT32 scanline, const extent_t& extent, const m2_poly_extra_data& object, int threadid)
113112{
114   const m2_poly_extra_data *extra = (const m2_poly_extra_data *)extradata;
115   model2_state *state = extra->state;
116   bitmap_rgb32 *destmap = (bitmap_rgb32 *)dest;
113   model2_state *state = object.state;
114   bitmap_rgb32 *destmap = (bitmap_rgb32 *)&m_destmap;
117115   UINT32 *p = &destmap->pix32(scanline);
118116
119   UINT32  tex_width = extra->texwidth;
120   UINT32  tex_height = extra->texheight;
117   UINT32  tex_width = object.texwidth;
118   UINT32  tex_height = object.texheight;
121119
122120   /* extract color information */
123121   const UINT16 *colortable_r = (const UINT16 *)&state->m_colorxlat[0x0000/4];
124122   const UINT16 *colortable_g = (const UINT16 *)&state->m_colorxlat[0x4000/4];
125123   const UINT16 *colortable_b = (const UINT16 *)&state->m_colorxlat[0x8000/4];
126124   const UINT16 *lumaram = (const UINT16 *)state->m_lumaram.target();
127   UINT32  colorbase = extra->colorbase;
128   UINT32  lumabase = extra->lumabase;
129   UINT32  tex_x = extra->texx;
130   UINT32  tex_y = extra->texy;
125   UINT32  colorbase = object.colorbase;
126   UINT32  lumabase = object.lumabase;
127   UINT32  tex_x = object.texx;
128   UINT32  tex_y = object.texy;
131129   UINT32  tex_x_mask, tex_y_mask;
132   UINT32  tex_mirr_x = extra->texmirrorx;
133   UINT32  tex_mirr_y = extra->texmirrory;
134   UINT32 *sheet = extra->texsheet;
135   float ooz = extent->param[0].start;
136   float uoz = extent->param[1].start;
137   float voz = extent->param[2].start;
138   float dooz = extent->param[0].dpdx;
139   float duoz = extent->param[1].dpdx;
140   float dvoz = extent->param[2].dpdx;
130   UINT32  tex_mirr_x = object.texmirrorx;
131   UINT32  tex_mirr_y = object.texmirrory;
132   UINT32 *sheet = object.texsheet;
133   float ooz = extent.param[0].start;
134   float uoz = extent.param[1].start;
135   float voz = extent.param[2].start;
136   float dooz = extent.param[0].dpdx;
137   float duoz = extent.param[1].dpdx;
138   float dvoz = extent.param[2].dpdx;
141139   int     x;
142140
143141   tex_x_mask  = tex_width - 1;
r249095r249096
149147   colortable_g += ((colorbase >>  5) & 0x1f) << 8;
150148   colortable_b += ((colorbase >> 10) & 0x1f) << 8;
151149
152   for(x = extent->startx; x < extent->stopx; x++, uoz += duoz, voz += dvoz, ooz += dooz)
150   for(x = extent.startx; x < extent.stopx; x++, uoz += duoz, voz += dvoz, ooz += dooz)
153151   {
154152      float z = recip_approx(ooz) * 256.0f;
155153      INT32 u = uoz * z;
trunk/src/mame/video/model3.c
r249095r249096
11// license:BSD-3-Clause
2// copyright-holders:Andrew Gardner, R. Belmont, Ville Linde
2// copyright-holders:R. Belmont, Ville Linde
33#include "emu.h"
44#include "video/poly.h"
55#include "video/rgbutil.h"
trunk/src/mame/video/namcos22.c
r249095r249096
4343#include "includes/namcos22.h"
4444
4545
46// polynew constructor
46// poly constructor
4747namcos22_renderer::namcos22_renderer(namcos22_state &state)
4848   : poly_manager<float, namcos22_object_data, 4, 8000>(state.machine()),
4949      m_state(state)
r249095r249096
6363
6464/*********************************************************************************************/
6565
66// polynew scanline callbacks
66// poly scanline callbacks
6767void namcos22_renderer::renderscanline_uvi_full(INT32 scanline, const extent_t &extent, const namcos22_object_data &extra, int threadid)
6868{
6969   float z = extent.param[0].start;
trunk/src/mess/drivers/asst128.c
r249095r249096
5858
5959void asst128_state::machine_start()
6060{
61   memory_region* font = memregion(":isa_cga:cga_mc1502:gfx1");
62   memcpy(font->base(), memregion("gfx1")->base(), 0x2000);
61   memory_region* font = memregion(":board0:cga_mc1502:gfx1");
62   memcpy(font->base(), memregion("maincpu")->base()+0xffa6e, 0x0400);
63   memcpy(font->base()+0x0400, memregion("maincpu")->base()+0xf4000, 0x0400);
6364}
6465
6566WRITE8_MEMBER(asst128_state::asst128_fdc_dor_w)
r249095r249096
107108   asst128_mb_device::static_set_cputag(*device, "maincpu");
108109   MCFG_DEVICE_INPUT_DEFAULTS(asst128)
109110
111//   MCFG_DEVICE_REMOVE("mb:dma8237")
112
110113   MCFG_DEVICE_REMOVE("mb:cassette")
111114   MCFG_CASSETTE_ADD("mb:cassette")
112115   MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_MOTOR_ENABLED | CASSETTE_SPEAKER_ENABLED)
113116
114   MCFG_ISA8_SLOT_ADD("mb:isa", "isa_cga", pc_isa8_cards, "cga_mc1502", true)
115   MCFG_ISA8_SLOT_ADD("mb:isa", "isa_lpt", pc_isa8_cards, "lpt", true)
116   MCFG_ISA8_SLOT_ADD("mb:isa", "isa_com", pc_isa8_cards, "com", true)
117   MCFG_ISA8_SLOT_ADD("mb:isa", "board0", pc_isa8_cards, "cga_mc1502", true)
118   MCFG_ISA8_SLOT_ADD("mb:isa", "board1", pc_isa8_cards, "lpt", true)
117119
118120   MCFG_PC_KBDC_SLOT_ADD("mb:pc_kbdc", "kbd", pc_xt_keyboards, STR_KBD_IBM_PC_XT_83)
119121
r249095r249096
124126
125127   MCFG_PC_JOY_ADD("pc_joy")
126128
127   /* internal ram */
128129   MCFG_RAM_ADD(RAM_TAG)
129130   MCFG_RAM_DEFAULT_SIZE("640K")
130131MACHINE_CONFIG_END
131132
132133ROM_START( asst128 )
133134   ROM_REGION16_LE(0x100000,"maincpu", 0)
134   ROM_DEFAULT_BIOS("floppy")
135   /* BASIC ROM taken from IBM 5150 and needs dumping */
136   ROM_LOAD( "basic-1.10.rom",    0xf6000, 0x8000, CRC(ebacb791) SHA1(07449ebca18f979b9ab748582b736e402f2bf940))
137   ROM_LOAD( "asf400-f600.bin",   0xf4000, 0x2000, CRC(e3bf22de) SHA1(d4319edc82c0015ca0adc6c8771e887659717e62))
138   ROM_SYSTEM_BIOS(0, "floppy", "3rd party floppy support")
139   ROMX_LOAD( "rombios7.bin",     0xfc001, 0x2000, CRC(7d7c8d6a) SHA1(a731a65ee547f1d78cfc91461f38166da014f3dc), ROM_SKIP(1) | ROM_BIOS(1))
140   ROMX_LOAD( "rombios8.bin",     0xfc000, 0x2000, CRC(ba304663) SHA1(b2533b8f8240f72b7315f27c7b64f95ac52687ca), ROM_SKIP(1) | ROM_BIOS(1))
141   ROM_SYSTEM_BIOS(1, "stock", "cassette-only BIOS?")
142   ROMX_LOAD( "mainbios.bin",     0xfe000, 0x2000, CRC(8426cbf5) SHA1(41d14137ffa651977041da22aa8071c0f7854158), ROM_BIOS(2))
135   ROM_LOAD( "extbios.bin",      0xf4000, 0x2000, CRC(e3bf22de) SHA1(d4319edc82c0015ca0adc6c8771e887659717e62))
136   ROM_LOAD( "basic.bin",        0xf6000, 0x8000, CRC(a4ec66f6) SHA1(80e934986022681ccde180e92aa108e716c4f19b))
137   ROM_LOAD( "mainbios.bin",     0xfe000, 0x2000, CRC(8426cbf5) SHA1(41d14137ffa651977041da22aa8071c0f7854158))
138
139   // XXX needs dumping
143140   ROM_REGION(0x2000,"gfx1", ROMREGION_ERASE00)
144   ROM_COPY( "maincpu", 0xffa6e, 0x0000, 0x0400 )
145   ROM_COPY( "maincpu", 0xfc000, 0x0400, 0x0400 )
141   ROM_LOAD( "asst128cg.bin", 0, 0x2000, NO_DUMP )
146142ROM_END
147143
148144/*    YEAR  NAME        PARENT      COMPAT      MACHINE     INPUT       INIT        COMPANY            FULLNAME */
trunk/src/mess/drivers/at.c
r249095r249096
264264
265265
266266static INPUT_PORTS_START( atcga )
267   PORT_START("DSW0")
268   PORT_DIPNAME( 0xc0, 0x40, "Number of floppy drives")
269   PORT_DIPSETTING(    0x00, "1" )
270   PORT_DIPSETTING(    0x40, "2" )
271   PORT_DIPSETTING(    0x80, "3" )
272   PORT_DIPSETTING(    0xc0, "4" )
273   PORT_DIPNAME( 0x30, 0x00, "Graphics adapter")
274   PORT_DIPSETTING(    0x00, "EGA/VGA" )
275   PORT_DIPSETTING(    0x10, "Color 40x25" )
276   PORT_DIPSETTING(    0x20, "Color 80x25" )
277   PORT_DIPSETTING(    0x30, "Monochrome" )
278   PORT_DIPNAME( 0x0c, 0x0c, "RAM banks")
279   PORT_DIPSETTING(    0x00, "1 - 16  64 256K" )
280   PORT_DIPSETTING(    0x04, "2 - 32 128 512K" )
281   PORT_DIPSETTING(    0x08, "3 - 48 192 576K" )
282   PORT_DIPSETTING(    0x0c, "4 - 64 256 640K" )
283   PORT_DIPNAME( 0x02, 0x00, "80387 installed")
284   PORT_DIPSETTING(    0x00, DEF_STR( No ) )
285   PORT_DIPSETTING(    0x02, DEF_STR( Yes ) )
286   PORT_DIPNAME( 0x01, 0x01, "Floppy installed")
287   PORT_DIPSETTING(    0x00, DEF_STR( No ) )
288   PORT_DIPSETTING(    0x01, DEF_STR( Yes ) )
289267INPUT_PORTS_END
290268
291269static INPUT_PORTS_START( atvga )
r249095r249096
302280   PORT_DIPNAME( 0x01, 0x01, "VGA 4")
303281   PORT_DIPSETTING(    0x01, DEF_STR( Off ) )
304282   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
305
306   PORT_START("DSW0")
307   PORT_DIPNAME( 0xc0, 0x40, "Number of floppy drives")
308   PORT_DIPSETTING(    0x00, "1" )
309   PORT_DIPSETTING(    0x40, "2" )
310   PORT_DIPSETTING(    0x80, "3" )
311   PORT_DIPSETTING(    0xc0, "4" )
312   PORT_DIPNAME( 0x30, 0x00, "Graphics adapter")
313   PORT_DIPSETTING(    0x00, "EGA/VGA" )
314   PORT_DIPSETTING(    0x10, "Color 40x25" )
315   PORT_DIPSETTING(    0x20, "Color 80x25" )
316   PORT_DIPSETTING(    0x30, "Monochrome" )
317   PORT_DIPNAME( 0x0c, 0x0c, "RAM banks")
318   PORT_DIPSETTING(    0x00, "1 - 16  64 256K" )
319   PORT_DIPSETTING(    0x04, "2 - 32 128 512K" )
320   PORT_DIPSETTING(    0x08, "3 - 48 192 576K" )
321   PORT_DIPSETTING(    0x0c, "4 - 64 256 640K" )
322   PORT_DIPNAME( 0x02, 0x00, "80387 installed")
323   PORT_DIPSETTING(    0x00, DEF_STR( No ) )
324   PORT_DIPSETTING(    0x02, DEF_STR( Yes ) )
325   PORT_DIPNAME( 0x01, 0x01, "Floppy installed")
326   PORT_DIPSETTING(    0x00, DEF_STR( No ) )
327   PORT_DIPSETTING(    0x01, DEF_STR( Yes ) )
328283INPUT_PORTS_END
329284
330285WRITE_LINE_MEMBER( at_state::at_mc146818_irq )
trunk/src/mess/drivers/besta.c
r249095r249096
1010
1111#include "emu.h"
1212#include "cpu/m68000/m68000.h"
13#include "machine/68230pit.h"
1314#include "machine/terminal.h"
1415
1516#define VERBOSE_DBG 1       /* general debug messages */
r249095r249096
3233   besta_state(const machine_config &mconfig, device_type type, const char *tag)
3334      : driver_device(mconfig, type, tag),
3435      m_maincpu(*this, "maincpu"),
36      m_pit1 (*this, "pit1"),
37      m_pit2 (*this, "pit2"),
3538      m_terminal(*this, TERMINAL_TAG),
3639      m_p_ram(*this, "p_ram")
3740   {
r249095r249096
4447   UINT8 m_mpcc_regs[32];
4548
4649   required_device<cpu_device> m_maincpu;
50   required_device<pit68230_device> m_pit1;
51   required_device<pit68230_device> m_pit2;
4752   virtual void machine_reset();
4853
4954   required_device<generic_terminal_device> m_terminal;
r249095r249096
96101
97102static ADDRESS_MAP_START(besta_mem, AS_PROGRAM, 32, besta_state)
98103   AM_RANGE(0x00000000, 0x001fffff) AM_RAM AM_SHARE("p_ram")       // local bus DRAM, 4MB
99//  AM_RANGE(0x08010000, 0x08011fff) AM_RAM                         // unknown -- accessed by cp31dssp
100   AM_RANGE(0xff000000, 0xff00ffff) AM_ROM AM_REGION("user1",0)    // actual mapping is up to 0xff03ffff
104//   AM_RANGE(0x08010000, 0x08011fff) AM_RAM                         // unknown -- accessed by cp31dssp
105//   AM_RANGE(0xfca03500, 0xfca0350f) AM_READWRITE8(iscsi_reg_r, iscsi_reg_w, 0xffffffff)
106   AM_RANGE(0xff000000, 0xff00ffff) AM_ROM AM_REGION("user1", 0)   // actual mapping is up to 0xff03ffff
101107   AM_RANGE(0xff040000, 0xff07ffff) AM_RAM                         // onboard SRAM
102//  68561 MPCC (console)
103//  AM_RANGE(0xff800000, 0xff80001f) AM_DEVREADWRITE8("mpcc", mpcc68561_t, reg_r, reg_w, 0xffffffff)
104   AM_RANGE(0xff800000, 0xff80001f) AM_READWRITE8(mpcc_reg_r, mpcc_reg_w, 0xffffffff)
105//  AM_RANGE(0xff800200, 0xff800xxx) // 68230 PIT2
106//  AM_RANGE(0xff800400, 0xff800xxx) // ??? -- shows up in cp31dssp log
107//  AM_RANGE(0xff800800, 0xff800xxx) // BIM
108//  AM_RANGE(0xff800a00, 0xff800xxx) // 62421 RTC
109//  AM_RANGE(0xff800c00, 0xff800xxx) // 68230 PIT
108//   AM_RANGE(0xff800000, 0xff80001f) AM_DEVREADWRITE8("mpcc", mpcc68561_t, reg_r, reg_w, 0xffffffff)
109   AM_RANGE(0xff800000, 0xff80001f) AM_READWRITE8(mpcc_reg_r, mpcc_reg_w, 0xffffffff) // console
110   AM_RANGE(0xff800200, 0xff800237) AM_DEVREADWRITE8 ("pit2", pit68230_device, read, write, 0xffffffff)
111//   AM_RANGE(0xff800400, 0xff800xxx) // ??? -- shows up in cp31dssp log
112//   AM_RANGE(0xff800800, 0xff800xxx) // 68153 BIM
113//   AM_RANGE(0xff800a00, 0xff800xxx) // 62421 RTC
114   AM_RANGE(0xff800c00, 0xff800c37) AM_DEVREADWRITE8 ("pit1", pit68230_device, read, write, 0xffffffff)
115//   AM_RANGE(0xff800e00, 0xff800xxx) // PIT3?
110116ADDRESS_MAP_END
111117
112118/* Input ports */
r249095r249096
131137   MCFG_CPU_ADD("maincpu", M68030, 2*16670000)
132138   MCFG_CPU_PROGRAM_MAP(besta_mem)
133139
140   MCFG_DEVICE_ADD ("pit1", PIT68230, 16670000 / 2)   // XXX verify clock
141
142   MCFG_DEVICE_ADD ("pit2", PIT68230, 16670000 / 2)   // XXX verify clock
143
134144   MCFG_DEVICE_ADD(TERMINAL_TAG, GENERIC_TERMINAL, 0)
135145   MCFG_GENERIC_TERMINAL_KEYBOARD_CB(WRITE8(besta_state, kbd_put))
136146MACHINE_CONFIG_END
r249095r249096
151161/* Driver */
152162
153163/*    YEAR  NAME    PARENT  COMPAT   MACHINE    INPUT                 INIT    COMPANY         FULLNAME       FLAGS */
154COMP( 1988, besta88,  0,      0,     besta,     besta,   driver_device,  0,  "Sapsan", "Besta-88", MACHINE_NOT_WORKING | MACHINE_NO_SOUND)
164COMP( 1988, besta88,  0,      0,     besta,     besta,   driver_device,  0,  "Sapsan", "Besta-88", MACHINE_NOT_WORKING | MACHINE_NO_SOUND_HW)
trunk/src/mess/drivers/canon_s80.c
r0r249096
1// license:GPL2+
2// copyright-holders:FelipeSanches
3/*
4 * canon_s80.c
5 *
6 *    CANON S-80 electronic typewriter
7 *
8 * skeleton driver by:
9 *    Felipe Correa da Silva Sanches <juca@members.fsf.org>
10 *
11 * known issues:
12 *  - memory-map is uncertain
13 *  - maincpu clock is guessed
14 *  - still need to hookup the Hitachi HD44780 LCD Controller
15 *  - still lacks description of the keyboard inputs
16 *  - as well as a "paper" device to plot the output of the dot matrix print head
17 */
18
19#include "emu.h"
20#include "cpu/m6800/m6800.h"
21//#include "video/hd44780.h"
22
23class canons80_state : public driver_device
24{
25public:
26   canons80_state(const machine_config &mconfig, device_type type, const char *tag)
27         : driver_device(mconfig, type, tag)
28         { }
29
30   DECLARE_DRIVER_INIT(canons80);
31};
32
33
34static ADDRESS_MAP_START(canons80_map, AS_PROGRAM, 8, canons80_state )
35    AM_RANGE(0x0000, 0x7fff) AM_RAM
36    AM_RANGE(0x8000, 0xffff) AM_ROM
37ADDRESS_MAP_END
38
39static MACHINE_CONFIG_START( canons80, canons80_state )
40   /* basic machine hardware */
41   MCFG_CPU_ADD("maincpu", HD6301, 5000000) /* hd63a01xop 5 MHz guessed: TODO: check on PCB */
42   MCFG_CPU_PROGRAM_MAP(canons80_map)
43MACHINE_CONFIG_END
44
45DRIVER_INIT_MEMBER(canons80_state, canons80)
46{}
47
48ROM_START( canons80 )
49   ROM_REGION( 0x10000, "maincpu", 0 ) /* 6800 code */
50   ROM_LOAD( "canon_8735kx_nh4-0029_064.ic6", 0x8000, 0x8000, CRC(b6cd2ff7) SHA1(e47a136300c826e480fac1be7fc090523078a2a6) )
51ROM_END
52
53/*    YEAR  NAME      PARENT  COMPAT   MACHINE  INPUT  INIT                      COMPANY  FULLNAME                            FLAGS */
54COMP( 1988, canons80,      0,      0, canons80,     0, canons80_state, canons80, "Canon", "Canon S-80 electronic typewriter", MACHINE_NOT_WORKING | MACHINE_NO_SOUND)
trunk/src/mess/drivers/dvk_kcgd.c
r0r249096
1/***************************************************************************
2
3    KCGD (Kontroller Cvetnogo Graficheskogo Displeya = Colour Graphics
4    Display Controller), a replacement for KSM (dvk_ksm.c) in later
5    models of DVK desktops.
6
7    MPI (Q-Bus clone) board. Interfaces with MS7004 (DEC LK201 workalike)
8    keyboard, mouse, and monochrome or color CRT.
9
10    To do:
11    - K1801VM2 CPU core (interrupts and EVNT pin, full EIS set, other insns)
12    - Everything else :-)
13
14****************************************************************************/
15
16#include "emu.h"
17
18#include "bus/rs232/rs232.h"
19#include "cpu/t11/t11.h"
20#include "machine/clock.h"
21#include "machine/ms7004.h"
22
23#define KCGD_TOTAL_HORZ 1000   // XXX verify
24#define KCGD_DISP_HORZ  800
25#define KCGD_HORZ_START 200   // XXX verify
26
27#define KCGD_TOTAL_VERT 600   // XXX verify
28#define KCGD_DISP_VERT  480
29#define KCGD_VERT_START 100   // XXX verify
30
31#define KCGD_STATUS_PAGE   0
32#define KCGD_STATUS_INTERLACE   1
33#define KCGD_STATUS_TIMER_INT   5
34#define KCGD_STATUS_MODE_INT   6
35#define KCGD_STATUS_MODE_LAST   7
36#define KCGD_STATUS_TIMER_VAL   15
37
38#define KCGD_PAGE_0   015574
39#define KCGD_PAGE_1   005574
40
41#define VERBOSE_DBG 1       /* general debug messages */
42
43#define DBG_LOG(N,M,A) \
44   do { \
45      if(VERBOSE_DBG>=N) \
46      { \
47         if( M ) \
48            logerror("%11.6f at %s: %-24s",machine().time().as_double(),machine().describe_context(),(char*)M ); \
49         logerror A; \
50      } \
51   } while (0)
52
53
54class kcgd_state : public driver_device
55{
56public:
57   kcgd_state(const machine_config &mconfig, device_type type, const char *tag) :
58      driver_device(mconfig, type, tag),
59      m_maincpu(*this, "maincpu"),
60//      m_ms7004(*this, "ms7004"),
61      m_palette(*this, "palette"),
62      m_screen(*this, "screen")
63   { }
64
65   virtual void machine_reset();
66   virtual void video_start();
67   UINT32 screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
68   TIMER_DEVICE_CALLBACK_MEMBER(scanline_callback);
69   DECLARE_PALETTE_INIT(kcgd);
70
71   enum
72   {
73      TIMER_ID_VSYNC_ON,
74      TIMER_ID_VSYNC_OFF,
75      TIMER_ID_500HZ
76   };
77   virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr);
78
79   DECLARE_WRITE_LINE_MEMBER(write_keyboard_clock);
80   DECLARE_WRITE_LINE_MEMBER(write_line_clock);
81
82   DECLARE_READ16_MEMBER(vram_addr_r);
83   DECLARE_READ16_MEMBER(vram_data_r);
84   DECLARE_READ16_MEMBER(vram_mmap_r);
85   DECLARE_WRITE16_MEMBER(vram_addr_w);
86   DECLARE_WRITE16_MEMBER(vram_data_w);
87   DECLARE_WRITE16_MEMBER(vram_mmap_w);
88   DECLARE_READ16_MEMBER(status_r);
89   DECLARE_WRITE16_MEMBER(status_w);
90   DECLARE_READ8_MEMBER(palette_index_r);
91   DECLARE_READ8_MEMBER(palette_data_r);
92   DECLARE_WRITE8_MEMBER(palette_index_w);
93   DECLARE_WRITE8_MEMBER(palette_data_w);
94
95   emu_timer *m_vsync_on_timer;
96   emu_timer *m_vsync_off_timer;
97   emu_timer *m_500hz_timer;
98
99private:
100   void draw_scanline(UINT16 *p, UINT16 offset);
101   rectangle m_tmpclip;
102   bitmap_ind16 m_tmpbmp;
103
104   struct {
105      UINT16 status;   // 167770
106      UINT8 control;   // 167772
107      int palette_index, vram_addr;
108      UINT8 palette[16];
109   } m_video;
110   UINT32 *m_videoram;
111
112protected:
113   required_device<cpu_device> m_maincpu;
114//   required_device<ms7004_device> m_ms7004;
115   required_device<palette_device> m_palette;
116   required_device<screen_device> m_screen;
117};
118
119static ADDRESS_MAP_START( kcgd_mem, AS_PROGRAM, 16, kcgd_state )
120   ADDRESS_MAP_UNMAP_HIGH
121   AM_RANGE (0000000, 0077777) AM_READWRITE(vram_mmap_r, vram_mmap_w)
122   AM_RANGE (0100000, 0157777) AM_ROM
123   AM_RANGE (0160000, 0160001) AM_MIRROR(03774) AM_READWRITE(vram_addr_r, vram_addr_w)
124   AM_RANGE (0160002, 0160003) AM_MIRROR(03774) AM_READWRITE(vram_data_r, vram_data_w)
125   AM_RANGE (0167770, 0167771) AM_READWRITE(status_r, status_w)
126   AM_RANGE (0167772, 0167773) AM_READWRITE8(palette_index_r, palette_index_w, 0x00ff)   // reads always return 0
127   AM_RANGE (0167772, 0167773) AM_READWRITE8(palette_data_r, palette_data_w, 0xff00)
128//   AM_RANGE (0176560, 0176567) AM_RAM   // USART2 -- host
129//   AM_RANGE (0177560, 0177567) AM_RAM   // USART3 -- keyboard
130ADDRESS_MAP_END
131
132void kcgd_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
133{
134   switch (id)
135   {
136/*
137   case TIMER_ID_VSYNC_ON:
138      m_maincpu->set_input_line(INPUT_LINE_EVNT, ASSERT_LINE);
139      break;
140
141   case TIMER_ID_VSYNC_OFF:
142      m_maincpu->set_input_line(INPUT_LINE_EVNT, CLEAR_LINE);
143      break;
144*/
145   case TIMER_ID_500HZ:
146      m_video.status ^= (1 << KCGD_STATUS_TIMER_VAL);
147      break;
148   }
149}
150
151void kcgd_state::machine_reset()
152{
153   memset(&m_video, 0, sizeof(m_video));
154}
155
156void kcgd_state::video_start()
157{
158//   screen_device *screen = machine().device<screen_device>("screen");
159
160   // 64 kwords, word size is 17 bits
161   m_videoram = auto_alloc_array(machine(), UINT32, 65536);
162
163   m_tmpclip = rectangle(0, KCGD_DISP_HORZ-1, 0, KCGD_DISP_VERT-1);
164   m_tmpbmp.allocate(KCGD_DISP_HORZ, KCGD_DISP_VERT);
165/*
166   m_vsync_on_timer = timer_alloc(TIMER_ID_VSYNC_ON);
167   m_vsync_on_timer->adjust(screen->time_until_pos(0, 0), 0, screen->frame_period());
168
169   m_vsync_off_timer = timer_alloc(TIMER_ID_VSYNC_OFF);
170   m_vsync_off_timer->adjust(screen->time_until_pos(16, 0), 0, screen->frame_period());
171*/
172   m_500hz_timer = timer_alloc(TIMER_ID_500HZ);
173   m_500hz_timer->adjust(attotime::from_hz(500), 0, attotime::from_hz(500));
174}
175
176PALETTE_INIT_MEMBER(kcgd_state, kcgd)
177{
178   for (int i = 0; i < 16; i++)
179   {
180      palette.set_pen_color(i, i?i:255, i?i:255, i?i:255);
181   }
182}
183
184/*
185   VRAM is 128K and is word-addressable, so address fits into 16 bits.
186   Low 32K of VRAM are not used to store pixel data -- XXX.
187*/
188WRITE16_MEMBER(kcgd_state::vram_addr_w)
189{
190   DBG_LOG(3,"VRAM WA", ("%06o\n", data));
191   m_video.vram_addr = data;
192}
193
194READ16_MEMBER(kcgd_state::vram_addr_r)
195{
196   DBG_LOG(3,"VRAM RA", ("\n"));
197   return m_video.vram_addr;
198}
199
200WRITE16_MEMBER(kcgd_state::vram_data_w)
201{
202   DBG_LOG(1,"VRAM W2", ("%06o <- %04XH\n", m_video.vram_addr, data));
203   m_videoram[m_video.vram_addr] = data | (BIT(m_video.control, 7) << 16);
204}
205
206READ16_MEMBER(kcgd_state::vram_data_r)
207{
208   DBG_LOG(2,"VRAM R2", ("%06o\n", m_video.vram_addr));
209   m_video.status = (m_video.status & 0xff7f) | (BIT(m_videoram[m_video.vram_addr], 16) << 7);
210   return (UINT16) (m_videoram[m_video.vram_addr] & 0xffff);
211}
212
213WRITE16_MEMBER(kcgd_state::vram_mmap_w)
214{
215   DBG_LOG(3,"VRAM W1", ("%06o <- %04XH\n", offset, data));
216   m_videoram[offset] = data | (BIT(m_video.control, 7) << 16);
217}
218
219READ16_MEMBER(kcgd_state::vram_mmap_r)
220{
221   DBG_LOG(3,"VRAM R1", ("%06o\n", offset));
222   return (UINT16) (m_videoram[offset] & 0xffff);
223}
224
225WRITE16_MEMBER(kcgd_state::status_w)
226{
227   DBG_LOG(1,"Status W", ("data %04XH (useful %02XH)\n", data, data & 0x63));
228   // bits 7 and 15 are read-only
229   m_video.status = (m_video.status & 0x8080) | (data & 0x7f7f);
230}
231
232READ16_MEMBER(kcgd_state::status_r)
233{
234   UINT16 data = m_video.status ^ (BIT(m_video.control, 6) << 7);
235   DBG_LOG(1,"Status R", ("data %04X index %d\n", data, m_video.palette_index));
236   return data;
237}
238
239WRITE8_MEMBER(kcgd_state::palette_index_w)
240{
241   m_video.control = data;
242   m_video.palette_index = ((data >> 2) & 15);
243   DBG_LOG(1,"Palette index, Control W", ("data %02XH index %d\n", data, m_video.palette_index));
244}
245
246WRITE8_MEMBER(kcgd_state::palette_data_w)
247{
248   DBG_LOG(1,"Palette data W", ("data %02XH index %d\n", data, m_video.palette_index));
249   m_video.palette[m_video.palette_index] = data;
250   m_palette->set_pen_color(m_video.palette_index,
251      85*(data & 3), 85*((data >> 2) & 3), 85*((data >> 4) & 3));
252}
253
254READ8_MEMBER(kcgd_state::palette_index_r)
255{
256   return 0;
257}
258
259READ8_MEMBER(kcgd_state::palette_data_r)
260{
261   DBG_LOG(1,"Palette data R", ("index %d\n", m_video.palette_index));
262   return m_video.palette[m_video.palette_index];
263}
264
265/*
266    Raster sizes are:
267    - 800(400)x480 in hires(lores) 60 Hz interlaced mode
268    - 800(400)x240 in hires(lores) 30 Hz progressive mode
269
270    Video memory is 17 bits wide (bit 16 indicates hi/lo res mode for each word,
271    host writes it separately (via bit 7 in 167772).
272*/
273
274void kcgd_state::draw_scanline(UINT16 *p, UINT16 offset)
275{
276   int i;
277
278   for ( i = 0; i < 100; i++ )
279   {
280      UINT32 data = m_videoram[ offset++ ];
281      if (BIT(data, 16)) {
282         *p = ( data >> 12) & 0x0F; p++;
283         *p = ( data >> 12) & 0x0F; p++;
284         *p = ( data >> 8 ) & 0x0F; p++;
285         *p = ( data >> 8 ) & 0x0F; p++;
286         *p = ( data >> 4 ) & 0x0F; p++;
287         *p = ( data >> 4 ) & 0x0F; p++;
288         *p =   data        & 0x0F; p++;
289         *p =   data        & 0x0F; p++;
290      } else {
291         *p = 5*(( data >> 14) & 0x03); p++;
292         *p = 5*(( data >> 12) & 0x03); p++;
293         *p = 5*(( data >> 10) & 0x03); p++;
294         *p = 5*(( data >> 8 ) & 0x03); p++;
295         *p = 5*(( data >> 6 ) & 0x03); p++;
296         *p = 5*(( data >> 4 ) & 0x03); p++;
297         *p = 5*(( data >> 2 ) & 0x03); p++;
298         *p = 5*(  data        & 0x03); p++;
299      }
300   }
301}
302
303TIMER_DEVICE_CALLBACK_MEMBER(kcgd_state::scanline_callback)
304{
305   UINT16 y = m_screen->vpos(), offset;
306
307   if (y < KCGD_VERT_START) return;
308   y -= KCGD_VERT_START;
309   if (y >= KCGD_DISP_VERT) return;
310
311   offset = BIT(m_video.status, KCGD_STATUS_PAGE) ? (KCGD_PAGE_1 >> 1) : (KCGD_PAGE_0 >> 1);
312
313   DBG_LOG(2,"scanline_cb", ("frame %" I64FMT "d y %.3d page %d offset %04X *offset %04X\n",
314      m_screen->frame_number(), BIT(m_video.status, KCGD_STATUS_PAGE),
315      y, offset + y, m_videoram[offset + y]));
316
317   draw_scanline(&m_tmpbmp.pix16(y), m_videoram[offset + (KCGD_DISP_VERT-1) - y]);
318}
319
320UINT32 kcgd_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
321{
322   copybitmap(bitmap, m_tmpbmp, 0, 0, KCGD_HORZ_START, KCGD_VERT_START, cliprect);
323   return 0;
324}
325
326/* F4 Character Displayer */
327static const gfx_layout kcgd_charlayout =
328{
329   8, 10,                  /* 8x10 pixels */
330   256,                    /* 256 characters */
331   1,                      /* 1 bits per pixel */
332   { 0 },                  /* no bitplanes */
333   /* x offsets */
334   { 0, 1, 2, 3, 4, 5, 6, 7 },
335   /* y offsets */
336   { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8 },
337   8*10                    /* every char takes 10 bytes */
338};
339
340static GFXDECODE_START( kcgd )
341   GFXDECODE_ENTRY("maincpu", 0112236, kcgd_charlayout, 0, 1)
342GFXDECODE_END
343
344static MACHINE_CONFIG_START( kcgd, kcgd_state )
345   MCFG_CPU_ADD("maincpu", K1801VM2, XTAL_30_8MHz/4)
346   MCFG_CPU_PROGRAM_MAP(kcgd_mem)
347   MCFG_T11_INITIAL_MODE(0100000)
348
349   MCFG_TIMER_DRIVER_ADD_PERIODIC("scantimer", kcgd_state, scanline_callback, attotime::from_hz(50*28*11)) // XXX verify
350   MCFG_TIMER_START_DELAY(attotime::from_hz(XTAL_30_8MHz/KCGD_HORZ_START))
351
352   MCFG_SCREEN_ADD("screen", RASTER)
353   MCFG_SCREEN_UPDATE_DRIVER(kcgd_state, screen_update)
354   MCFG_SCREEN_RAW_PARAMS(XTAL_30_8MHz, KCGD_TOTAL_HORZ, KCGD_HORZ_START,
355      KCGD_HORZ_START+KCGD_DISP_HORZ, KCGD_TOTAL_VERT, KCGD_VERT_START,
356      KCGD_VERT_START+KCGD_DISP_VERT);
357
358   MCFG_SCREEN_PALETTE("palette")
359   MCFG_PALETTE_ADD("palette", 16)
360   MCFG_PALETTE_INIT_OWNER(kcgd_state, kcgd)
361
362   MCFG_GFXDECODE_ADD("gfxdecode", "palette", kcgd)
363#if 0
364   MCFG_DEVICE_ADD("ms7004", MS7004, 0)
365   MCFG_MS7004_TX_HANDLER(DEVWRITELINE("i8251kbd", i8251_device, write_rxd))
366
367   MCFG_DEVICE_ADD("keyboard_clock", CLOCK, 4800*16)
368   MCFG_CLOCK_SIGNAL_HANDLER(WRITELINE(kcgd_state, write_keyboard_clock))
369#endif
370MACHINE_CONFIG_END
371
372ROM_START( dvk_kcgd )
373   ROM_REGION16_BE(0x100000,"maincpu", ROMREGION_ERASE00)
374   ROM_DEFAULT_BIOS("181")
375   ROM_SYSTEM_BIOS(0, "181", "mask 181")
376   ROMX_LOAD("kr1801re2-181.bin", 0100000, 020000, CRC(acac124f) SHA1(412c3eb71bece6f791fc5a9d707cf4692fd0b45b), ROM_BIOS(1))
377   ROM_SYSTEM_BIOS(1, "182", "mask 182")
378   ROMX_LOAD("kr1801re2-182.bin", 0100000, 020000, CRC(3ca2921a) SHA1(389b30c40ed7e41dae71d58c7bff630359a48153), ROM_BIOS(2))
379ROM_END
380
381/* Driver */
382
383/*    YEAR  NAME      PARENT  COMPAT   MACHINE    INPUT    INIT                      COMPANY     FULLNAME       FLAGS */
384COMP( 1987, dvk_kcgd, 0,      0,       kcgd,      0,       driver_device,     0,     "USSR",     "DVK KCGD",    MACHINE_NOT_WORKING | MACHINE_NO_SOUND_HW )
trunk/src/mess/drivers/force68k.c
r249095r249096
1// license:BSD-3-Clause
1// license:BSD-3-Clause
22// copyright-holders:Joakim Larsson Edstr??m
33/***************************************************************************
4 *
5 *  Force SYS68K CPU-1/CPU-6 VME SBC drivers, initially based on the 68ksbc.c
6 *
7 *  13/06/2015
8 *
9 * The info found on the links below is for a later revisions of the board I have
10 * but it is somewhat compatible so I got the system ROM up and running in terminal.
11 * My CPU-1 board has proms from 1983 and the PCB has no rev markings so probably
12 * the original or a very early design. The board real estate differs from the later
13 * CPU-1:s I found pictures of but has the same main chips and functions.
14 *
15 * http://bitsavers.trailing-edge.com/pdf/forceComputers/1988_Force_VMEbus_Products.pdf
16 * http://www.artisantg.com/info/P_wUovN.pdf
17 *
18 * Some info from those documents:
19 *
20 * Address Map
21 * ----------------------------------------------------------
22 * Address Range     Description
23 * ----------------------------------------------------------
24 * 000 000 - 000 007 Initialisation vectors from system EPROM
25 * 000 008 - 01F FFF Dynamic RAM on CPU-1 B
26 * 000 008 - 07F FFF Dynamic RAM on CPU-1 D
27 * 080 008 - 09F FFF SYSTEM EPROM Area
28 * OAO 000 - OBF FFF USER EPROMArea
29 * 0C0 041 - 0C0 043 ACIA (P3) Host
30 * 0C0 080 - 0C0 082 ACIA (P4) Terminal
31 * 0C0 101 - 0C0 103 ACIA (P5) Remote device (eg serial printer)
32 * 0C0 401 - 0C0 42F RTC
33 * OEO 001 - 0E0 035 PI/T (eg centronics printer)
34 * OEO 200 - 0E0 2FF FPU
35 * OEO 300 - 0E0 300 Reset Off
36 * OEO 380 - 0E0 380 Reset On
37 * 100 000 - FEF FFF VMEbus addresses (A24)
38 * FFO 000 - FFF FFF VMEbus Short I/O (A16)
39 * ----------------------------------------------------------
40 *
41 * Interrupt sources
42 * ----------------------------------------------------------
43 * Description                  Device  Lvl  IRQ    VME board
44 *                           /Board      Vector  Address
45 * ----------------------------------------------------------
46 * On board Sources
47 * ABORT                        Switch  7    31
48 * Real Time Clock (RTC)        58167A  6    30
49 * Parallel/Timer (PI/T)        68230   5    29
50 * Terminal ACIA                6850    4    28
51 * Remote ACIA                  6850    3    27
52 * Host ACIA                    6850    2    26
53 * ACFAIL, SYSFAIL              VME     5    29
54 * Off board Sources (other VME boards)
55 * 6 Port Serial I/O board      SIO     4    64-75  0xb00000
56 * 8 Port Serial I/O board      ISIO    4    76-83  0x960000
57 * Disk Controller              WFC     3    119    0xb01000
58 * SCSI Controller              ISCSI   4    119    0xa00000
59 * Slot 1 Controller Board      ASCU    7    31     0xb02000
60 * ----------------------------------------------------------
61 *
62 *  TODO:
63 *  - Finish 3 x ACIA6850, host and remote interface left, terminal works
64 *  - Finish 1 x 68230 Motorola, Parallel Interface / Timer as required by ROM
65 *    - Configure PIT to the Centronics device printer interface as
66 *      supported by ROM (DONE)
67 *  - Add 1 x Abort Switch
68 *  - Add 1 x Reset Switch
69 *  - Add 1 x Halt LED
70 *  - Add a jumper field device as supported by PCB
71 *  - Add configurable serial connector between ACIA:s and
72 *    - Real terminal emulator, ie rs232 "socket"
73 *    - Debug console
74 *  - Add VME bus driver
75 *
76 ****************************************************************************/
477
5    Force SYS68K CPU-1/CPU-6 VME SBC drivers, initially based on the 68ksbc.c
6
7    13/06/2015
8
9 The info found on the links below is for a later revisions of the board I have
10 but I hope it is somewhat compatible so I can get it up and running at least.
11 My CPU-1 board has proms from 1983 and no rev markings so probably the original.
12
13 http://bitsavers.trailing-edge.com/pdf/forceComputers/1988_Force_VMEbus_Products.pdf
14 http://www.artisantg.com/info/P_wUovN.pdf
15
16 Some info from those documents:
17
18Address Map
19----------------------------------------------------------
20Address Range     Description
21----------------------------------------------------------
22000 000 - 000 007 Initialisation vectors from system EPROM
23000 008 - 01F FFF Dynamic RAM on CPU-1 B
24000 008 - 07F FFF Dynamic RAM on CPU-1 D
25080 008 - 09F FFF SYSTEM EPROM Area
26OAO 000 - OBF FFF USER EPROMArea
270C0 041 - 0C0 043 ACIA (P3) Host
280C0 080 - 0C0 082 ACIA (P4) Terminal
290C0 101 - 0C0 103 ACIA (P5) Remote device (eg serial printer)
300C0 401 - 0C0 42F RTC
31OEO 001 - 0E0 035 PI/T (eg centronics printer)
32OEO 200 - 0E0 2FF FPU
33OEO 300 - 0E0 300 Reset Off
34OEO 380 - 0E0 380 Reset On
35100 000 - FEF FFF VMEbus addresses (A24)
36FFO 000 - FFF FFF VMEbus Short I/O (A16)
37----------------------------------------------------------
38
39Interrupt sources
40----------------------------------------------------------
41Description                  Device  Lvl  IRQ    VME board
42                             /Board      Vector  Address
43----------------------------------------------------------
44On board Sources
45 ABORT                        Switch  7    31
46 Real Time Clock (RTC)        58167A  6    30
47 Parallel/Timer (PI/T)        68230   5    29
48 Terminal ACIA                6850    4    28
49 Remote ACIA                  6850    3    27
50 Host ACIA                    6850    2    26
51 ACFAIL, SYSFAIL              VME     5    29
52Off board Sources (other VME boards)
53 6 Port Serial I/O board      SIO     4    64-75  0xb00000
54 8 Port Serial I/O board      ISIO    4    76-83  0x960000
55 Disk Controller              WFC     3    119    0xb01000
56 SCSI Controller              ISCSI   4    119    0xa00000
57 Slot 1 Controller Board      ASCU    7    31     0xb02000
58----------------------------------------------------------
59
6010. The VMEbus
61---------------
62The implemented VMEbus Interface includes 24 address, 16 data,
636 address modifier and the asynchronous control signals.
64A single level bus arbiter is provided to build multi master
65systems. In addition to the bus arbiter, a separate slave bus
66arbitration allows selection of the arbitration level (0-3).
67
68The address modifier range .,Short 110 Access?? can be selected
69via a jumper for variable system generation. The 7 interrupt
70request levels of the VMEbus are fully supported from the
71SYS68K1CPU-1 B/D. For multi-processing, each IRQ signal can be
72enabled/disabled via a jumper field.
73
74Additionally, the SYS68K1CPU-1 B/D supports the ACFAIL, SYSRESET,
75SYSFAIL and SYSCLK signal (16 MHz).
76
77
78    TODO:
79    - Finish 2 x ACIA6850, host and remote interface left, terminal works
80    - Finish 1 x 68230 Motorola, Parallel Interface / Timer
81      - Connect Port B to a Centronics printer interface
82    - Add 1 x Abort Switch
83    - Add configurable serial connector between ACIA:s and
84      - Real terminal emulator, ie rs232 "socket"
85      - Debug console
86    - Add VME bus driver
87
88****************************************************************************/
89
9078#include "emu.h"
9179#include "bus/rs232/rs232.h"
9280#include "cpu/m68000/m68000.h"
r249095r249096
9482#include "machine/68230pit.h"
9583#include "machine/6850acia.h"
9684#include "machine/clock.h"
85#include "bus/centronics/ctronics.h"
86#include "bus/generic/slot.h"
87#include "bus/generic/carts.h"
9788
89#define LOG(x) x
90
9891#define BAUDGEN_CLOCK XTAL_1_8432MHz
9992/*
100 The baudrate on the Force68k CPU-1 to CPU-6 is generated by a
101 Motorola 14411 bitrate generator, the CPU-6 documents matches the circuits
102 that I could find on the CPU-1 board. Here how I calculated the clock for
103 the factory settings. No need to add selectors until terminal.c supports
104 configurable baudrates. Fortunality CPU-1 was shipped with 9600N8!
105
106 From the documents:
107
108  3 RS232C interfaces, strap selectable baud rate from 110-9600 or 600-19200 baud
109
110  Default Jumper Settings of B7:
111  --------------------------------
112  GND           10 - 11 RSA input on 14411
113  F1 on 14411    1 - 20 Baud selector of the terminal port
114  F1 on 14411    3 - 18 Baud selector of the host port
115  F1 on 14411    5 - 16 Baud selector of the remote port
116
117 The RSB input on the 14411 is kept high always so RSA=0, RSB=1 and a 1.8432MHz crystal
118 generates 153600 on the F1 output pin which by default strapping is connected to all
119 three 6850 acias on the board. These can be strapped separatelly to speedup downloads.
120
121 The selectable outputs from 14411, F1-F16:
122 X16 RSA=0,RSB=1: 153600, 115200, 76800, 57600, 38400, 28800, 19200, 9600, 4800, 3200, 2153.3, 1758.8, 1200, 921600, 1843000
123 X64 RSA=1,RSB=1: 614400, 460800, 307200, 230400, 153600, 115200, 76800, 57600, 38400, 28800, 19200, 9600, 4800, 921600, 1843000
124
125 However, the datasheet says baudrate is strapable for 110-9600 but the output is 153600
126 so the system rom MUST setup the acia to divide by 16 to generate the correct baudrate.
127
128*/
93 * The baudrate on the Force68k CPU-1 to CPU-6 is generated by a
94 * Motorola 14411 bitrate generator, the CPU-6 documents matches the circuits
95 * that I could find on the CPU-1 board. Here how I calculated the clock for
96 * the factory settings. No need to add selectors until terminal.c supports
97 * configurable baudrates. Fortunality CPU-1 was shipped with 9600N8!
98 *
99 * From the documents:
100 *
101 * 3 RS232C interfaces, strap selectable baud rate from 110-9600 or 600-19200 baud
102 *
103 * Default Jumper Settings of B7:
104 * --------------------------------
105 * GND           10 - 11 RSA input on 14411
106 * F1 on 14411    1 - 20 Baud selector of the terminal port
107 * F1 on 14411    3 - 18 Baud selector of the host port
108 * F1 on 14411    5 - 16 Baud selector of the remote port
109 *
110 * The RSB input on the 14411 is kept high always so RSA=0, RSB=1 and a 1.8432MHz crystal
111 * generates 153600 on the F1 output pin which by default strapping is connected to all
112 * three 6850 acias on the board. These can be strapped separatelly to speedup downloads.
113 *
114 * The selectable outputs from 14411, F1-F16:
115 * X16 RSA=0,RSB=1: 153600, 115200, 76800, 57600, 38400, 28800, 19200, 9600, 4800, 3200, 2153.3, 1758.8, 1200, 921600, 1843000
116 * X64 RSA=1,RSB=1: 614400, 460800, 307200, 230400, 153600, 115200, 76800, 57600, 38400, 28800, 19200, 9600, 4800, 921600, 1843000
117 *
118 * However, the datasheet says baudrate is strapable for 110-9600 but the output is 153600
119 * so the system rom MUST setup the acia to divide by 16 to generate the correct baudrate.
120 *
121 */
129122#define ACIA_CLOCK (BAUDGEN_CLOCK / 12)
130123
131124class force68k_state : public driver_device
132125{
133126public:
134   force68k_state(const machine_config &mconfig, device_type type, const char *tag) :
135      driver_device(mconfig, type, tag),
136         //      m_rtc(*this, "rtc")
137         m_maincpu(*this, "maincpu"),
138         m_rtc(*this, "rtc"),
139         m_pit(*this, "pit"),
140         m_aciahost(*this, "aciahost"),
141         m_aciaterm(*this, "aciaterm"),
142         m_aciaremt(*this, "aciaremt")
143   {
144   }
127force68k_state(const machine_config &mconfig, device_type type, const char *tag) :
128        driver_device (mconfig, type, tag),
129        m_maincpu (*this, "maincpu"),
130        m_rtc (*this, "rtc"),
131        m_pit (*this, "pit"),
132        m_aciahost (*this, "aciahost"),
133        m_aciaterm (*this, "aciaterm"),
134        m_aciaremt (*this, "aciaremt"),
135        m_centronics (*this, "centronics")
136        , m_centronics_ack (0)
137        , m_centronics_busy (0)
138        , m_centronics_perror (0)
139        , m_centronics_select (0)
140        ,m_cart(*this, "exp_rom1")
141{
142}
145143
146   DECLARE_READ16_MEMBER(bootvect_r);
147   virtual void machine_start();
148   DECLARE_WRITE_LINE_MEMBER(write_aciahost_clock);
149   DECLARE_WRITE_LINE_MEMBER(write_aciaterm_clock);
150   DECLARE_WRITE_LINE_MEMBER(write_aciaremt_clock);
144DECLARE_READ16_MEMBER (bootvect_r);
145DECLARE_READ16_MEMBER (vme_a24_r);
146DECLARE_WRITE16_MEMBER (vme_a24_w);
147DECLARE_READ16_MEMBER (vme_a16_r);
148DECLARE_WRITE16_MEMBER (vme_a16_w);
149virtual void machine_start ();
150// clocks
151DECLARE_WRITE_LINE_MEMBER (write_aciahost_clock);
152DECLARE_WRITE_LINE_MEMBER (write_aciaterm_clock);
153DECLARE_WRITE_LINE_MEMBER (write_aciaremt_clock);
154// centronics printer interface
155DECLARE_WRITE_LINE_MEMBER (centronics_ack_w);
156DECLARE_WRITE_LINE_MEMBER (centronics_busy_w);
157DECLARE_WRITE_LINE_MEMBER (centronics_perror_w);
158DECLARE_WRITE_LINE_MEMBER (centronics_select_w);
159// User EPROM/SRAM slot(s)
160int force68k_load_cart(device_image_interface &image, generic_slot_device *slot);
161DECLARE_DEVICE_IMAGE_LOAD_MEMBER (exp1_load) { return force68k_load_cart(image, m_cart); }
162DECLARE_READ16_MEMBER (read16_rom);
151163
164protected:
165
152166private:
153   required_device<cpu_device> m_maincpu;
154   required_device<mm58167_device> m_rtc;
155   required_device<pit68230_device> m_pit;
156   required_device<acia6850_device> m_aciahost;
157   required_device<acia6850_device> m_aciaterm;
158   required_device<acia6850_device> m_aciaremt;
167required_device<cpu_device> m_maincpu;
168required_device<mm58167_device> m_rtc;
169required_device<pit68230_device> m_pit;
170required_device<acia6850_device> m_aciahost;
171required_device<acia6850_device> m_aciaterm;
172required_device<acia6850_device> m_aciaremt;
173optional_device<centronics_device> m_centronics;
159174
160   // Pointer to System ROMs needed by bootvect_r
161   UINT16  *m_sysrom;
175INT32 m_centronics_ack;
176INT32 m_centronics_busy;
177INT32 m_centronics_perror;
178INT32 m_centronics_select;
179
180// Pointer to System ROMs needed by bootvect_r
181UINT16  *m_sysrom;
182UINT16  *m_usrrom;
183
184required_device<generic_slot_device> m_cart;
185
162186};
163187
164static ADDRESS_MAP_START(force68k_mem, AS_PROGRAM, 16, force68k_state)
165      ADDRESS_MAP_UNMAP_HIGH
166      AM_RANGE(0x000000, 0x000007) AM_ROM AM_READ(bootvect_r) /* Vectors mapped from System EPROM */
167      AM_RANGE(0x000008, 0x01ffff) AM_RAM /* DRAM */
168      AM_RANGE(0x080000, 0x09ffff) AM_ROM /* System EPROM Area */
169//  AM_RANGE(0x0a0000, 0x0bffff) AM_ROM /* User EPROM Area   */
170   AM_RANGE(0x0c0040, 0x0c0041) AM_DEVREADWRITE8("aciahost", acia6850_device, status_r, control_w, 0x00ff)
171   AM_RANGE(0x0c0042, 0x0c0043) AM_DEVREADWRITE8("aciahost", acia6850_device, data_r, data_w, 0x00ff)
172   AM_RANGE(0x0c0080, 0x0c0081) AM_DEVREADWRITE8("aciaterm", acia6850_device, status_r, control_w, 0xff00)
173   AM_RANGE(0x0c0082, 0x0c0083) AM_DEVREADWRITE8("aciaterm", acia6850_device, data_r, data_w, 0xff00)
174   AM_RANGE(0x0c0100, 0x0c0101) AM_DEVREADWRITE8("aciaremt", acia6850_device, status_r, control_w, 0x00ff)
175   AM_RANGE(0x0c0102, 0x0c0103) AM_DEVREADWRITE8("aciaremt", acia6850_device, data_r, data_w, 0x00ff)
176      AM_RANGE(0x0c0400, 0x0c042f) AM_DEVREADWRITE8("rtc", mm58167_device, read, write, 0x00ff)
177      AM_RANGE(0x0e0000, 0x0e0035) AM_DEVREADWRITE8("pit", pit68230_device, data_r, data_w, 0x00ff)
188static ADDRESS_MAP_START (force68k_mem, AS_PROGRAM, 16, force68k_state)
189ADDRESS_MAP_UNMAP_HIGH
190AM_RANGE (0x000000, 0x000007) AM_ROM AM_READ (bootvect_r)       /* Vectors mapped from System EPROM */
191AM_RANGE (0x000008, 0x01ffff) AM_RAM /* DRAM CPU-1B */
192//AM_RANGE (0x020000, 0x07ffff) AM_RAM /* Additional DRAM CPU-1D */
193AM_RANGE (0x080000, 0x083fff) AM_ROM /* System EPROM Area 16Kb DEBUGGER supplied as default on CPU-1B/D     */
194AM_RANGE (0x084000, 0x09ffff) AM_ROM /* System EPROM Area 112Kb additional space for System ROM     */
195//AM_RANGE (0x0a0000, 0x0bffff) AM_ROM /* User EPROM/SRAM Area, max 128Kb mapped by a cartslot  */
196AM_RANGE (0x0c0040, 0x0c0041) AM_DEVREADWRITE8 ("aciahost", acia6850_device, status_r, control_w, 0x00ff)
197AM_RANGE (0x0c0042, 0x0c0043) AM_DEVREADWRITE8 ("aciahost", acia6850_device, data_r, data_w, 0x00ff)
198AM_RANGE (0x0c0080, 0x0c0081) AM_DEVREADWRITE8 ("aciaterm", acia6850_device, status_r, control_w, 0xff00)
199AM_RANGE (0x0c0082, 0x0c0083) AM_DEVREADWRITE8 ("aciaterm", acia6850_device, data_r, data_w, 0xff00)
200AM_RANGE (0x0c0100, 0x0c0101) AM_DEVREADWRITE8 ("aciaremt", acia6850_device, status_r, control_w, 0x00ff)
201AM_RANGE (0x0c0102, 0x0c0103) AM_DEVREADWRITE8 ("aciaremt", acia6850_device, data_r, data_w, 0x00ff)
202AM_RANGE (0x0c0400, 0x0c042f) AM_DEVREADWRITE8 ("rtc", mm58167_device, read, write, 0x00ff)
203AM_RANGE (0x0e0000, 0x0e0035) AM_DEVREADWRITE8 ("pit", pit68230_device, read, write, 0x00ff)
178204//      AM_RANGE(0x0e0200, 0x0e0380) AM_READWRITE(fpu_r, fpu_w) /* optional FPCP 68881 FPU interface */
179//      AM_RANGE(0x100000, 0xfeffff) /* VMEbus Rev B addresses (24 bits) */
180//      AM_RANGE(0xff0000, 0xffffff) /* VMEbus Rev B addresses (16 bits) */
205AM_RANGE(0x100000, 0xfeffff)  AM_READWRITE(vme_a24_r, vme_a24_w) /* VMEbus Rev B addresses (24 bits) */
206AM_RANGE(0xff0000, 0xffffff)  AM_READWRITE(vme_a16_r, vme_a16_w) /* VMEbus Rev B addresses (16 bits) */
181207ADDRESS_MAP_END
182208
183209/* Input ports */
184static INPUT_PORTS_START( force68k )
210static INPUT_PORTS_START (force68k)
185211INPUT_PORTS_END
186212
187void force68k_state::machine_start()
213/*
214 *  Centronics support
215 *
216 *  The system ROMs has support for a parallel printer interface but the signals are just routed to row A
217 *  of the VME P2 connector so no on board Centronics connector is available but assumed to be added on a
218 *  separate I/O board. After some detective work I found that the ROM works as follows:
219 *
220 *  The 'PA' (Printer Attach) command issues a <cr> on Port A and sends a strobe on H2 it then loops over
221 *  the select signal, bit 0 on Port B, and the ack signal on HS1, both to be non zero. The support is really
222 *  flawed as the strobe signal goes high instead of low ( this might assume an inverting driver on the
223 *  P2 board ) and the busy signal is not checked at all. Or I might have assumed it all wrong, but it now
224 *  works with the generic centronics printer driver. Need the printer board documentation to improve further.
225 *
226 *  When the 'PA' command is successful everything printed to screen is mirrored on the printer. Use the
227 *  'NOPA' command to stop mirroring. I had no printer ROMs so could not test it with a "real" printer.
228 *
229 *  Force CPU-1 init sequence for MC68230 PIT
230 *  -----------------------------------------
231 *  0801E6 0E0000 W 00 -> PGCR  Mode 0 (uni8), H34 dis, H12 dis, H1234 HZ
232 *  0801E6 0E0002 W 00 -> PSRR  PC4, PC5, H1S>H2S>H3S>H4S
233 *  0801E6 0E0004 W FF -> PADDR Port A all Outputs
234 *  0801E6 0E0006 W 00 -> PBDDR Port B all Inputs
235 *  0801EA 0E000C W 60 -> PACR  Port A Mode 01, pin def, dbfr H1 data rec, H2 status/int, H2 output neg, H2S clrd
236 *  0801F0 0E000E W A0 -> PBCR  Port B mode 1x, H4 output neg, H4S clrd, H3 int dis, H3 edg input, H3S set by assrt edg
237 *  0801F6 0E0000 W 30 -> PGCR  H34 enable, H12enable
238 *  0801FC 0E000E W A8 -> PBCR  +H4 asserted
239 *  08020A 0E000E W A0 -> PBCR  +H4 negated
240 *
241 *  Upon PA (Printer Attach) command enabling the Centronics printer mode
242 *  ---------------------------------------------------------------------
243 *  081DB4 0E0011 W D0 -> PADR  Data to Port A
244 *  081DB8 0E000D W 68 -> PACR  H2 output asserted Centronics Strobe
245 *  081DC0 0E000D W 60 -> PACR  H2 output negated
246 *  081DD0 0E0013 R 00 <- PBDR  Port B polled for 01 (data) & 03 (mask)
247 *
248 */
249
250/* Centronics ACK handler
251 * The centronics ack signal is expected by the ROM to arrive at H1 input line
252 */
253WRITE_LINE_MEMBER (force68k_state::centronics_ack_w)
188254{
189   m_sysrom = (UINT16*)(memregion("maincpu")->base() + 0x080000);
255//      LOG (logerror ("centronics_ack_w(%d) %lld\n", state, m_maincpu->total_cycles ()));
256        m_centronics_ack = state;
257        m_pit->h1_set (state);
190258}
191259
192READ16_MEMBER(force68k_state::bootvect_r)
193{
194      return m_sysrom[offset];
260/* Centronics BUSY handler
261 * The centronics busy signal is not used by the ROM driver afaik
262 */
263WRITE_LINE_MEMBER (force68k_state::centronics_busy_w){
264//      LOG (logerror ("centronics_busy_w(%d) %lld\n", state, m_maincpu->total_cycles ()));
265        m_centronics_busy = state;
195266}
196267
197WRITE_LINE_MEMBER(force68k_state::write_aciahost_clock)
198{
199      m_aciahost->write_txc(state);
200   m_aciahost->write_rxc(state);
268/* Centronics PERROR handler
269 * The centronics perror signal is not used by the ROM driver afaik
270 */
271WRITE_LINE_MEMBER (force68k_state::centronics_perror_w){
272//      LOG (logerror ("centronics_perror_w(%d) %lld\n", state, m_maincpu->total_cycles ()));
273        m_centronics_perror = state;
201274}
202275
203WRITE_LINE_MEMBER(force68k_state::write_aciaterm_clock)
276/* Centronics SELECT handler
277 * The centronics select signal is expected by the ROM on Port B bit 0
278 */
279WRITE_LINE_MEMBER (force68k_state::centronics_select_w){
280//      LOG (logerror ("centronics_select_w(%d) %lld\n", state, m_maincpu->total_cycles ()));
281        m_centronics_select = state;
282        m_pit->portb_setbit (0, state);
283}
284
285/* Start it up */
286void force68k_state::machine_start ()
204287{
205      m_aciaterm->write_txc(state);
206   m_aciaterm->write_rxc(state);
288        LOG (logerror ("machine_start\n"));
289
290        save_item (NAME (m_centronics_busy));
291        save_item (NAME (m_centronics_ack));
292        save_item (NAME (m_centronics_select));
293        save_item (NAME (m_centronics_perror));
294
295        /* Setup pointer to bootvector in ROM for bootvector handler bootvect_r */
296        m_sysrom = (UINT16*)(memregion ("maincpu")->base () + 0x080000);
297
298        /* Map user ROM/RAM socket(s) */
299        if (m_cart->exists())
300        {
301                m_usrrom = (UINT16*)m_cart->get_rom_base();
302#if 0 // This should be the correct way but produces odd and even bytes swapped
303                m_maincpu->space(AS_PROGRAM).install_read_handler(0xa0000, 0xbffff, read16_delegate(FUNC(generic_slot_device::read16_rom), (generic_slot_device*)m_cart));
304#else // So we installs a custom very ineffecient handler for now until we understand hwp to solve the problem better
305                m_maincpu->space(AS_PROGRAM).install_read_handler(0xa0000, 0xbffff, read16_delegate(FUNC(force68k_state::read16_rom), this));
306#endif
307        }
207308}
208309
209WRITE_LINE_MEMBER(force68k_state::write_aciaremt_clock)
310/* A very ineffecient User cart emulation of two 8 bit sockets (odd and even) */
311READ16_MEMBER (force68k_state::read16_rom){
312  offset = offset % m_cart->common_get_size("rom"); // Don't read outside buffer...
313  return ((m_usrrom [offset] << 8) & 0xff00) | ((m_usrrom [offset] >> 8) & 0x00ff);
314}
315
316/* Boot vector handler, the PCB hardwires the first 8 bytes from 0x80000 to 0x0 */
317READ16_MEMBER (force68k_state::bootvect_r){
318        return m_sysrom [offset];
319}
320
321/* 10. The VMEbus (text from board documentation)
322 * ---------------
323 * The implemented VMEbus Interface includes 24 address, 16 data,
324 * 6 address modifier and the asynchronous control signals.
325 * A single level bus arbiter is provided to build multi master
326 * systems. In addition to the bus arbiter, a separate slave bus
327 * arbitration allows selection of the arbitration level (0-3).
328 *
329 * The address modifier range .,Short 110 Access« can be selected
330 * via a jumper for variable system generation. The 7 interrupt
331 * request levels of the VMEbus are fully supported from the
332 * SYS68K1CPU-1 B/D. For multi-processing, each IRQ signal can be
333 * enabled/disabled via a jumper field.
334 *
335 * Additionally, the SYS68K1CPU-1 B/D supports the ACFAIL, SYSRESET,
336 * SYSFAIL and SYSCLK signal (16 MHz).
337 */
338
339/* Dummy VME access methods until the VME bus device is ready for use */
340READ16_MEMBER (force68k_state::vme_a24_r){
341        LOG (logerror ("vme_a24_r\n"));
342        return (UINT16) 0;
343}
344
345WRITE16_MEMBER (force68k_state::vme_a24_w){
346        LOG (logerror ("vme_a24_w\n"));
347}
348
349READ16_MEMBER (force68k_state::vme_a16_r){
350        LOG (logerror ("vme_16_r\n"));
351        return (UINT16) 0;
352}
353
354WRITE16_MEMBER (force68k_state::vme_a16_w){
355        LOG (logerror ("vme_a16_w\n"));
356}
357
358/*
359 * Serial port clock sources can all be driven by different outputs of the 14411
360 */
361WRITE_LINE_MEMBER (force68k_state::write_aciahost_clock){
362        m_aciahost->write_txc (state);
363        m_aciahost->write_rxc (state);
364}
365
366WRITE_LINE_MEMBER (force68k_state::write_aciaterm_clock){
367        m_aciaterm->write_txc (state);
368        m_aciaterm->write_rxc (state);
369}
370
371WRITE_LINE_MEMBER (force68k_state::write_aciaremt_clock){
372        m_aciaremt->write_txc (state);
373        m_aciaremt->write_rxc (state);
374}
375
376/*
377 * 4. The USER Area (Text from the board manual)
378  The USER area contains two 28 pin sockets with JEDEC compatible pin out.
379   To allow the usage of static RAM's, the access to the USER area is byte
380   oriented. Table 3. lists the usable device types.
381
382   Bits   Bytes    EPROM SRAM
383   --------------------------
384   2Kx16   4 Kbyte 2716  6116
385   4Kx16   8 Kbyte 2732
386   8Kx16  16 Kbyte 2764  6264
387   16Kx16 32 Kbyte 27128
388   32Kx16 64 Kbyte 27256
389   --------------------------
390*/
391// Implementation of static 2 x 64K EPROM in sockets J10/J11 as 16 bit wide cartridge for easier
392// software handling. TODO: make configurable according to table above.
393static MACHINE_CONFIG_FRAGMENT( fccpu1_eprom_sockets )
394        MCFG_GENERIC_CARTSLOT_ADD("exp_rom1", generic_plain_slot, "fccpu1_cart")
395        MCFG_GENERIC_EXTENSIONS("bin,rom")
396        MCFG_GENERIC_WIDTH(GENERIC_ROM16_WIDTH)
397        MCFG_GENERIC_ENDIAN(ENDIANNESS_BIG)
398        MCFG_GENERIC_LOAD(force68k_state, exp1_load)
399//      MCFG_SOFTWARE_LIST_ADD("cart_list", "fccpu1_cart")
400MACHINE_CONFIG_END
401
402/***************************
403   Rom loading functions
404****************************/
405int force68k_state::force68k_load_cart(device_image_interface &image, generic_slot_device *slot)
210406{
211      m_aciaremt->write_txc(state);
212   m_aciaremt->write_rxc(state);
407        UINT32 size = slot->common_get_size("rom");
408
409        if (size > 0x20000) // Max 128Kb
410        {
411                LOG( printf("Cartridge size exceeding max size (128Kb): %d\n", size) );
412                image.seterror(IMAGE_ERROR_UNSPECIFIED, "Cartridge size exceeding max size (128Kb)");
413                return IMAGE_INIT_FAIL;
414        }
415
416        slot->rom_alloc(size, GENERIC_ROM16_WIDTH, ENDIANNESS_BIG);
417        slot->common_load_rom(slot->get_rom_base(), size, "rom");
418       
419        return IMAGE_INIT_PASS;
213420}
214421
215static MACHINE_CONFIG_START( fccpu1, force68k_state )
216   /* basic machine hardware */
217   MCFG_CPU_ADD("maincpu", M68000, XTAL_16MHz / 2)
218   MCFG_CPU_PROGRAM_MAP(force68k_mem)
422/*
423 * Machine configuration
424 */
425static MACHINE_CONFIG_START (fccpu1, force68k_state)
426/* basic machine hardware */
427MCFG_CPU_ADD ("maincpu", M68000, XTAL_16MHz / 2)
428MCFG_CPU_PROGRAM_MAP (force68k_mem)
219429
220      /* P3/Host Port config */
221   MCFG_DEVICE_ADD("aciahost", ACIA6850, 0)
222      MCFG_DEVICE_ADD("aciahost_clock", CLOCK, ACIA_CLOCK)
223   MCFG_CLOCK_SIGNAL_HANDLER(WRITELINE(force68k_state, write_aciahost_clock))
430/* P3/Host Port config 
431 * LO command causes ROM monitor to expect S-records on HOST port by default
432 * Implementation through nullmodem currently does not support handshakes so
433 * the ROM momitor is over-run while checking for checksums etc if used with
434 * UI mount <file> feature.
435 */
436MCFG_DEVICE_ADD ("aciahost", ACIA6850, 0)
224437
225      /* P4/Terminal Port config */
226   MCFG_DEVICE_ADD("aciaterm", ACIA6850, 0)
438MCFG_ACIA6850_TXD_HANDLER (DEVWRITELINE ("rs232host", rs232_port_device, write_txd))
439MCFG_ACIA6850_RTS_HANDLER (DEVWRITELINE ("rs232host", rs232_port_device, write_rts))
227440
228   MCFG_ACIA6850_TXD_HANDLER(DEVWRITELINE("rs232trm", rs232_port_device, write_txd))
229   MCFG_ACIA6850_RTS_HANDLER(DEVWRITELINE("rs232trm", rs232_port_device, write_rts))
441MCFG_RS232_PORT_ADD ("rs232host", default_rs232_devices, "null_modem")
442MCFG_RS232_RXD_HANDLER (DEVWRITELINE ("aciahost", acia6850_device, write_rxd))
443MCFG_RS232_CTS_HANDLER (DEVWRITELINE ("aciahost", acia6850_device, write_cts))
230444
231   MCFG_RS232_PORT_ADD("rs232trm", default_rs232_devices, "terminal")
232   MCFG_RS232_RXD_HANDLER(DEVWRITELINE("aciaterm", acia6850_device, write_rxd))
233   MCFG_RS232_CTS_HANDLER(DEVWRITELINE("aciaterm", acia6850_device, write_cts))
445MCFG_DEVICE_ADD ("aciahost_clock", CLOCK, ACIA_CLOCK)
446MCFG_CLOCK_SIGNAL_HANDLER (WRITELINE (force68k_state, write_aciahost_clock))
234447
235      MCFG_DEVICE_ADD("aciaterm_clock", CLOCK, ACIA_CLOCK)
236   MCFG_CLOCK_SIGNAL_HANDLER(WRITELINE(force68k_state, write_aciaterm_clock))
448/* P4/Terminal Port config */
449MCFG_DEVICE_ADD ("aciaterm", ACIA6850, 0)
237450
238      /* P5/Remote Port config */
239   MCFG_DEVICE_ADD("aciaremt", ACIA6850, 0)
451MCFG_ACIA6850_TXD_HANDLER (DEVWRITELINE ("rs232trm", rs232_port_device, write_txd))
452MCFG_ACIA6850_RTS_HANDLER (DEVWRITELINE ("rs232trm", rs232_port_device, write_rts))
240453
241#define PRINTER 0
242#if PRINTER
243   MCFG_ACIA6850_TXD_HANDLER(DEVWRITELINE("rs232rmt", rs232_port_device, write_txd))
244   MCFG_ACIA6850_RTS_HANDLER(DEVWRITELINE("rs232rmt", rs232_port_device, write_rts))
454MCFG_RS232_PORT_ADD ("rs232trm", default_rs232_devices, "terminal")
455MCFG_RS232_RXD_HANDLER (DEVWRITELINE ("aciaterm", acia6850_device, write_rxd))
456MCFG_RS232_CTS_HANDLER (DEVWRITELINE ("aciaterm", acia6850_device, write_cts))
245457
246   MCFG_RS232_PORT_ADD("rs232rmt", default_rs232_devices, "printer")
247   MCFG_RS232_RXD_HANDLER(DEVWRITELINE("aciaremt", acia6850_device, write_rxd))
248   MCFG_RS232_CTS_HANDLER(DEVWRITELINE("aciaremt", acia6850_device, write_cts))
249#endif
458MCFG_DEVICE_ADD ("aciaterm_clock", CLOCK, ACIA_CLOCK)
459MCFG_CLOCK_SIGNAL_HANDLER (WRITELINE (force68k_state, write_aciaterm_clock))
250460
251      MCFG_DEVICE_ADD("aciaremt_clock", CLOCK, ACIA_CLOCK)
252   MCFG_CLOCK_SIGNAL_HANDLER(WRITELINE(force68k_state, write_aciaterm_clock))
461/* P5/Remote Port config */
462MCFG_DEVICE_ADD ("aciaremt", ACIA6850, 0)
253463
254   /* RTC Real Time Clock device */
255   MCFG_DEVICE_ADD("rtc", MM58167, XTAL_32_768kHz)
464MCFG_DEVICE_ADD ("aciaremt_clock", CLOCK, ACIA_CLOCK)
465MCFG_CLOCK_SIGNAL_HANDLER (WRITELINE (force68k_state, write_aciaterm_clock))
256466
257   /* PIT Parallel Interface and Timer device, assuming strapped for on board clock */
258   MCFG_DEVICE_ADD("pit", PIT68230, XTAL_16MHz / 2)
467/* RTC Real Time Clock device */
468MCFG_DEVICE_ADD ("rtc", MM58167, XTAL_32_768kHz)
259469
260MACHINE_CONFIG_END
470/* PIT Parallel Interface and Timer device, assuming strapped for on board clock */
471MCFG_DEVICE_ADD ("pit", PIT68230, XTAL_16MHz / 2)
472MCFG_PIT68230_PA_OUTPUT_CALLBACK (DEVWRITE8 ("cent_data_out", output_latch_device, write))
473MCFG_PIT68230_H2_CALLBACK (DEVWRITELINE ("centronics", centronics_device, write_strobe))
261474
262#if 0
475// centronics
476MCFG_CENTRONICS_ADD ("centronics", centronics_devices, "printer")
477MCFG_CENTRONICS_ACK_HANDLER (WRITELINE (force68k_state, centronics_ack_w))
478MCFG_CENTRONICS_BUSY_HANDLER (WRITELINE (force68k_state, centronics_busy_w))
479MCFG_CENTRONICS_PERROR_HANDLER (WRITELINE (force68k_state, centronics_perror_w))
480MCFG_CENTRONICS_SELECT_HANDLER (WRITELINE (force68k_state, centronics_select_w))
481MCFG_CENTRONICS_OUTPUT_LATCH_ADD ("cent_data_out", "centronics")
263482
264static MACHINE_CONFIG_START( fccpu6, force68k_state )
265   MCFG_CPU_ADD("maincpu", M68000, XTAL_8MHz)  /* Jumper B10 Mode B */
266   MCFG_CPU_PROGRAM_MAP(force68k_mem)
483// EPROM sockets
484MCFG_FRAGMENT_ADD(fccpu1_eprom_sockets)
267485MACHINE_CONFIG_END
268486
269static MACHINE_CONFIG_START( fccpu6a, force68k_state )
270   MCFG_CPU_ADD("maincpu", M68000, XTAL_12_5MHz) /* Jumper B10 Mode A */
271   MCFG_CPU_PROGRAM_MAP(force68k_mem)
487#if 0 /*
488       * CPU-6 family is device and adressmap compatible with CPU-1 but with additions
489       * such as an optional 68881 FPU
490       */
491static MACHINE_CONFIG_START (fccpu6, force68k_state)
492MCFG_CPU_ADD ("maincpu", M68000, XTAL_8MHz)         /* Jumper B10 Mode B */
493MCFG_CPU_PROGRAM_MAP (force68k_mem)
272494MACHINE_CONFIG_END
273495
274static MACHINE_CONFIG_START( fccpu6v, force68k_state )
275   MCFG_CPU_ADD("maincpu", M68010, XTAL_8MHz)  /* Jumper B10 Mode B */
276   MCFG_CPU_PROGRAM_MAP(force68k_mem)
496static MACHINE_CONFIG_START (fccpu6a, force68k_state)
497MCFG_CPU_ADD ("maincpu", M68000, XTAL_12_5MHz)        /* Jumper B10 Mode A */
498MCFG_CPU_PROGRAM_MAP (force68k_mem)
277499MACHINE_CONFIG_END
278500
279static MACHINE_CONFIG_START( fccpu6va, force68k_state )
280   MCFG_CPU_ADD("maincpu", M68010, XTAL_12_5MHz) /* Jumper B10 Mode A */
281   MCFG_CPU_PROGRAM_MAP(force68k_mem)
501static MACHINE_CONFIG_START (fccpu6v, force68k_state)
502MCFG_CPU_ADD ("maincpu", M68010, XTAL_8MHz)         /* Jumper B10 Mode B */
503MCFG_CPU_PROGRAM_MAP (force68k_mem)
282504MACHINE_CONFIG_END
283505
284static MACHINE_CONFIG_START( fccpu6vb, force68k_state )
285   MCFG_CPU_ADD("maincpu", M68010, XTAL_12_5MHz) /* Jumper B10 Mode A */
286   MCFG_CPU_PROGRAM_MAP(force68k_mem)
506static MACHINE_CONFIG_START (fccpu6va, force68k_state)
507MCFG_CPU_ADD ("maincpu", M68010, XTAL_12_5MHz)        /* Jumper B10 Mode A */
508MCFG_CPU_PROGRAM_MAP (force68k_mem)
287509MACHINE_CONFIG_END
510
511static MACHINE_CONFIG_START (fccpu6vb, force68k_state)
512MCFG_CPU_ADD ("maincpu", M68010, XTAL_12_5MHz)        /* Jumper B10 Mode A */
513MCFG_CPU_PROGRAM_MAP (force68k_mem)
514MACHINE_CONFIG_END
288515#endif
289516
290517/* ROM definitions */
291ROM_START( fccpu1 )
292   ROM_REGION(0x1000000, "maincpu", 0)
518ROM_START (fccpu1)
519ROM_REGION (0x1000000, "maincpu", 0)
293520
294      ROM_LOAD16_BYTE( "fccpu1V1.0L.j8.bin", 0x080001, 0x2000, CRC(3ac6f08f) SHA1(502f6547b508d8732bd68bbbb2402d8c30fefc3b) )
295      ROM_LOAD16_BYTE( "fccpu1V1.0L.j9.bin", 0x080000, 0x2000, CRC(035315fb) SHA1(90dc44d9c25d28428233e6846da6edce2d69e440) )
296/* COMMAND SUMMARY DESCRIPTION (From CPU-1B datasheet, ROMs were dumped
297   from a CPU-1 board so some features might be missing or different)
298---------------------------------------------------------------------------
299   BF <address1> <address2> <data> <CR>        Block Fill memory - from addr1 through addr2 with data
300   BM <address1> <address2> <address 3> <CR>   Block Move  - move from addr1 through addr2to addr3
301   BR [<address> [; <count>] ... ] <CR>        Set/display Breakpoint
302   BS <address1> <address2> <data> <CR>        Block Search - search addr1 through addr2 for data
303   BT <address1> <address2> <CR>               Block Test of memory
304   DC <expression> <CR>                        Data Conversion
305   DF <CR>                                     Display Formatted registers
306   DU [n] <address1> <address2>[<string>] <CR> Dump memory to object file
307   GO [<address] <CR>                          Execute program
308   GD [<address] <CR>                          Go Direct
309   GT <address> <CR>                           Exec prog: temporary breakpoint
310   HE<CR>                                      Help; display monitor commands
311   LO [n] [;<options] <CR>                     Load Object file
312   MD <address> [<count?? <CR>                  Memory Display
313   MM <address> [<data?? [;<options?? <CR>       Memory Modify
314   MS <address> <data1 > <data2> < ... <CR>    Memory Set - starting at addr with data 1. data 2 ...
315   NOBR [<address> ... ] <CR>                  Remove Breakpoint
316   NOPA <CR>                                   Printer Detach (Centronics on PIT/P2)
317   OF <CR>                                     Offset
318   PA <CR>                                     Printer Attach (Centronics on PIT/P2)
319   PF[n] <CR>                                  Set/display Port Format
320   RM <CR>                                     Register Modify
321   TM [<exit character?? <CR>                   Transparent Mode
322   TR [<count] <CR>                            Trace
323   TT <address> <CR>                           Trace: temporary breakpoint
324   VE [n] [<string] <CR>                       Verify memory/object file
325----------------------------------------------------------------------------
326  .AO - .A7 [<expression] <CR>                 Display/set address register
327  .00 - .07 [<expression] <CR>                 Display/set data register
328  .RO - .R6 [<expression] <CR>                 Display/set offset register
329  .PC [<expression] <CR>                       Display/set program counter
330  .SR [<expression] <CR>                       Display/set status register
331  .SS [<expression] <CR>                       Display/set supervisor stack
332  .US [<expression] <CR>                       Display/set user stack
333----------------------------------------------------------------------------
334   MD <address> [<count>]; D1 <CR>             Disassemble memory location
335   MM <address>; DI <CR>                       Disassemble/Assemble memory location
336----------------------------------------------------------------------------
337*/
521ROM_LOAD16_BYTE ("fccpu1V1.0L.j8.bin", 0x080001, 0x2000, CRC (3ac6f08f) SHA1 (502f6547b508d8732bd68bbbb2402d8c30fefc3b))
522ROM_LOAD16_BYTE ("fccpu1V1.0L.j9.bin", 0x080000, 0x2000, CRC (035315fb) SHA1 (90dc44d9c25d28428233e6846da6edce2d69e440))
523
524/*
525 * System ROM terminal commands
526 *
527 * COMMAND SUMMARY DESCRIPTION (From CPU-1B datasheet, ROMs were dumped
528 * from a CPU-1 board so some features might be missing or different)
529 * ---------------------------------------------------------------------------
530 * BF <address1> <address2> <data> <CR>        Block Fill memory - from addr1 through addr2 with data
531 * BM <address1> <address2> <address 3> <CR>   Block Move  - move from addr1 through addr2to addr3
532 * BR [<address> [; <count>] ... ] <CR>        Set/display Breakpoint
533 * BS <address1> <address2> <data> <CR>        Block Search - search addr1 through addr2 for data
534 * BT <address1> <address2> <CR>               Block Test of memory
535 * DC <expression> <CR>                        Data Conversion
536 * DF <CR>                                     Display Formatted registers
537 * DU [n] <address1> <address2>[<string>] <CR> Dump memory to object file
538 * GO or G [<address] <CR>                     Execute program.
539 * GD [<address] <CR>                          Go Direct
540 * GT <address> <CR>                           Exec prog: temporary breakpoint
541 * HE<CR>                                      Help; display monitor commands
542 * LO [n] [;<options] <CR>                     Load Object file
543 * MD <address> [<count>] <CR>                 Memory Display
544 * MM or M <address> [<data<][;<options>] <CR> Memory Modify
545 * MS <address> <data1 > <data2> < ... <CR>    Memory Set - starting at addr with data 1. data 2 ...
546 * NOBR [<address> ... ] <CR>                  Remove Breakpoint
547 * NOPA <CR>                                   Printer Detach (Centronics on PIT/P2)
548 * OF <CR>                                     Offset
549 * PA <CR>                                     Printer Attach (Centronics on PIT/P2)
550 * PF[n] <CR>                                  Set/display Port Format
551 * RM <CR>                                     Register Modify
552 * TM [<exit character>] <CR>                  Transparent Mode
553 * TR OR T [<count] <CR>                       Trace
554 * TT <address> <CR>                           Trace: temporary breakpoint
555 * VE [n] [<string] <CR>                       Verify memory/object file
556 * ----------------------------------------------------------------------------
557 * .AO - .A7 [<expression] <CR>                Display/set address register
558 * .00 - .07 [<expression] <CR>                Display/set data register
559 * .RO - .R6 [<expression] <CR>                Display/set offset register
560 * .PC [<expression] <CR>                      Display/set program counter
561 * .SR [<expression] <CR>                      Display/set status register
562 * .SS [<expression] <CR>                      Display/set supervisor stack
563 * .US [<expression] <CR>                      Display/set user stack
564 * ----------------------------------------------------------------------------
565 * MD <address> [<count>]; DI <CR>             Disassemble memory location
566 * MM <address>; DI <CR>                       Disassemble/Assemble memory location
567 * ----------------------------------------------------------------------------
568 * Undocumented commands found in ROM table at address 0x80308
569 * .*                                          No WHAT message displayed, no action seen.
570 */
338571ROM_END
339572
573/*
574 * CPU-6 ROMs were generally based om VMEPROM which contained the PDOS RTOS from Eyring Research.
575 * I don't have these but if anyone can dump them and send to me I can verify that they work as expected.
576 */
340577#if 0
341ROM_START( fccpu6 )
342   ROM_REGION(0x1000000, "maincpu", 0)
578ROM_START (fccpu6)
579ROM_REGION (0x1000000, "maincpu", 0)
343580ROM_END
344581
345ROM_START( fccpu6a )
346   ROM_REGION(0x1000000, "maincpu", 0)
582ROM_START (fccpu6a)
583ROM_REGION (0x1000000, "maincpu", 0)
347584ROM_END
348585
349ROM_START( fccpu6v )
350   ROM_REGION(0x1000000, "maincpu", 0)
586ROM_START (fccpu6v)
587ROM_REGION (0x1000000, "maincpu", 0)
351588ROM_END
352589
353ROM_START( fccpu6va )
354   ROM_REGION(0x1000000, "maincpu", 0)
590ROM_START (fccpu6va)
591ROM_REGION (0x1000000, "maincpu", 0)
355592ROM_END
356593
357ROM_START( fccpu6vb )
358   ROM_REGION(0x1000000, "maincpu", 0)
594ROM_START (fccpu6vb)
595ROM_REGION (0x1000000, "maincpu", 0)
359596ROM_END
360597#endif
361598
trunk/src/mess/drivers/mc1000.c
r249095r249096
378378  +---------*---*---o V+
379379  |         |   |
380380 +-+        |   |
381 | |309K    |   |
381 | |390K    |   |
382382 | |R17     |8  |4
383383 +-+      +-------+
384384  |      7|       |3
r249095r249096
390390 | |   |  |  555  |
391391 +-+   |  |       |
392392  |    | 6|       |5
393  *----*?-|       |---+
393  *----*--|       |---+
394394  |       |       |   |
395395 ---C30   +-------+  ---C29
396 ---103       |1     ---103
396 ---10n       |1     ---10n
397397 _|_         _|_     _|_
398398 ///         ///     ///
399399
400400 Calculated properties:
401401
402402 * 99.74489795918367 Duty Cycle Percentage
403 * 368.1126130105722 Frequency in Hertz
403 * 367.3469387755102 Frequency in Hertz
404404 * 0.00000693 Seconds Low
405 * 0.0027096299999999998 Seconds High
405 * 0.00270963 Seconds High
406406
407407 */
408408
409#define MC1000_NE555_FREQ       (368) /* Hz */
409#define MC1000_NE555_FREQ       (367) /* Hz */
410410#define MC1000_NE555_DUTY_CYCLE (99.745) /* % */
411411
412412TIMER_DEVICE_CALLBACK_MEMBER(mc1000_state::ne555_tick)
trunk/src/mess/drivers/mk85.c
r249095r249096
6363
6464static MACHINE_CONFIG_START( mk85, mk85_state )
6565   /* basic machine hardware */
66   MCFG_CPU_ADD("maincpu",T11, XTAL_4MHz)
67   MCFG_T11_INITIAL_MODE(5 << 13)         /* start from 0000 */
66   MCFG_CPU_ADD("maincpu", K1801VM2, XTAL_4MHz)
67   MCFG_T11_INITIAL_MODE(0)
6868   MCFG_CPU_PROGRAM_MAP(mk85_mem)
6969
7070
trunk/src/mess/drivers/mk90.c
r249095r249096
6868
6969static MACHINE_CONFIG_START( mk90, mk90_state )
7070   /* basic machine hardware */
71   MCFG_CPU_ADD("maincpu",T11, XTAL_4MHz)
72   MCFG_T11_INITIAL_MODE(0xf600)
71   MCFG_CPU_ADD("maincpu", K1801VM2, XTAL_4MHz)
72   MCFG_T11_INITIAL_MODE(0x8000)
7373   MCFG_CPU_PROGRAM_MAP(mk90_mem)
7474
7575
trunk/src/mess/drivers/tispeak.c
r249095r249096
487487
488488void tispeak_state::prepare_display()
489489{
490   display_matrix_seg(16, 16, m_plate, (m_r & 0x8000) ? m_grid : 0, 0x3fff);
490   UINT16 gridmask = (m_display_decay[15][16] != 0) ? 0xffff : 0x8000;
491   display_matrix_seg(16+1, 16, m_plate | 0x10000, m_grid & gridmask, 0x3fff);
491492}
492493
493494WRITE16_MEMBER(tispeak_state::snspell_write_r)
r249095r249096
500501   // R15: filament on
501502   // other bits: MCU internal use
502503   m_r = m_inp_mux = data;
503   m_grid = data & 0x1ff;
504   m_grid = data & 0x81ff;
504505   prepare_display();
505506}
506507
r249095r249096
547548{
548549   // same as default, except R13 is used for an extra digit
549550   m_r = m_inp_mux = data;
550   m_grid = data & 0x21ff;
551   m_grid = data & 0xa1ff;
551552   prepare_display();
552553}
553554
trunk/src/mess/drivers/uknc.c
r249095r249096
5858
5959static MACHINE_CONFIG_START( uknc, uknc_state )
6060   /* basic machine hardware */
61   MCFG_CPU_ADD("maincpu", T11, 8000000)
62   MCFG_T11_INITIAL_MODE(0x36ff)  /* initial mode word has DAL15,14,11,8 pulled low */
61   MCFG_CPU_ADD("maincpu", K1801VM2, 8000000)
62   MCFG_T11_INITIAL_MODE(0x8000)
6363   MCFG_CPU_PROGRAM_MAP(uknc_mem)
6464
65   MCFG_CPU_ADD("subcpu",  T11, 6000000)
66   MCFG_T11_INITIAL_MODE(0x36ff)  /* initial mode word has DAL15,14,11,8 pulled low */
65   MCFG_CPU_ADD("subcpu",  K1801VM2, 6000000)
66   MCFG_T11_INITIAL_MODE(0x8000)
6767   MCFG_CPU_PROGRAM_MAP(uknc_sub_mem)
6868
6969
trunk/src/mess/layout/fccpu1.lay
r0r249096
1<?xml version="1.0"?>
2<!-- fccpu1.lay -->
3<!-- 2015-07-27: Initial version.  [JLE] -->
4<mamelayout version="2">
5    <element name="front">
6            <image file="front.png" />
7    </element>
8    <view name="Force Computers SYS68K/CPU-1">
9        <screen index="0">
10            <bounds left="100" top="0" right="640" bottom="480" /> 
11        </screen>
12   <bezel name="frontpanel" element="front">
13     <bounds x="0" y="0" width="36" height="480" />
14   </bezel>
15    </view>
16</mamelayout>
17
trunk/src/osd/modules/debugger/win/debugviewinfo.c
r249095r249096
1515
1616#include "strconv.h"
1717
18#include "winutil.h"
1819
20
1921// debugger view styles
2022#define DEBUG_VIEW_STYLE    WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN
2123#define DEBUG_VIEW_STYLE_EX 0
r249095r249096
4850
4951   // create the child view
5052   m_wnd = CreateWindowEx(DEBUG_VIEW_STYLE_EX, TEXT("MAMEDebugView"), NULL, DEBUG_VIEW_STYLE,
51         0, 0, 100, 100, parent, NULL, GetModuleHandle(NULL), this);
53          0, 0, 100, 100, parent, NULL, GetModuleHandleUni(), this);
5254   if (m_wnd == NULL)
5355      goto cleanup;
5456
5557   // create the scroll bars
5658   m_hscroll = CreateWindowEx(HSCROLL_STYLE_EX, TEXT("SCROLLBAR"), NULL, HSCROLL_STYLE,
57         0, 0, 100, CW_USEDEFAULT, m_wnd, NULL, GetModuleHandle(NULL), this);
59         0, 0, 100, CW_USEDEFAULT, m_wnd, NULL, GetModuleHandleUni(), this);
5860   m_vscroll = CreateWindowEx(VSCROLL_STYLE_EX, TEXT("SCROLLBAR"), NULL, VSCROLL_STYLE,
59         0, 0, CW_USEDEFAULT, 100, m_wnd, NULL, GetModuleHandle(NULL), this);
61         0, 0, CW_USEDEFAULT, 100, m_wnd, NULL, GetModuleHandleUni(), this);
6062   if ((m_hscroll == NULL) || (m_vscroll == NULL))
6163      goto cleanup;
6264
r249095r249096
254256{
255257   // create a combo box
256258   HWND const result = CreateWindowEx(COMBO_BOX_STYLE_EX, TEXT("COMBOBOX"), NULL, COMBO_BOX_STYLE,
257         0, 0, 100, 1000, parent, NULL, GetModuleHandle(NULL), NULL);
259         0, 0, 100, 1000, parent, NULL, GetModuleHandleUni(), NULL);
258260   SetWindowLongPtr(result, GWLP_USERDATA, userdata);
259261   SendMessage(result, WM_SETFONT, (WPARAM)metrics().debug_font(), (LPARAM)FALSE);
260262
r249095r249096
789791
790792      // initialize the description of the window class
791793      wc.lpszClassName    = TEXT("MAMEDebugView");
792      wc.hInstance        = GetModuleHandle(NULL);
794      wc.hInstance        = GetModuleHandleUni();
793795      wc.lpfnWndProc      = &debugview_info::static_view_proc;
794796      wc.hCursor          = LoadCursor(NULL, IDC_ARROW);
795797      wc.hIcon            = LoadIcon(wc.hInstance, MAKEINTRESOURCE(2));
r249095r249096
798800      wc.style            = 0;
799801      wc.cbClsExtra       = 0;
800802      wc.cbWndExtra       = 0;
803     
804      UnregisterClass(wc.lpszClassName, wc.hInstance);
801805
802806      // register the class; fail if we can't
803807      if (!RegisterClass(&wc))
trunk/src/osd/modules/debugger/win/debugwininfo.c
r249095r249096
1717#include "window.h"
1818#include "winutf8.h"
1919
20#include "winutil.h"
2021
22
2123bool debugwin_info::s_window_class_registered = false;
2224
2325
r249095r249096
3638   register_window_class();
3739
3840   m_wnd = win_create_window_ex_utf8(DEBUG_WINDOW_STYLE_EX, "MAMEDebugWindow", title, DEBUG_WINDOW_STYLE,
39         0, 0, 100, 100, win_window_list->m_hwnd, create_standard_menubar(), GetModuleHandle(NULL), this);
41         0, 0, 100, 100, win_window_list->m_hwnd, create_standard_menubar(), GetModuleHandleUni(), this);
4042   if (m_wnd == NULL)
4143      return;
4244
r249095r249096
580582
581583      // initialize the description of the window class
582584      wc.lpszClassName    = TEXT("MAMEDebugWindow");
583      wc.hInstance        = GetModuleHandle(NULL);
585      wc.hInstance        = GetModuleHandleUni();
584586      wc.lpfnWndProc      = &debugwin_info::static_window_proc;
585587      wc.hCursor          = LoadCursor(NULL, IDC_ARROW);
586588      wc.hIcon            = LoadIcon(wc.hInstance, MAKEINTRESOURCE(2));
r249095r249096
589591      wc.style            = 0;
590592      wc.cbClsExtra       = 0;
591593      wc.cbWndExtra       = 0;
594     
595      UnregisterClass(wc.lpszClassName, wc.hInstance);
592596
593597      // register the class; fail if we can't
594598      if (!RegisterClass(&wc))
trunk/src/osd/modules/debugger/win/editwininfo.c
r249095r249096
1313
1414#include "strconv.h"
1515
16#include "winutil.h"
1617
18
1719// edit box styles
1820#define EDIT_BOX_STYLE      WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL
1921#define EDIT_BOX_STYLE_EX   0
r249095r249096
3234
3335   // create an edit box and override its key handling
3436   m_editwnd = CreateWindowEx(EDIT_BOX_STYLE_EX, TEXT("EDIT"), NULL, EDIT_BOX_STYLE,
35         0, 0, 100, 100, window(), NULL, GetModuleHandle(NULL), NULL);
37         0, 0, 100, 100, window(), NULL, GetModuleHandleUni(), NULL);
3638   m_original_editproc = (WNDPROC)(FPTR)GetWindowLongPtr(m_editwnd, GWLP_WNDPROC);
3739   SetWindowLongPtr(m_editwnd, GWLP_USERDATA, (LONG_PTR)this);
3840   SetWindowLongPtr(m_editwnd, GWLP_WNDPROC, (LONG_PTR)&editwin_info::static_edit_proc);
trunk/src/osd/windows/input.c
r249095r249096
3838#include "strconv.h"
3939#include "config.h"
4040
41#include "winutil.h"
42
4143//============================================================
4244//  PARAMETERS
4345//============================================================
r249095r249096
11171119   int didevtype_joystick = DI8DEVCLASS_GAMECTRL;
11181120
11191121   dinput_version = DIRECTINPUT_VERSION;
1120   result = DirectInput8Create(GetModuleHandle(NULL), dinput_version, IID_IDirectInput8, (void **)&dinput, NULL);
1122   result = DirectInput8Create(GetModuleHandleUni(), dinput_version, IID_IDirectInput8, (void **)&dinput, NULL);
11211123   if (result != DI_OK)
11221124   {
11231125      dinput_version = 0;
r249095r249096
11301132
11311133   // first attempt to initialize DirectInput at the current version
11321134   dinput_version = DIRECTINPUT_VERSION;
1133   result = DirectInputCreate(GetModuleHandle(NULL), dinput_version, &dinput, NULL);
1135   result = DirectInputCreate(GetModuleHandleUni(), dinput_version, &dinput, NULL);
11341136   if (result != DI_OK)
11351137   {
11361138      // if that fails, try version 5
11371139      dinput_version = 0x0500;
1138      result = DirectInputCreate(GetModuleHandle(NULL), dinput_version, &dinput, NULL);
1140      result = DirectInputCreate(GetModuleHandleUni(), dinput_version, &dinput, NULL);
11391141      if (result != DI_OK)
11401142      {
11411143         // if that fails, try version 3
11421144         dinput_version = 0x0300;
1143         result = DirectInputCreate(GetModuleHandle(NULL), dinput_version, &dinput, NULL);
1145         result = DirectInputCreate(GetModuleHandleUni(), dinput_version, &dinput, NULL);
11441146         if (result != DI_OK)
11451147         {
11461148            dinput_version = 0;
trunk/src/osd/windows/output.c
r249095r249096
1717// MAMEOS headers
1818#include "output.h"
1919
20#include "winutil.h"
2021
2122
23
2224//============================================================
2325//  CONSTANTS
2426//============================================================
r249095r249096
101103                  1, 1,
102104                  NULL,
103105                  NULL,
104                  GetModuleHandle(NULL),
106                  GetModuleHandleUni(),
105107                  NULL);
106108   assert(output_hwnd != NULL);
107109
r249095r249096
167169
168170      // initialize the description of the window class
169171      wc.lpszClassName    = OUTPUT_WINDOW_CLASS;
170      wc.hInstance        = GetModuleHandle(NULL);
172      wc.hInstance        = GetModuleHandleUni();
171173      wc.lpfnWndProc      = output_window_proc;
174     
175      UnregisterClass(wc.lpszClassName, wc.hInstance);
172176
173177      // register the class; fail if we can't
174178      if (!RegisterClass(&wc))
trunk/src/osd/windows/window.c
r249095r249096
3535#include "config.h"
3636#include "winutf8.h"
3737
38#include "winutil.h"
39
3840extern int drawnone_init(running_machine &machine, osd_draw_callbacks *callbacks);
3941extern int drawgdi_init(running_machine &machine, osd_draw_callbacks *callbacks);
4042extern int drawdd_init(running_machine &machine, osd_draw_callbacks *callbacks);
r249095r249096
885887
886888      // initialize the description of the window class
887889      wc.lpszClassName    = TEXT("MAME");
888      wc.hInstance        = GetModuleHandle(NULL);
890      wc.hInstance        = GetModuleHandleUni();
889891      wc.lpfnWndProc      = winwindow_video_window_proc_ui;
890892      wc.hCursor          = LoadCursor(NULL, IDC_ARROW);
891893      wc.hIcon            = LoadIcon(wc.hInstance, MAKEINTRESOURCE(2));
894     
895      UnregisterClass(wc.lpszClassName, wc.hInstance);
892896
893897      // register the class; fail if we can't
894898      if (!RegisterClass(&wc))
r249095r249096
11911195                  monitorbounds.left() + 100, monitorbounds.top() + 100,
11921196                  NULL,//(win_window_list != NULL) ? win_window_list->m_hwnd : NULL,
11931197                  menu,
1194                  GetModuleHandle(NULL),
1198                  GetModuleHandleUni(),
11951199                  NULL);
11961200   if (m_hwnd == NULL)
11971201      return 1;
trunk/src/osd/windows/winmain.c
r249095r249096
13211321   dynamic_bind<PIMAGE_NT_HEADERS (WINAPI *)(PVOID)> image_nt_header(TEXT("dbghelp.dll"), "ImageNtHeader");
13221322
13231323   // start with the image base
1324   PVOID base = reinterpret_cast<PVOID>(GetModuleHandle(NULL));
1324   PVOID base = reinterpret_cast<PVOID>(GetModuleHandleUni());
13251325   assert(base != NULL);
13261326
13271327   // make sure we have the functions we need
trunk/src/osd/windows/winutil.c
r249095r249096
9292      is_first_time = FALSE;
9393
9494      // get the current module
95      module = GetModuleHandle(NULL);
95      module = GetModuleHandleUni();
9696      if (!module)
9797         return FALSE;
9898      image_ptr = (BYTE*) module;
r249095r249096
122122   }
123123   return is_gui_frontend;
124124}
125
126//-------------------------------------------------
127//  Universal way to get module handle
128//-------------------------------------------------
129
130HMODULE WINAPI GetModuleHandleUni()
131{
132   MEMORY_BASIC_INFORMATION mbi;
133   VirtualQuery((LPCVOID)GetModuleHandleUni, &mbi, sizeof(mbi));
134   return (HMODULE)mbi.AllocationBase;
135}
trunk/src/osd/windows/winutil.h
r249095r249096
1515file_error win_error_to_file_error(DWORD error);
1616osd_dir_entry_type win_attributes_to_entry_type(DWORD attributes);
1717BOOL win_is_gui_application(void);
18HMODULE WINAPI GetModuleHandleUni();
1819
1920#endif // __WINUTIL__
trunk/tests/lib/util/corestr.c
r249095r249096
11// license:BSD-3-Clause
22// copyright-holders:Miodrag Milanovic
33
4#include "UnitTest++/UnitTest++.h"
4#include "gtest/gtest.h"
55#include "corestr.h"
66
7TEST(strmakeupper)
7TEST(corestr,strmakeupper)
88{
99   std::string value = "test";
10   CHECK_EQUAL("TEST", strmakeupper(value).c_str());
10   EXPECT_STREQ("TEST", strmakeupper(value).c_str());
1111}
1212
13TEST(strmakelower)
13TEST(corestr,strmakelower)
1414{
1515   std::string value = "ValUE";
16   CHECK_EQUAL("value", strmakelower(value).c_str());
16   EXPECT_STREQ("value", strmakelower(value).c_str());
1717}
1818
19TEST(strreplace)
19TEST(corestr,strreplace)
2020{
2121   std::string value = "Main string";
22   CHECK_EQUAL(1, strreplace(value,"str","aaa"));
23   CHECK_EQUAL("Main aaaing", value.c_str());
24   CHECK_EQUAL(4, strreplace(value,"a","b"));
22   EXPECT_EQ(1, strreplace(value,"str","aaa"));
23   EXPECT_STREQ("Main aaaing", value.c_str());
24   EXPECT_EQ(4, strreplace(value,"a","b"));
2525}
2626
27TEST(strtrimspace)
27TEST(corestr,strtrimspace)
2828{
2929   std::string value = "    a value  for test  ";
30   CHECK_EQUAL("a value  for test", strtrimspace(value).c_str());
30   EXPECT_STREQ("a value  for test", strtrimspace(value).c_str());
3131   value = "\r\n\ta value  for test\r\n\n\r";
32   CHECK_EQUAL("a value  for test", strtrimspace(value).c_str());
32   EXPECT_STREQ("a value  for test", strtrimspace(value).c_str());
3333}
3434
35TEST(strreplacechr)
35TEST(corestr,strreplacechr)
3636{
3737   std::string value = "String for doing replaces";
3838   strreplacechr(value,'a','A');
3939   strreplacechr(value,'e','E');
4040   strreplacechr(value,'i','I');
4141   strreplacechr(value,'o','O');
42   CHECK_EQUAL("StrIng fOr dOIng rEplAcEs", value.c_str());
42   EXPECT_STREQ("StrIng fOr dOIng rEplAcEs", value.c_str());
4343}
4444
45TEST(strdelchr)
45TEST(corestr,strdelchr)
4646{
4747   std::string value = "String for doing deletes";
4848   strdelchr(value,'a');
4949   strdelchr(value,'e');
5050   strdelchr(value,'i');
5151   strdelchr(value,'o');
52   CHECK_EQUAL("Strng fr dng dlts", value.c_str());
52   EXPECT_STREQ("Strng fr dng dlts", value.c_str());
5353}
5454
trunk/tests/main.c
r249095r249096
11// license:BSD-3-Clause
22// copyright-holders:Miodrag Milanovic
33
4#include "UnitTest++/UnitTest++.h"
4#include <stdio.h>
5#include "gtest/gtest.h"
56
6int main(int, char const *[])
7int main(int argc, char **argv)
78{
8    return UnitTest::RunAllTests();
9  testing::InitGoogleTest(&argc, argv);
10  return RUN_ALL_TESTS();
911}
12


Previous 199869 Revisions Next


© 1997-2024 The MAME Team