updated gtest to latest

This commit is contained in:
Riccardo Spagni 2015-03-24 08:48:43 +02:00
parent 178b009e90
commit 1c49d6b2d3
No known key found for this signature in database
GPG Key ID: 55432DF31CCD4FCD
37 changed files with 4929 additions and 1916 deletions

157
tests/gtest/CHANGES Normal file
View File

@ -0,0 +1,157 @@
Changes for 1.7.0:
* New feature: death tests are supported on OpenBSD and in iOS
simulator now.
* New feature: Google Test now implements a protocol to allow
a test runner to detect that a test program has exited
prematurely and report it as a failure (before it would be
falsely reported as a success if the exit code is 0).
* New feature: Test::RecordProperty() can now be used outside of the
lifespan of a test method, in which case it will be attributed to
the current test case or the test program in the XML report.
* New feature (potentially breaking): --gtest_list_tests now prints
the type parameters and value parameters for each test.
* Improvement: char pointers and char arrays are now escaped properly
in failure messages.
* Improvement: failure summary in XML reports now includes file and
line information.
* Improvement: the <testsuites> XML element now has a timestamp attribute.
* Improvement: When --gtest_filter is specified, XML report now doesn't
contain information about tests that are filtered out.
* Fixed the bug where long --gtest_filter flag values are truncated in
death tests.
* Potentially breaking change: RUN_ALL_TESTS() is now implemented as a
function instead of a macro in order to work better with Clang.
* Compatibility fixes with C++ 11 and various platforms.
* Bug/warning fixes.
Changes for 1.6.0:
* New feature: ADD_FAILURE_AT() for reporting a test failure at the
given source location -- useful for writing testing utilities.
* New feature: the universal value printer is moved from Google Mock
to Google Test.
* New feature: type parameters and value parameters are reported in
the XML report now.
* A gtest_disable_pthreads CMake option.
* Colored output works in GNU Screen sessions now.
* Parameters of value-parameterized tests are now printed in the
textual output.
* Failures from ad hoc test assertions run before RUN_ALL_TESTS() are
now correctly reported.
* Arguments of ASSERT_XY and EXPECT_XY no longer need to support << to
ostream.
* More complete handling of exceptions.
* GTEST_ASSERT_XY can be used instead of ASSERT_XY in case the latter
name is already used by another library.
* --gtest_catch_exceptions is now true by default, allowing a test
program to continue after an exception is thrown.
* Value-parameterized test fixtures can now derive from Test and
WithParamInterface<T> separately, easing conversion of legacy tests.
* Death test messages are clearly marked to make them more
distinguishable from other messages.
* Compatibility fixes for Android, Google Native Client, MinGW, HP UX,
PowerPC, Lucid autotools, libCStd, Sun C++, Borland C++ Builder (Code Gear),
IBM XL C++ (Visual Age C++), and C++0x.
* Bug fixes and implementation clean-ups.
* Potentially incompatible changes: disables the harmful 'make install'
command in autotools.
Changes for 1.5.0:
* New feature: assertions can be safely called in multiple threads
where the pthreads library is available.
* New feature: predicates used inside EXPECT_TRUE() and friends
can now generate custom failure messages.
* New feature: Google Test can now be compiled as a DLL.
* New feature: fused source files are included.
* New feature: prints help when encountering unrecognized Google Test flags.
* Experimental feature: CMake build script (requires CMake 2.6.4+).
* Experimental feature: the Pump script for meta programming.
* double values streamed to an assertion are printed with enough precision
to differentiate any two different values.
* Google Test now works on Solaris and AIX.
* Build and test script improvements.
* Bug fixes and implementation clean-ups.
Potentially breaking changes:
* Stopped supporting VC++ 7.1 with exceptions disabled.
* Dropped support for 'make install'.
Changes for 1.4.0:
* New feature: the event listener API
* New feature: test shuffling
* New feature: the XML report format is closer to junitreport and can
be parsed by Hudson now.
* New feature: when a test runs under Visual Studio, its failures are
integrated in the IDE.
* New feature: /MD(d) versions of VC++ projects.
* New feature: elapsed time for the tests is printed by default.
* New feature: comes with a TR1 tuple implementation such that Boost
is no longer needed for Combine().
* New feature: EXPECT_DEATH_IF_SUPPORTED macro and friends.
* New feature: the Xcode project can now produce static gtest
libraries in addition to a framework.
* Compatibility fixes for Solaris, Cygwin, minGW, Windows Mobile,
Symbian, gcc, and C++Builder.
* Bug fixes and implementation clean-ups.
Changes for 1.3.0:
* New feature: death tests on Windows, Cygwin, and Mac.
* New feature: ability to use Google Test assertions in other testing
frameworks.
* New feature: ability to run disabled test via
--gtest_also_run_disabled_tests.
* New feature: the --help flag for printing the usage.
* New feature: access to Google Test flag values in user code.
* New feature: a script that packs Google Test into one .h and one
.cc file for easy deployment.
* New feature: support for distributing test functions to multiple
machines (requires support from the test runner).
* Bug fixes and implementation clean-ups.
Changes for 1.2.1:
* Compatibility fixes for Linux IA-64 and IBM z/OS.
* Added support for using Boost and other TR1 implementations.
* Changes to the build scripts to support upcoming release of Google C++
Mocking Framework.
* Added Makefile to the distribution package.
* Improved build instructions in README.
Changes for 1.2.0:
* New feature: value-parameterized tests.
* New feature: the ASSERT/EXPECT_(NON)FATAL_FAILURE(_ON_ALL_THREADS)
macros.
* Changed the XML report format to match JUnit/Ant's.
* Added tests to the Xcode project.
* Added scons/SConscript for building with SCons.
* Added src/gtest-all.cc for building Google Test from a single file.
* Fixed compatibility with Solaris and z/OS.
* Enabled running Python tests on systems with python 2.3 installed,
e.g. Mac OS X 10.4.
* Bug fixes.
Changes for 1.1.0:
* New feature: type-parameterized tests.
* New feature: exception assertions.
* New feature: printing elapsed time of tests.
* Improved the robustness of death tests.
* Added an Xcode project and samples.
* Adjusted the output format on Windows to be understandable by Visual Studio.
* Minor bug fixes.
Changes for 1.0.1:
* Added project files for Visual Studio 7.1.
* Fixed issues with compiling on Mac OS X.
* Fixed issues with compiling on Cygwin.
Changes for 1.0.0:
* Initial Open Source release of Google Test

View File

@ -59,6 +59,16 @@ include_directories(
# Where Google Test's libraries can be found. # Where Google Test's libraries can be found.
link_directories(${gtest_BINARY_DIR}/src) link_directories(${gtest_BINARY_DIR}/src)
# Summary of tuple support for Microsoft Visual Studio:
# Compiler version(MS) version(cmake) Support
# ---------- ----------- -------------- -----------------------------
# <= VS 2010 <= 10 <= 1600 Use Google Tests's own tuple.
# VS 2012 11 1700 std::tr1::tuple + _VARIADIC_MAX=10
# VS 2013 12 1800 std::tr1::tuple
if (MSVC AND MSVC_VERSION EQUAL 1700)
add_definitions(/D _VARIADIC_MAX=10)
endif()
######################################################################## ########################################################################
# #
# Defines the gtest & gtest_main libraries. User tests should link # Defines the gtest & gtest_main libraries. User tests should link
@ -77,7 +87,7 @@ target_link_libraries(gtest_main gtest)
# #
# They are not built by default. To build them, set the # They are not built by default. To build them, set the
# gtest_build_samples option to ON. You can do it by running ccmake # gtest_build_samples option to ON. You can do it by running ccmake
# or specifying the -Dbuild_gtest_samples=ON flag when running cmake. # or specifying the -Dgtest_build_samples=ON flag when running cmake.
if (gtest_build_samples) if (gtest_build_samples)
cxx_executable(sample1_unittest samples gtest_main samples/sample1.cc) cxx_executable(sample1_unittest samples gtest_main samples/sample1.cc)
@ -124,6 +134,8 @@ if (gtest_build_tests)
test/gtest-param-test2_test.cc) test/gtest-param-test2_test.cc)
cxx_test(gtest-port_test gtest_main) cxx_test(gtest-port_test gtest_main)
cxx_test(gtest_pred_impl_unittest gtest_main) cxx_test(gtest_pred_impl_unittest gtest_main)
cxx_test(gtest_premature_exit_test gtest
test/gtest_premature_exit_test.cc)
cxx_test(gtest-printers_test gtest_main) cxx_test(gtest-printers_test gtest_main)
cxx_test(gtest_prod_test gtest_main cxx_test(gtest_prod_test gtest_main
test/production.cc) test/production.cc)
@ -140,10 +152,13 @@ if (gtest_build_tests)
############################################################ ############################################################
# C++ tests built with non-standard compiler flags. # C++ tests built with non-standard compiler flags.
# MSVC 7.1 does not support STL with exceptions disabled.
if (NOT MSVC OR MSVC_VERSION GREATER 1310)
cxx_library(gtest_no_exception "${cxx_no_exception}" cxx_library(gtest_no_exception "${cxx_no_exception}"
src/gtest-all.cc) src/gtest-all.cc)
cxx_library(gtest_main_no_exception "${cxx_no_exception}" cxx_library(gtest_main_no_exception "${cxx_no_exception}"
src/gtest-all.cc src/gtest_main.cc) src/gtest-all.cc src/gtest_main.cc)
endif()
cxx_library(gtest_main_no_rtti "${cxx_no_rtti}" cxx_library(gtest_main_no_rtti "${cxx_no_rtti}"
src/gtest-all.cc src/gtest_main.cc) src/gtest-all.cc src/gtest_main.cc)
@ -166,12 +181,10 @@ if (gtest_build_tests)
PROPERTIES PROPERTIES
COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
if (NOT MSVC OR NOT MSVC_VERSION EQUAL 1600) if (NOT MSVC OR MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010.
# The C++ Standard specifies tuple_element<int, class>. # Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that
# Yet MSVC 10's <utility> declares tuple_element<size_t, class>. # conflict with our own definitions. Therefore using our own tuple does not
# That declaration conflicts with our own standard-conforming # work on those compilers.
# tuple implementation. Therefore using our own tuple with
# MSVC 10 doesn't compile.
cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}" cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}"
src/gtest-all.cc src/gtest_main.cc) src/gtest-all.cc src/gtest_main.cc)
@ -189,11 +202,15 @@ if (gtest_build_tests)
cxx_executable(gtest_break_on_failure_unittest_ test gtest) cxx_executable(gtest_break_on_failure_unittest_ test gtest)
py_test(gtest_break_on_failure_unittest) py_test(gtest_break_on_failure_unittest)
# Visual Studio .NET 2003 does not support STL with exceptions disabled.
if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003
cxx_executable_with_flags( cxx_executable_with_flags(
gtest_catch_exceptions_no_ex_test_ gtest_catch_exceptions_no_ex_test_
"${cxx_no_exception}" "${cxx_no_exception}"
gtest_main_no_exception gtest_main_no_exception
test/gtest_catch_exceptions_test_.cc) test/gtest_catch_exceptions_test_.cc)
endif()
cxx_executable_with_flags( cxx_executable_with_flags(
gtest_catch_exceptions_ex_test_ gtest_catch_exceptions_ex_test_
"${cxx_exception}" "${cxx_exception}"
@ -222,11 +239,14 @@ if (gtest_build_tests)
cxx_executable(gtest_shuffle_test_ test gtest) cxx_executable(gtest_shuffle_test_ test gtest)
py_test(gtest_shuffle_test) py_test(gtest_shuffle_test)
# MSVC 7.1 does not support STL with exceptions disabled.
if (NOT MSVC OR MSVC_VERSION GREATER 1310)
cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception) cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception)
set_target_properties(gtest_throw_on_failure_test_ set_target_properties(gtest_throw_on_failure_test_
PROPERTIES PROPERTIES
COMPILE_FLAGS "${cxx_no_exception}") COMPILE_FLAGS "${cxx_no_exception}")
py_test(gtest_throw_on_failure_test) py_test(gtest_throw_on_failure_test)
endif()
cxx_executable(gtest_uninitialized_test_ test gtest) cxx_executable(gtest_uninitialized_test_ test gtest)
py_test(gtest_uninitialized_test) py_test(gtest_uninitialized_test)

37
tests/gtest/CONTRIBUTORS Normal file
View File

@ -0,0 +1,37 @@
# This file contains a list of people who've made non-trivial
# contribution to the Google C++ Testing Framework project. People
# who commit code to the project are encouraged to add their names
# here. Please keep the list sorted by first names.
Ajay Joshi <jaj@google.com>
Balázs Dán <balazs.dan@gmail.com>
Bharat Mediratta <bharat@menalto.com>
Chandler Carruth <chandlerc@google.com>
Chris Prince <cprince@google.com>
Chris Taylor <taylorc@google.com>
Dan Egnor <egnor@google.com>
Eric Roman <eroman@chromium.org>
Hady Zalek <hady.zalek@gmail.com>
Jeffrey Yasskin <jyasskin@google.com>
Jói Sigurðsson <joi@google.com>
Keir Mierle <mierle@gmail.com>
Keith Ray <keith.ray@gmail.com>
Kenton Varda <kenton@google.com>
Manuel Klimek <klimek@google.com>
Markus Heule <markus.heule@gmail.com>
Mika Raento <mikie@iki.fi>
Miklós Fazekas <mfazekas@szemafor.com>
Pasi Valminen <pasi.valminen@gmail.com>
Patrick Hanna <phanna@google.com>
Patrick Riley <pfr@google.com>
Peter Kaminski <piotrk@google.com>
Preston Jackson <preston.a.jackson@gmail.com>
Rainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>
Russ Cox <rsc@google.com>
Russ Rufer <russ@pentad.com>
Sean Mcafee <eefacm@gmail.com>
Sigurður Ásgeirsson <siggi@google.com>
Tracy Bialik <tracy@pentad.com>
Vadim Berman <vadimb@google.com>
Vlad Losev <vladl@google.com>
Zhanyong Wan <wan@google.com>

28
tests/gtest/LICENSE Normal file
View File

@ -0,0 +1,28 @@
Copyright 2008, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

435
tests/gtest/README Normal file
View File

@ -0,0 +1,435 @@
Google C++ Testing Framework
============================
http://code.google.com/p/googletest/
Overview
--------
Google's framework for writing C++ tests on a variety of platforms
(Linux, Mac OS X, Windows, Windows CE, Symbian, etc). Based on the
xUnit architecture. Supports automatic test discovery, a rich set of
assertions, user-defined assertions, death tests, fatal and non-fatal
failures, various options for running the tests, and XML test report
generation.
Please see the project page above for more information as well as the
mailing list for questions, discussions, and development. There is
also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please
join us!
Requirements for End Users
--------------------------
Google Test is designed to have fairly minimal requirements to build
and use with your projects, but there are some. Currently, we support
Linux, Windows, Mac OS X, and Cygwin. We will also make our best
effort to support other platforms (e.g. Solaris, AIX, and z/OS).
However, since core members of the Google Test project have no access
to these platforms, Google Test may have outstanding issues there. If
you notice any problems on your platform, please notify
googletestframework@googlegroups.com. Patches for fixing them are
even more welcome!
### Linux Requirements ###
These are the base requirements to build and use Google Test from a source
package (as described below):
* GNU-compatible Make or gmake
* POSIX-standard shell
* POSIX(-2) Regular Expressions (regex.h)
* A C++98-standard-compliant compiler
### Windows Requirements ###
* Microsoft Visual C++ 7.1 or newer
### Cygwin Requirements ###
* Cygwin 1.5.25-14 or newer
### Mac OS X Requirements ###
* Mac OS X 10.4 Tiger or newer
* Developer Tools Installed
Also, you'll need CMake 2.6.4 or higher if you want to build the
samples using the provided CMake script, regardless of the platform.
Requirements for Contributors
-----------------------------
We welcome patches. If you plan to contribute a patch, you need to
build Google Test and its own tests from an SVN checkout (described
below), which has further requirements:
* Python version 2.3 or newer (for running some of the tests and
re-generating certain source files from templates)
* CMake 2.6.4 or newer
Getting the Source
------------------
There are two primary ways of getting Google Test's source code: you
can download a stable source release in your preferred archive format,
or directly check out the source from our Subversion (SVN) repository.
The SVN checkout requires a few extra steps and some extra software
packages on your system, but lets you track the latest development and
make patches much more easily, so we highly encourage it.
### Source Package ###
Google Test is released in versioned source packages which can be
downloaded from the download page [1]. Several different archive
formats are provided, but the only difference is the tools used to
manipulate them, and the size of the resulting file. Download
whichever you are most comfortable with.
[1] http://code.google.com/p/googletest/downloads/list
Once the package is downloaded, expand it using whichever tools you
prefer for that type. This will result in a new directory with the
name "gtest-X.Y.Z" which contains all of the source code. Here are
some examples on Linux:
tar -xvzf gtest-X.Y.Z.tar.gz
tar -xvjf gtest-X.Y.Z.tar.bz2
unzip gtest-X.Y.Z.zip
### SVN Checkout ###
To check out the main branch (also known as the "trunk") of Google
Test, run the following Subversion command:
svn checkout http://googletest.googlecode.com/svn/trunk/ gtest-svn
Setting up the Build
--------------------
To build Google Test and your tests that use it, you need to tell your
build system where to find its headers and source files. The exact
way to do it depends on which build system you use, and is usually
straightforward.
### Generic Build Instructions ###
Suppose you put Google Test in directory ${GTEST_DIR}. To build it,
create a library build target (or a project as called by Visual Studio
and Xcode) to compile
${GTEST_DIR}/src/gtest-all.cc
with ${GTEST_DIR}/include in the system header search path and ${GTEST_DIR}
in the normal header search path. Assuming a Linux-like system and gcc,
something like the following will do:
g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
-pthread -c ${GTEST_DIR}/src/gtest-all.cc
ar -rv libgtest.a gtest-all.o
(We need -pthread as Google Test uses threads.)
Next, you should compile your test source file with
${GTEST_DIR}/include in the system header search path, and link it
with gtest and any other necessary libraries:
g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \
-o your_test
As an example, the make/ directory contains a Makefile that you can
use to build Google Test on systems where GNU make is available
(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google
Test's own tests. Instead, it just builds the Google Test library and
a sample test. You can use it as a starting point for your own build
script.
If the default settings are correct for your environment, the
following commands should succeed:
cd ${GTEST_DIR}/make
make
./sample1_unittest
If you see errors, try to tweak the contents of make/Makefile to make
them go away. There are instructions in make/Makefile on how to do
it.
### Using CMake ###
Google Test comes with a CMake build script (CMakeLists.txt) that can
be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for
free from http://www.cmake.org/.
CMake works by generating native makefiles or build projects that can
be used in the compiler environment of your choice. The typical
workflow starts with:
mkdir mybuild # Create a directory to hold the build output.
cd mybuild
cmake ${GTEST_DIR} # Generate native build scripts.
If you want to build Google Test's samples, you should replace the
last command with
cmake -Dgtest_build_samples=ON ${GTEST_DIR}
If you are on a *nix system, you should now see a Makefile in the
current directory. Just type 'make' to build gtest.
If you use Windows and have Visual Studio installed, a gtest.sln file
and several .vcproj files will be created. You can then build them
using Visual Studio.
On Mac OS X with Xcode installed, a .xcodeproj file will be generated.
### Legacy Build Scripts ###
Before settling on CMake, we have been providing hand-maintained build
projects/scripts for Visual Studio, Xcode, and Autotools. While we
continue to provide them for convenience, they are not actively
maintained any more. We highly recommend that you follow the
instructions in the previous two sections to integrate Google Test
with your existing build system.
If you still need to use the legacy build scripts, here's how:
The msvc\ folder contains two solutions with Visual C++ projects.
Open the gtest.sln or gtest-md.sln file using Visual Studio, and you
are ready to build Google Test the same way you build any Visual
Studio project. Files that have names ending with -md use DLL
versions of Microsoft runtime libraries (the /MD or the /MDd compiler
option). Files without that suffix use static versions of the runtime
libraries (the /MT or the /MTd option). Please note that one must use
the same option to compile both gtest and the test code. If you use
Visual Studio 2005 or above, we recommend the -md version as /MD is
the default for new projects in these versions of Visual Studio.
On Mac OS X, open the gtest.xcodeproj in the xcode/ folder using
Xcode. Build the "gtest" target. The universal binary framework will
end up in your selected build directory (selected in the Xcode
"Preferences..." -> "Building" pane and defaults to xcode/build).
Alternatively, at the command line, enter:
xcodebuild
This will build the "Release" configuration of gtest.framework in your
default build location. See the "xcodebuild" man page for more
information about building different configurations and building in
different locations.
If you wish to use the Google Test Xcode project with Xcode 4.x and
above, you need to either:
* update the SDK configuration options in xcode/Config/General.xconfig.
Comment options SDKROOT, MACOS_DEPLOYMENT_TARGET, and GCC_VERSION. If
you choose this route you lose the ability to target earlier versions
of MacOS X.
* Install an SDK for an earlier version. This doesn't appear to be
supported by Apple, but has been reported to work
(http://stackoverflow.com/questions/5378518).
Tweaking Google Test
--------------------
Google Test can be used in diverse environments. The default
configuration may not work (or may not work well) out of the box in
some environments. However, you can easily tweak Google Test by
defining control macros on the compiler command line. Generally,
these macros are named like GTEST_XYZ and you define them to either 1
or 0 to enable or disable a certain feature.
We list the most frequently used macros below. For a complete list,
see file include/gtest/internal/gtest-port.h.
### Choosing a TR1 Tuple Library ###
Some Google Test features require the C++ Technical Report 1 (TR1)
tuple library, which is not yet available with all compilers. The
good news is that Google Test implements a subset of TR1 tuple that's
enough for its own need, and will automatically use this when the
compiler doesn't provide TR1 tuple.
Usually you don't need to care about which tuple library Google Test
uses. However, if your project already uses TR1 tuple, you need to
tell Google Test to use the same TR1 tuple library the rest of your
project uses, or the two tuple implementations will clash. To do
that, add
-DGTEST_USE_OWN_TR1_TUPLE=0
to the compiler flags while compiling Google Test and your tests. If
you want to force Google Test to use its own tuple library, just add
-DGTEST_USE_OWN_TR1_TUPLE=1
to the compiler flags instead.
If you don't want Google Test to use tuple at all, add
-DGTEST_HAS_TR1_TUPLE=0
and all features using tuple will be disabled.
### Multi-threaded Tests ###
Google Test is thread-safe where the pthread library is available.
After #include "gtest/gtest.h", you can check the GTEST_IS_THREADSAFE
macro to see whether this is the case (yes if the macro is #defined to
1, no if it's undefined.).
If Google Test doesn't correctly detect whether pthread is available
in your environment, you can force it with
-DGTEST_HAS_PTHREAD=1
or
-DGTEST_HAS_PTHREAD=0
When Google Test uses pthread, you may need to add flags to your
compiler and/or linker to select the pthread library, or you'll get
link errors. If you use the CMake script or the deprecated Autotools
script, this is taken care of for you. If you use your own build
script, you'll need to read your compiler and linker's manual to
figure out what flags to add.
### As a Shared Library (DLL) ###
Google Test is compact, so most users can build and link it as a
static library for the simplicity. You can choose to use Google Test
as a shared library (known as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add
-DGTEST_CREATE_SHARED_LIBRARY=1
to the compiler flags. You'll also need to tell the linker to produce
a shared library instead - consult your linker's manual for how to do
it.
To compile your *tests* that use the gtest shared library, add
-DGTEST_LINKED_AS_SHARED_LIBRARY=1
to the compiler flags.
Note: while the above steps aren't technically necessary today when
using some compilers (e.g. GCC), they may become necessary in the
future, if we decide to improve the speed of loading the library (see
http://gcc.gnu.org/wiki/Visibility for details). Therefore you are
recommended to always add the above flags when using Google Test as a
shared library. Otherwise a future release of Google Test may break
your build script.
### Avoiding Macro Name Clashes ###
In C++, macros don't obey namespaces. Therefore two libraries that
both define a macro of the same name will clash if you #include both
definitions. In case a Google Test macro clashes with another
library, you can force Google Test to rename its macro to avoid the
conflict.
Specifically, if both Google Test and some other code define macro
FOO, you can add
-DGTEST_DONT_DEFINE_FOO=1
to the compiler flags to tell Google Test to change the macro's name
from FOO to GTEST_FOO. Currently FOO can be FAIL, SUCCEED, or TEST.
For example, with -DGTEST_DONT_DEFINE_TEST=1, you'll need to write
GTEST_TEST(SomeTest, DoesThis) { ... }
instead of
TEST(SomeTest, DoesThis) { ... }
in order to define a test.
Upgrating from an Earlier Version
---------------------------------
We strive to keep Google Test releases backward compatible.
Sometimes, though, we have to make some breaking changes for the
users' long-term benefits. This section describes what you'll need to
do if you are upgrading from an earlier version of Google Test.
### Upgrading from 1.3.0 or Earlier ###
You may need to explicitly enable or disable Google Test's own TR1
tuple library. See the instructions in section "Choosing a TR1 Tuple
Library".
### Upgrading from 1.4.0 or Earlier ###
The Autotools build script (configure + make) is no longer officially
supportted. You are encouraged to migrate to your own build system or
use CMake. If you still need to use Autotools, you can find
instructions in the README file from Google Test 1.4.0.
On platforms where the pthread library is available, Google Test uses
it in order to be thread-safe. See the "Multi-threaded Tests" section
for what this means to your build script.
If you use Microsoft Visual C++ 7.1 with exceptions disabled, Google
Test will no longer compile. This should affect very few people, as a
large portion of STL (including <string>) doesn't compile in this mode
anyway. We decided to stop supporting it in order to greatly simplify
Google Test's implementation.
Developing Google Test
----------------------
This section discusses how to make your own changes to Google Test.
### Testing Google Test Itself ###
To make sure your changes work as intended and don't break existing
functionality, you'll want to compile and run Google Test's own tests.
For that you can use CMake:
mkdir mybuild
cd mybuild
cmake -Dgtest_build_tests=ON ${GTEST_DIR}
Make sure you have Python installed, as some of Google Test's tests
are written in Python. If the cmake command complains about not being
able to find Python ("Could NOT find PythonInterp (missing:
PYTHON_EXECUTABLE)"), try telling it explicitly where your Python
executable can be found:
cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR}
Next, you can build Google Test and all of its own tests. On *nix,
this is usually done by 'make'. To run the tests, do
make test
All tests should pass.
### Regenerating Source Files ###
Some of Google Test's source files are generated from templates (not
in the C++ sense) using a script. A template file is named FOO.pump,
where FOO is the name of the file it will generate. For example, the
file include/gtest/internal/gtest-type-util.h.pump is used to generate
gtest-type-util.h in the same directory.
Normally you don't need to worry about regenerating the source files,
unless you need to modify them. In that case, you should modify the
corresponding .pump files instead and run the pump.py Python script to
regenerate them. You can find pump.py in the scripts/ directory.
Read the Pump manual [2] for how to use it.
[2] http://code.google.com/p/googletest/wiki/PumpManual
### Contributing a Patch ###
We welcome patches. Please read the Google Test developer's guide [3]
for how you can contribute. In particular, make sure you have signed
the Contributor License Agreement, or we won't be able to accept the
patch.
[3] http://code.google.com/p/googletest/wiki/GoogleTestDevGuide
Happy testing!

View File

@ -37,7 +37,7 @@ macro(fix_default_compiler_settings_)
# We prefer more strict warning checking for building Google Test. # We prefer more strict warning checking for building Google Test.
# Replaces /W3 with /W4 in defaults. # Replaces /W3 with /W4 in defaults.
string(REPLACE "/W3" "-W4" ${flag_var} "${${flag_var}}") string(REPLACE "/W3" "/W4" ${flag_var} "${${flag_var}}")
endforeach() endforeach()
endif() endif()
endmacro() endmacro()
@ -55,7 +55,32 @@ macro(config_compiler_and_linker)
if (MSVC) if (MSVC)
# Newlines inside flags variables break CMake's NMake generator. # Newlines inside flags variables break CMake's NMake generator.
# TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds. # TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.
set(cxx_base_flags "-GS -W4 -WX -wd4127 -wd4251 -wd4275 -nologo -J -Zi") set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi")
if (MSVC_VERSION LESS 1400) # 1400 is Visual Studio 2005
# Suppress spurious warnings MSVC 7.1 sometimes issues.
# Forcing value to bool.
set(cxx_base_flags "${cxx_base_flags} -wd4800")
# Copy constructor and assignment operator could not be generated.
set(cxx_base_flags "${cxx_base_flags} -wd4511 -wd4512")
# Compatibility warnings not applicable to Google Test.
# Resolved overload was found by argument-dependent lookup.
set(cxx_base_flags "${cxx_base_flags} -wd4675")
endif()
if (MSVC_VERSION LESS 1500) # 1500 is Visual Studio 2008
# Conditional expression is constant.
# When compiling with /W4, we get several instances of C4127
# (Conditional expression is constant). In our code, we disable that
# warning on a case-by-case basis. However, on Visual Studio 2005,
# the warning fires on std::list. Therefore on that compiler and earlier,
# we disable the warning project-wide.
set(cxx_base_flags "${cxx_base_flags} -wd4127")
endif()
if (NOT (MSVC_VERSION LESS 1700)) # 1700 is Visual Studio 2012.
# Suppress "unreachable code" warning on VS 2012 and later.
# http://stackoverflow.com/questions/3232669 explains the issue.
set(cxx_base_flags "${cxx_base_flags} -wd4702")
endif()
set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32") set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32")
set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN") set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN")
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
@ -69,7 +94,8 @@ macro(config_compiler_and_linker)
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
# explicitly. # explicitly.
set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0")
set(cxx_strict_flags "-Wextra") set(cxx_strict_flags
"-Wextra -Wno-unused-parameter -Wno-missing-field-initializers")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro")
set(cxx_exception_flags "-features=except") set(cxx_exception_flags "-features=except")
# Sun Pro doesn't provide macros to indicate whether exceptions and # Sun Pro doesn't provide macros to indicate whether exceptions and

View File

@ -51,6 +51,17 @@ GTEST_DECLARE_string_(death_test_style);
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
namespace internal {
// Returns a Boolean value indicating whether the caller is currently
// executing in the context of the death test child process. Tools such as
// Valgrind heap checkers may need this to modify their behavior in death
// tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it.
GTEST_API_ bool InDeathTestChild();
} // namespace internal
// The following macros are useful for writing death tests. // The following macros are useful for writing death tests.
// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
@ -75,7 +86,7 @@ GTEST_DECLARE_string_(death_test_style);
// for (int i = 0; i < 5; i++) { // for (int i = 0; i < 5; i++) {
// EXPECT_DEATH(server.ProcessRequest(i), // EXPECT_DEATH(server.ProcessRequest(i),
// "Invalid request .* in ProcessRequest()") // "Invalid request .* in ProcessRequest()")
// << "Failed to die on request " << i); // << "Failed to die on request " << i;
// } // }
// //
// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
@ -245,10 +256,10 @@ class GTEST_API_ KilledBySignal {
# ifdef NDEBUG # ifdef NDEBUG
# define EXPECT_DEBUG_DEATH(statement, regex) \ # define EXPECT_DEBUG_DEATH(statement, regex) \
do { statement; } while (::testing::internal::AlwaysFalse()) GTEST_EXECUTE_STATEMENT_(statement, regex)
# define ASSERT_DEBUG_DEATH(statement, regex) \ # define ASSERT_DEBUG_DEATH(statement, regex) \
do { statement; } while (::testing::internal::AlwaysFalse()) GTEST_EXECUTE_STATEMENT_(statement, regex)
# else # else

View File

@ -48,8 +48,11 @@
#include <limits> #include <limits>
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-internal.h"
// Ensures that there is at least one operator<< in the global namespace.
// See Message& operator<<(...) below for why.
void operator<<(const testing::internal::Secret&, int);
namespace testing { namespace testing {
@ -87,15 +90,7 @@ class GTEST_API_ Message {
public: public:
// Constructs an empty Message. // Constructs an empty Message.
// We allocate the stringstream separately because otherwise each use of Message();
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
// stack frame leading to huge stack frames in some cases; gcc does not reuse
// the stack space.
Message() : ss_(new ::std::stringstream) {
// By default, we want there to be enough precision when printing
// a double to a Message.
*ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
}
// Copy constructor. // Copy constructor.
Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
@ -118,7 +113,22 @@ class GTEST_API_ Message {
// Streams a non-pointer value to this object. // Streams a non-pointer value to this object.
template <typename T> template <typename T>
inline Message& operator <<(const T& val) { inline Message& operator <<(const T& val) {
::GTestStreamToHelper(ss_.get(), val); // Some libraries overload << for STL containers. These
// overloads are defined in the global namespace instead of ::std.
//
// C++'s symbol lookup rule (i.e. Koenig lookup) says that these
// overloads are visible in either the std namespace or the global
// namespace, but not other namespaces, including the testing
// namespace which Google Test's Message class is in.
//
// To allow STL containers (and other types that has a << operator
// defined in the global namespace) to be used in Google Test
// assertions, testing::Message must access the custom << operator
// from the global namespace. With this using declaration,
// overloads of << defined in the global namespace and those
// visible via Koenig lookup are both exposed in this function.
using ::operator <<;
*ss_ << val;
return *this; return *this;
} }
@ -140,7 +150,7 @@ class GTEST_API_ Message {
if (pointer == NULL) { if (pointer == NULL) {
*ss_ << "(null)"; *ss_ << "(null)";
} else { } else {
::GTestStreamToHelper(ss_.get(), pointer); *ss_ << pointer;
} }
return *this; return *this;
} }
@ -164,12 +174,8 @@ class GTEST_API_ Message {
// These two overloads allow streaming a wide C string to a Message // These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding. // using the UTF-8 encoding.
Message& operator <<(const wchar_t* wide_c_str) { Message& operator <<(const wchar_t* wide_c_str);
return *this << internal::String::ShowWideCString(wide_c_str); Message& operator <<(wchar_t* wide_c_str);
}
Message& operator <<(wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8 // Converts the given wide string to a narrow string using the UTF-8
@ -183,13 +189,11 @@ class GTEST_API_ Message {
Message& operator <<(const ::wstring& wstr); Message& operator <<(const ::wstring& wstr);
#endif // GTEST_HAS_GLOBAL_WSTRING #endif // GTEST_HAS_GLOBAL_WSTRING
// Gets the text streamed to this object so far as a String. // Gets the text streamed to this object so far as an std::string.
// Each '\0' character in the buffer is replaced with "\\0". // Each '\0' character in the buffer is replaced with "\\0".
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
internal::String GetString() const { std::string GetString() const;
return internal::StringStreamToString(ss_.get());
}
private: private:
@ -199,16 +203,20 @@ class GTEST_API_ Message {
// decide between class template specializations for T and T*, so a // decide between class template specializations for T and T*, so a
// tr1::type_traits-like is_pointer works, and we can overload on that. // tr1::type_traits-like is_pointer works, and we can overload on that.
template <typename T> template <typename T>
inline void StreamHelper(internal::true_type /*dummy*/, T* pointer) { inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) {
if (pointer == NULL) { if (pointer == NULL) {
*ss_ << "(null)"; *ss_ << "(null)";
} else { } else {
::GTestStreamToHelper(ss_.get(), pointer); *ss_ << pointer;
} }
} }
template <typename T> template <typename T>
inline void StreamHelper(internal::false_type /*dummy*/, const T& value) { inline void StreamHelper(internal::false_type /*is_pointer*/,
::GTestStreamToHelper(ss_.get(), value); const T& value) {
// See the comments in Message& operator <<(const T&) above for why
// we need this using statement.
using ::operator <<;
*ss_ << value;
} }
#endif // GTEST_OS_SYMBIAN #endif // GTEST_OS_SYMBIAN
@ -225,6 +233,18 @@ inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
return os << sb.GetString(); return os << sb.GetString();
} }
namespace internal {
// Converts a streamable value to an std::string. A NULL pointer is
// converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0".
template <typename T>
std::string StreamableToString(const T& streamable) {
return (Message() << streamable).GetString();
}
} // namespace internal
} // namespace testing } // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_

View File

@ -1257,7 +1257,7 @@ inline internal::ParamGenerator<bool> Bool() {
// Boolean flags: // Boolean flags:
// //
// class FlagDependentTest // class FlagDependentTest
// : public testing::TestWithParam<tuple(bool, bool)> > { // : public testing::TestWithParam<tuple<bool, bool> > {
// virtual void SetUp() { // virtual void SetUp() {
// // Assigns external_flag_1 and external_flag_2 values from the tuple. // // Assigns external_flag_1 and external_flag_2 values from the tuple.
// tie(external_flag_1, external_flag_2) = GetParam(); // tie(external_flag_1, external_flag_2) = GetParam();

View File

@ -414,7 +414,7 @@ inline internal::ParamGenerator<bool> Bool() {
// Boolean flags: // Boolean flags:
// //
// class FlagDependentTest // class FlagDependentTest
// : public testing::TestWithParam<tuple(bool, bool)> > { // : public testing::TestWithParam<tuple<bool, bool> > {
// virtual void SetUp() { // virtual void SetUp() {
// // Assigns external_flag_1 and external_flag_2 values from the tuple. // // Assigns external_flag_1 and external_flag_2 values from the tuple.
// tie(external_flag_1, external_flag_2) = GetParam(); // tie(external_flag_1, external_flag_2) = GetParam();

View File

@ -103,6 +103,10 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#if GTEST_HAS_STD_TUPLE_
# include <tuple>
#endif
namespace testing { namespace testing {
// Definitions in the 'internal' and 'internal2' name spaces are // Definitions in the 'internal' and 'internal2' name spaces are
@ -480,14 +484,16 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_TR1_TUPLE #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
// Overload for ::std::tr1::tuple. Needed for printing function arguments,
// which are packed as tuples.
// Helper function for printing a tuple. T must be instantiated with // Helper function for printing a tuple. T must be instantiated with
// a tuple type. // a tuple type.
template <typename T> template <typename T>
void PrintTupleTo(const T& t, ::std::ostream* os); void PrintTupleTo(const T& t, ::std::ostream* os);
#endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
#if GTEST_HAS_TR1_TUPLE
// Overload for ::std::tr1::tuple. Needed for printing function arguments,
// which are packed as tuples.
// Overloaded PrintTo() for tuples of various arities. We support // Overloaded PrintTo() for tuples of various arities. We support
// tuples of up-to 10 fields. The following implementation works // tuples of up-to 10 fields. The following implementation works
@ -561,6 +567,13 @@ void PrintTo(
} }
#endif // GTEST_HAS_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE
#if GTEST_HAS_STD_TUPLE_
template <typename... Types>
void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
PrintTupleTo(t, os);
}
#endif // GTEST_HAS_STD_TUPLE_
// Overload for std::pair. // Overload for std::pair.
template <typename T1, typename T2> template <typename T1, typename T2>
void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) { void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
@ -580,10 +593,7 @@ class UniversalPrinter {
public: public:
// MSVC warns about adding const to a function type, so we want to // MSVC warns about adding const to a function type, so we want to
// disable the warning. // disable the warning.
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4180) // Temporarily disables warning 4180.
#endif // _MSC_VER
// Note: we deliberately don't call this PrintTo(), as that name // Note: we deliberately don't call this PrintTo(), as that name
// conflicts with ::testing::internal::PrintTo in the body of the // conflicts with ::testing::internal::PrintTo in the body of the
@ -600,9 +610,7 @@ class UniversalPrinter {
PrintTo(value, os); PrintTo(value, os);
} }
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_()
# pragma warning(pop) // Restores the warning state.
#endif // _MSC_VER
}; };
// UniversalPrintArray(begin, len, os) prints an array of 'len' // UniversalPrintArray(begin, len, os) prints an array of 'len'
@ -630,9 +638,12 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
} }
} }
// This overload prints a (const) char array compactly. // This overload prints a (const) char array compactly.
GTEST_API_ void UniversalPrintArray(const char* begin, GTEST_API_ void UniversalPrintArray(
size_t len, const char* begin, size_t len, ::std::ostream* os);
::std::ostream* os);
// This overload prints a (const) wchar_t array compactly.
GTEST_API_ void UniversalPrintArray(
const wchar_t* begin, size_t len, ::std::ostream* os);
// Implements printing an array type T[N]. // Implements printing an array type T[N].
template <typename T, size_t N> template <typename T, size_t N>
@ -651,10 +662,7 @@ class UniversalPrinter<T&> {
public: public:
// MSVC warns about adding const to a function type, so we want to // MSVC warns about adding const to a function type, so we want to
// disable the warning. // disable the warning.
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4180) // Temporarily disables warning 4180.
#endif // _MSC_VER
static void Print(const T& value, ::std::ostream* os) { static void Print(const T& value, ::std::ostream* os) {
// Prints the address of the value. We use reinterpret_cast here // Prints the address of the value. We use reinterpret_cast here
@ -665,27 +673,78 @@ class UniversalPrinter<T&> {
UniversalPrint(value, os); UniversalPrint(value, os);
} }
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_()
# pragma warning(pop) // Restores the warning state.
#endif // _MSC_VER
}; };
// Prints a value tersely: for a reference type, the referenced value // Prints a value tersely: for a reference type, the referenced value
// (but not the address) is printed; for a (const) char pointer, the // (but not the address) is printed; for a (const) char pointer, the
// NUL-terminated string (but not the pointer) is printed. // NUL-terminated string (but not the pointer) is printed.
template <typename T> template <typename T>
void UniversalTersePrint(const T& value, ::std::ostream* os) { class UniversalTersePrinter {
public:
static void Print(const T& value, ::std::ostream* os) {
UniversalPrint(value, os); UniversalPrint(value, os);
} }
inline void UniversalTersePrint(const char* str, ::std::ostream* os) { };
template <typename T>
class UniversalTersePrinter<T&> {
public:
static void Print(const T& value, ::std::ostream* os) {
UniversalPrint(value, os);
}
};
template <typename T, size_t N>
class UniversalTersePrinter<T[N]> {
public:
static void Print(const T (&value)[N], ::std::ostream* os) {
UniversalPrinter<T[N]>::Print(value, os);
}
};
template <>
class UniversalTersePrinter<const char*> {
public:
static void Print(const char* str, ::std::ostream* os) {
if (str == NULL) { if (str == NULL) {
*os << "NULL"; *os << "NULL";
} else { } else {
UniversalPrint(string(str), os); UniversalPrint(string(str), os);
} }
} }
inline void UniversalTersePrint(char* str, ::std::ostream* os) { };
UniversalTersePrint(static_cast<const char*>(str), os); template <>
class UniversalTersePrinter<char*> {
public:
static void Print(char* str, ::std::ostream* os) {
UniversalTersePrinter<const char*>::Print(str, os);
}
};
#if GTEST_HAS_STD_WSTRING
template <>
class UniversalTersePrinter<const wchar_t*> {
public:
static void Print(const wchar_t* str, ::std::ostream* os) {
if (str == NULL) {
*os << "NULL";
} else {
UniversalPrint(::std::wstring(str), os);
}
}
};
#endif
template <>
class UniversalTersePrinter<wchar_t*> {
public:
static void Print(wchar_t* str, ::std::ostream* os) {
UniversalTersePrinter<const wchar_t*>::Print(str, os);
}
};
template <typename T>
void UniversalTersePrint(const T& value, ::std::ostream* os) {
UniversalTersePrinter<T>::Print(value, os);
} }
// Prints a value using the type inferred by the compiler. The // Prints a value using the type inferred by the compiler. The
@ -694,19 +753,71 @@ inline void UniversalTersePrint(char* str, ::std::ostream* os) {
// NUL-terminated string. // NUL-terminated string.
template <typename T> template <typename T>
void UniversalPrint(const T& value, ::std::ostream* os) { void UniversalPrint(const T& value, ::std::ostream* os) {
UniversalPrinter<T>::Print(value, os); // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
// UniversalPrinter with T directly.
typedef T T1;
UniversalPrinter<T1>::Print(value, os);
} }
#if GTEST_HAS_TR1_TUPLE
typedef ::std::vector<string> Strings; typedef ::std::vector<string> Strings;
// TuplePolicy<TupleT> must provide:
// - tuple_size
// size of tuple TupleT.
// - get<size_t I>(const TupleT& t)
// static function extracting element I of tuple TupleT.
// - tuple_element<size_t I>::type
// type of element I of tuple TupleT.
template <typename TupleT>
struct TuplePolicy;
#if GTEST_HAS_TR1_TUPLE
template <typename TupleT>
struct TuplePolicy {
typedef TupleT Tuple;
static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value;
template <size_t I>
struct tuple_element : ::std::tr1::tuple_element<I, Tuple> {};
template <size_t I>
static typename AddReference<
const typename ::std::tr1::tuple_element<I, Tuple>::type>::type get(
const Tuple& tuple) {
return ::std::tr1::get<I>(tuple);
}
};
template <typename TupleT>
const size_t TuplePolicy<TupleT>::tuple_size;
#endif // GTEST_HAS_TR1_TUPLE
#if GTEST_HAS_STD_TUPLE_
template <typename... Types>
struct TuplePolicy< ::std::tuple<Types...> > {
typedef ::std::tuple<Types...> Tuple;
static const size_t tuple_size = ::std::tuple_size<Tuple>::value;
template <size_t I>
struct tuple_element : ::std::tuple_element<I, Tuple> {};
template <size_t I>
static const typename ::std::tuple_element<I, Tuple>::type& get(
const Tuple& tuple) {
return ::std::get<I>(tuple);
}
};
template <typename... Types>
const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size;
#endif // GTEST_HAS_STD_TUPLE_
#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
// This helper template allows PrintTo() for tuples and // This helper template allows PrintTo() for tuples and
// UniversalTersePrintTupleFieldsToStrings() to be defined by // UniversalTersePrintTupleFieldsToStrings() to be defined by
// induction on the number of tuple fields. The idea is that // induction on the number of tuple fields. The idea is that
// TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N // TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N
// fields in tuple t, and can be defined in terms of // fields in tuple t, and can be defined in terms of
// TuplePrefixPrinter<N - 1>. // TuplePrefixPrinter<N - 1>.
//
// The inductive case. // The inductive case.
template <size_t N> template <size_t N>
struct TuplePrefixPrinter { struct TuplePrefixPrinter {
@ -714,9 +825,14 @@ struct TuplePrefixPrinter {
template <typename Tuple> template <typename Tuple>
static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os); TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (N > 1) {
GTEST_INTENTIONAL_CONST_COND_POP_()
*os << ", "; *os << ", ";
UniversalPrinter<typename ::std::tr1::tuple_element<N - 1, Tuple>::type> }
::Print(::std::tr1::get<N - 1>(t), os); UniversalPrinter<
typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type>
::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os);
} }
// Tersely prints the first N fields of a tuple to a string vector, // Tersely prints the first N fields of a tuple to a string vector,
@ -725,12 +841,12 @@ struct TuplePrefixPrinter {
static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {
TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings); TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings);
::std::stringstream ss; ::std::stringstream ss;
UniversalTersePrint(::std::tr1::get<N - 1>(t), &ss); UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss);
strings->push_back(ss.str()); strings->push_back(ss.str());
} }
}; };
// Base cases. // Base case.
template <> template <>
struct TuplePrefixPrinter<0> { struct TuplePrefixPrinter<0> {
template <typename Tuple> template <typename Tuple>
@ -739,34 +855,13 @@ struct TuplePrefixPrinter<0> {
template <typename Tuple> template <typename Tuple>
static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}
}; };
// We have to specialize the entire TuplePrefixPrinter<> class
// template here, even though the definition of
// TersePrintPrefixToStrings() is the same as the generic version, as
// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't
// support specializing a method template of a class template.
template <>
struct TuplePrefixPrinter<1> {
template <typename Tuple>
static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
UniversalPrinter<typename ::std::tr1::tuple_element<0, Tuple>::type>::
Print(::std::tr1::get<0>(t), os);
}
// Helper function for printing a tuple.
// Tuple must be either std::tr1::tuple or std::tuple type.
template <typename Tuple> template <typename Tuple>
static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { void PrintTupleTo(const Tuple& t, ::std::ostream* os) {
::std::stringstream ss;
UniversalTersePrint(::std::tr1::get<0>(t), &ss);
strings->push_back(ss.str());
}
};
// Helper function for printing a tuple. T must be instantiated with
// a tuple type.
template <typename T>
void PrintTupleTo(const T& t, ::std::ostream* os) {
*os << "("; *os << "(";
TuplePrefixPrinter< ::std::tr1::tuple_size<T>::value>:: TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os);
PrintPrefixTo(t, os);
*os << ")"; *os << ")";
} }
@ -776,18 +871,18 @@ void PrintTupleTo(const T& t, ::std::ostream* os) {
template <typename Tuple> template <typename Tuple>
Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
Strings result; Strings result;
TuplePrefixPrinter< ::std::tr1::tuple_size<Tuple>::value>:: TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::
TersePrintPrefixToStrings(value, &result); TersePrintPrefixToStrings(value, &result);
return result; return result;
} }
#endif // GTEST_HAS_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
} // namespace internal } // namespace internal
template <typename T> template <typename T>
::std::string PrintToString(const T& value) { ::std::string PrintToString(const T& value) {
::std::stringstream ss; ::std::stringstream ss;
internal::UniversalTersePrint(value, &ss); internal::UniversalTersePrinter<T>::Print(value, &ss);
return ss.str(); return ss.str();
} }

View File

@ -62,7 +62,7 @@ class GTEST_API_ TestPartResult {
int a_line_number, int a_line_number,
const char* a_message) const char* a_message)
: type_(a_type), : type_(a_type),
file_name_(a_file_name), file_name_(a_file_name == NULL ? "" : a_file_name),
line_number_(a_line_number), line_number_(a_line_number),
summary_(ExtractSummary(a_message)), summary_(ExtractSummary(a_message)),
message_(a_message) { message_(a_message) {
@ -73,7 +73,9 @@ class GTEST_API_ TestPartResult {
// Gets the name of the source file where the test part took place, or // Gets the name of the source file where the test part took place, or
// NULL if it's unknown. // NULL if it's unknown.
const char* file_name() const { return file_name_.c_str(); } const char* file_name() const {
return file_name_.empty() ? NULL : file_name_.c_str();
}
// Gets the line in the source file where the test part took place, // Gets the line in the source file where the test part took place,
// or -1 if it's unknown. // or -1 if it's unknown.
@ -96,21 +98,22 @@ class GTEST_API_ TestPartResult {
// Returns true iff the test part fatally failed. // Returns true iff the test part fatally failed.
bool fatally_failed() const { return type_ == kFatalFailure; } bool fatally_failed() const { return type_ == kFatalFailure; }
private: private:
Type type_; Type type_;
// Gets the summary of the failure message by omitting the stack // Gets the summary of the failure message by omitting the stack
// trace in it. // trace in it.
static internal::String ExtractSummary(const char* message); static std::string ExtractSummary(const char* message);
// The name of the source file where the test part took place, or // The name of the source file where the test part took place, or
// NULL if the source file is unknown. // "" if the source file is unknown.
internal::String file_name_; std::string file_name_;
// The line in the source file where the test part took place, or -1 // The line in the source file where the test part took place, or -1
// if the line number is unknown. // if the line number is unknown.
int line_number_; int line_number_;
internal::String summary_; // The test failure summary. std::string summary_; // The test failure summary.
internal::String message_; // The test failure message. std::string message_; // The test failure message.
}; };
// Prints a TestPartResult object. // Prints a TestPartResult object.

View File

@ -52,6 +52,7 @@
#define GTEST_INCLUDE_GTEST_GTEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_H_
#include <limits> #include <limits>
#include <ostream>
#include <vector> #include <vector>
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
@ -69,14 +70,14 @@
// class ::string, which has the same interface as ::std::string, but // class ::string, which has the same interface as ::std::string, but
// has a different implementation. // has a different implementation.
// //
// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that // You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
// ::string is available AND is a distinct type to ::std::string, or // ::string is available AND is a distinct type to ::std::string, or
// define it to 0 to indicate otherwise. // define it to 0 to indicate otherwise.
// //
// If the user's ::std::string and ::string are the same class due to // If ::std::string and ::string are the same class on your platform
// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0. // due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0.
// //
// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined // If you do not define GTEST_HAS_GLOBAL_STRING, it is defined
// heuristically. // heuristically.
namespace testing { namespace testing {
@ -153,25 +154,15 @@ class ExecDeathTest;
class NoExecDeathTest; class NoExecDeathTest;
class FinalSuccessChecker; class FinalSuccessChecker;
class GTestFlagSaver; class GTestFlagSaver;
class StreamingListenerTest;
class TestResultAccessor; class TestResultAccessor;
class TestEventListenersAccessor; class TestEventListenersAccessor;
class TestEventRepeater; class TestEventRepeater;
class UnitTestRecordPropertyTestHelper;
class WindowsDeathTest; class WindowsDeathTest;
class UnitTestImpl* GetUnitTestImpl(); class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const String& message); const std::string& message);
// Converts a streamable value to a String. A NULL pointer is
// converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0".
// Declared in gtest-internal.h but defined here, so that it has access
// to the definition of the Message class, required by the ARM
// compiler.
template <typename T>
String StreamableToString(const T& streamable) {
return (Message() << streamable).GetString();
}
} // namespace internal } // namespace internal
@ -267,8 +258,31 @@ class GTEST_API_ AssertionResult {
// Copy constructor. // Copy constructor.
// Used in EXPECT_TRUE/FALSE(assertion_result). // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult& other); AssertionResult(const AssertionResult& other);
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
// Used in the EXPECT_TRUE/FALSE(bool_expression). // Used in the EXPECT_TRUE/FALSE(bool_expression).
explicit AssertionResult(bool success) : success_(success) {} //
// T must be contextually convertible to bool.
//
// The second parameter prevents this overload from being considered if
// the argument is implicitly convertible to AssertionResult. In that case
// we want AssertionResult's copy constructor to be used.
template <typename T>
explicit AssertionResult(
const T& success,
typename internal::EnableIf<
!internal::ImplicitlyConvertible<T, AssertionResult>::value>::type*
/*enabler*/ = NULL)
: success_(success) {}
GTEST_DISABLE_MSC_WARNINGS_POP_()
// Assignment operator.
AssertionResult& operator=(AssertionResult other) {
swap(other);
return *this;
}
// Returns true iff the assertion succeeded. // Returns true iff the assertion succeeded.
operator bool() const { return success_; } // NOLINT operator bool() const { return success_; } // NOLINT
@ -309,6 +323,9 @@ class GTEST_API_ AssertionResult {
message_->append(a_message.GetString().c_str()); message_->append(a_message.GetString().c_str());
} }
// Swap the contents of this AssertionResult with other.
void swap(AssertionResult& other);
// Stores result of the assertion predicate. // Stores result of the assertion predicate.
bool success_; bool success_;
// Stores the message describing the condition in case the expectation // Stores the message describing the condition in case the expectation
@ -316,8 +333,6 @@ class GTEST_API_ AssertionResult {
// Referenced via a pointer to avoid taking too much stack frame space // Referenced via a pointer to avoid taking too much stack frame space
// with test assertions. // with test assertions.
internal::scoped_ptr< ::std::string> message_; internal::scoped_ptr< ::std::string> message_;
GTEST_DISALLOW_ASSIGN_(AssertionResult);
}; };
// Makes a successful assertion result. // Makes a successful assertion result.
@ -344,8 +359,8 @@ GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
// //
// class FooTest : public testing::Test { // class FooTest : public testing::Test {
// protected: // protected:
// virtual void SetUp() { ... } // void SetUp() override { ... }
// virtual void TearDown() { ... } // void TearDown() override { ... }
// ... // ...
// }; // };
// //
@ -391,20 +406,21 @@ class GTEST_API_ Test {
// non-fatal) failure. // non-fatal) failure.
static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
// Logs a property for the current test. Only the last value for a given // Logs a property for the current test, test case, or for the entire
// key is remembered. // invocation of the test program when used outside of the context of a
// These are public static so they can be called from utility functions // test case. Only the last value for a given key is remembered. These
// that are not members of the test fixture. // are public static so they can be called from utility functions that are
// The arguments are const char* instead strings, as Google Test is used // not members of the test fixture. Calls to RecordProperty made during
// on platforms where string doesn't compile. // lifespan of the test (from the moment its constructor starts to the
// // moment its destructor finishes) will be output in XML as attributes of
// Note that a driving consideration for these RecordProperty methods // the <testcase> element. Properties recorded from fixture's
// was to produce xml output suited to the Greenspan charting utility, // SetUpTestCase or TearDownTestCase are logged as attributes of the
// which at present will only chart values that fit in a 32-bit int. It // corresponding <testsuite> element. Calls to RecordProperty made in the
// is the user's responsibility to restrict their values to 32-bit ints // global context (before or after invocation of RUN_ALL_TESTS and from
// if they intend them to be used with Greenspan. // SetUp/TearDown method of Environment objects registered with Google
static void RecordProperty(const char* key, const char* value); // Test) will be output as attributes of the <testsuites> element.
static void RecordProperty(const char* key, int value); static void RecordProperty(const std::string& key, const std::string& value);
static void RecordProperty(const std::string& key, int value);
protected: protected:
// Creates a Test object. // Creates a Test object.
@ -439,17 +455,17 @@ class GTEST_API_ Test {
// Uses a GTestFlagSaver to save and restore all Google Test flags. // Uses a GTestFlagSaver to save and restore all Google Test flags.
const internal::GTestFlagSaver* const gtest_flag_saver_; const internal::GTestFlagSaver* const gtest_flag_saver_;
// Often a user mis-spells SetUp() as Setup() and spends a long time // Often a user misspells SetUp() as Setup() and spends a long time
// wondering why it is never called by Google Test. The declaration of // wondering why it is never called by Google Test. The declaration of
// the following method is solely for catching such an error at // the following method is solely for catching such an error at
// compile time: // compile time:
// //
// - The return type is deliberately chosen to be not void, so it // - The return type is deliberately chosen to be not void, so it
// will be a conflict if a user declares void Setup() in his test // will be a conflict if void Setup() is declared in the user's
// fixture. // test fixture.
// //
// - This method is private, so it will be another compiler error // - This method is private, so it will be another compiler error
// if a user calls it from his test fixture. // if the method is called from the user's test fixture.
// //
// DO NOT OVERRIDE THIS FUNCTION. // DO NOT OVERRIDE THIS FUNCTION.
// //
@ -473,7 +489,7 @@ class TestProperty {
// C'tor. TestProperty does NOT have a default constructor. // C'tor. TestProperty does NOT have a default constructor.
// Always use this constructor (with parameters) to create a // Always use this constructor (with parameters) to create a
// TestProperty object. // TestProperty object.
TestProperty(const char* a_key, const char* a_value) : TestProperty(const std::string& a_key, const std::string& a_value) :
key_(a_key), value_(a_value) { key_(a_key), value_(a_value) {
} }
@ -488,15 +504,15 @@ class TestProperty {
} }
// Sets a new value, overriding the one supplied in the constructor. // Sets a new value, overriding the one supplied in the constructor.
void SetValue(const char* new_value) { void SetValue(const std::string& new_value) {
value_ = new_value; value_ = new_value;
} }
private: private:
// The key supplied by the user. // The key supplied by the user.
internal::String key_; std::string key_;
// The value supplied by the user. // The value supplied by the user.
internal::String value_; std::string value_;
}; };
// The result of a single Test. This includes a list of // The result of a single Test. This includes a list of
@ -547,6 +563,7 @@ class GTEST_API_ TestResult {
private: private:
friend class TestInfo; friend class TestInfo;
friend class TestCase;
friend class UnitTest; friend class UnitTest;
friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::DefaultGlobalTestPartResultReporter;
friend class internal::ExecDeathTest; friend class internal::ExecDeathTest;
@ -571,13 +588,16 @@ class GTEST_API_ TestResult {
// a non-fatal failure if invalid (e.g., if it conflicts with reserved // a non-fatal failure if invalid (e.g., if it conflicts with reserved
// key names). If a property is already recorded for the same key, the // key names). If a property is already recorded for the same key, the
// value will be updated, rather than storing multiple values for the same // value will be updated, rather than storing multiple values for the same
// key. // key. xml_element specifies the element for which the property is being
void RecordProperty(const TestProperty& test_property); // recorded and is used for validation.
void RecordProperty(const std::string& xml_element,
const TestProperty& test_property);
// Adds a failure if the key is a reserved attribute of Google Test // Adds a failure if the key is a reserved attribute of Google Test
// testcase tags. Returns true if the property is valid. // testcase tags. Returns true if the property is valid.
// TODO(russr): Validate attribute names are legal and human readable. // TODO(russr): Validate attribute names are legal and human readable.
static bool ValidateTestProperty(const TestProperty& test_property); static bool ValidateTestProperty(const std::string& xml_element,
const TestProperty& test_property);
// Adds a test part result to the list. // Adds a test part result to the list.
void AddTestPartResult(const TestPartResult& test_part_result); void AddTestPartResult(const TestPartResult& test_part_result);
@ -650,9 +670,9 @@ class GTEST_API_ TestInfo {
return NULL; return NULL;
} }
// Returns true if this test should run, that is if the test is not disabled // Returns true if this test should run, that is if the test is not
// (or it is disabled but the also_run_disabled_tests flag has been specified) // disabled (or it is disabled but the also_run_disabled_tests flag has
// and its full name matches the user-specified filter. // been specified) and its full name matches the user-specified filter.
// //
// Google Test allows the user to filter the tests by their full names. // Google Test allows the user to filter the tests by their full names.
// The full name of a test Bar in test case Foo is defined as // The full name of a test Bar in test case Foo is defined as
@ -668,22 +688,28 @@ class GTEST_API_ TestInfo {
// contains the character 'A' or starts with "Foo.". // contains the character 'A' or starts with "Foo.".
bool should_run() const { return should_run_; } bool should_run() const { return should_run_; }
// Returns true if the test was filtered out by --gtest_filter // Returns true iff this test will appear in the XML report.
bool filtered_out() const { return !matches_filter_; } bool is_reportable() const {
// For now, the XML report includes all tests matching the filter.
// In the future, we may trim tests that are excluded because of
// sharding.
return matches_filter_;
}
// Returns the result of the test. // Returns the result of the test.
const TestResult* result() const { return &result_; } const TestResult* result() const { return &result_; }
private: private:
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
friend class internal::DefaultDeathTestFactory; friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
friend class Test; friend class Test;
friend class TestCase; friend class TestCase;
friend class internal::UnitTestImpl; friend class internal::UnitTestImpl;
friend class internal::StreamingListenerTest;
friend TestInfo* internal::MakeAndRegisterTestInfo( friend TestInfo* internal::MakeAndRegisterTestInfo(
const char* test_case_name, const char* name, const char* test_case_name,
const char* name,
const char* type_param, const char* type_param,
const char* value_param, const char* value_param,
internal::TypeId fixture_class_id, internal::TypeId fixture_class_id,
@ -693,9 +719,10 @@ class GTEST_API_ TestInfo {
// Constructs a TestInfo object. The newly constructed instance assumes // Constructs a TestInfo object. The newly constructed instance assumes
// ownership of the factory object. // ownership of the factory object.
TestInfo(const char* test_case_name, const char* name, TestInfo(const std::string& test_case_name,
const char* a_type_param, const std::string& name,
const char* a_value_param, const char* a_type_param, // NULL if not a type-parameterized test
const char* a_value_param, // NULL if not a value-parameterized test
internal::TypeId fixture_class_id, internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory); internal::TestFactoryBase* factory);
@ -775,18 +802,21 @@ class GTEST_API_ TestCase {
// Returns true if any test in this test case should run. // Returns true if any test in this test case should run.
bool should_run() const { return should_run_; } bool should_run() const { return should_run_; }
// Returns true if this test case should be skipped in the report.
bool should_skip_report() const { return should_skip_report_; }
// Gets the number of successful tests in this test case. // Gets the number of successful tests in this test case.
int successful_test_count() const; int successful_test_count() const;
// Gets the number of failed tests in this test case. // Gets the number of failed tests in this test case.
int failed_test_count() const; int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const;
// Gets the number of disabled tests in this test case. // Gets the number of disabled tests in this test case.
int disabled_test_count() const; int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report.
int reportable_test_count() const;
// Get the number of tests in this test case that should run. // Get the number of tests in this test case that should run.
int test_to_run_count() const; int test_to_run_count() const;
@ -806,6 +836,10 @@ class GTEST_API_ TestCase {
// total_test_count() - 1. If i is not in that range, returns NULL. // total_test_count() - 1. If i is not in that range, returns NULL.
const TestInfo* GetTestInfo(int i) const; const TestInfo* GetTestInfo(int i) const;
// Returns the TestResult that holds test properties recorded during
// execution of SetUpTestCase and TearDownTestCase.
const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
private: private:
friend class Test; friend class Test;
friend class internal::UnitTestImpl; friend class internal::UnitTestImpl;
@ -824,7 +858,6 @@ class GTEST_API_ TestCase {
// Sets the should_run member. // Sets the should_run member.
void set_should_run(bool should) { should_run_ = should; } void set_should_run(bool should) { should_run_ = should; }
void set_should_skip_report(bool should) { should_skip_report_ = should; }
// Adds a TestInfo to this test case. Will delete the TestInfo upon // Adds a TestInfo to this test case. Will delete the TestInfo upon
// destruction of the TestCase object. // destruction of the TestCase object.
@ -859,11 +892,22 @@ class GTEST_API_ TestCase {
return test_info->should_run() && test_info->result()->Failed(); return test_info->should_run() && test_info->result()->Failed();
} }
// Returns true iff the test is disabled and will be reported in the XML
// report.
static bool TestReportableDisabled(const TestInfo* test_info) {
return test_info->is_reportable() && test_info->is_disabled_;
}
// Returns true iff test is disabled. // Returns true iff test is disabled.
static bool TestDisabled(const TestInfo* test_info) { static bool TestDisabled(const TestInfo* test_info) {
return test_info->is_disabled_; return test_info->is_disabled_;
} }
// Returns true iff this test will appear in the XML report.
static bool TestReportable(const TestInfo* test_info) {
return test_info->is_reportable();
}
// Returns true if the given test should run. // Returns true if the given test should run.
static bool ShouldRunTest(const TestInfo* test_info) { static bool ShouldRunTest(const TestInfo* test_info) {
return test_info->should_run(); return test_info->should_run();
@ -876,7 +920,7 @@ class GTEST_API_ TestCase {
void UnshuffleTests(); void UnshuffleTests();
// Name of the test case. // Name of the test case.
internal::String name_; std::string name_;
// Name of the parameter type, or NULL if this is not a typed or a // Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test. // type-parameterized test.
const internal::scoped_ptr<const ::std::string> type_param_; const internal::scoped_ptr<const ::std::string> type_param_;
@ -893,17 +937,18 @@ class GTEST_API_ TestCase {
Test::TearDownTestCaseFunc tear_down_tc_; Test::TearDownTestCaseFunc tear_down_tc_;
// True iff any test in this test case should run. // True iff any test in this test case should run.
bool should_run_; bool should_run_;
// True if this test case should not be reported
bool should_skip_report_;
// Elapsed time, in milliseconds. // Elapsed time, in milliseconds.
TimeInMillis elapsed_time_; TimeInMillis elapsed_time_;
// Holds test properties recorded during execution of SetUpTestCase and
// TearDownTestCase.
TestResult ad_hoc_test_result_;
// We disallow copying TestCases. // We disallow copying TestCases.
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
}; };
// An Environment object is capable of setting up and tearing down an // An Environment object is capable of setting up and tearing down an
// environment. The user should subclass this to define his own // environment. You should subclass this to define your own
// environment(s). // environment(s).
// //
// An Environment object does the set-up and tear-down in virtual // An Environment object does the set-up and tear-down in virtual
@ -1116,11 +1161,13 @@ class GTEST_API_ UnitTest {
// Returns the TestCase object for the test that's currently running, // Returns the TestCase object for the test that's currently running,
// or NULL if no test is running. // or NULL if no test is running.
const TestCase* current_test_case() const; const TestCase* current_test_case() const
GTEST_LOCK_EXCLUDED_(mutex_);
// Returns the TestInfo object for the test that's currently running, // Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running. // or NULL if no test is running.
const TestInfo* current_test_info() const; const TestInfo* current_test_info() const
GTEST_LOCK_EXCLUDED_(mutex_);
// Returns the random seed used at the start of the current test run. // Returns the random seed used at the start of the current test run.
int random_seed() const; int random_seed() const;
@ -1130,7 +1177,8 @@ class GTEST_API_ UnitTest {
// value-parameterized tests and instantiate and register them. // value-parameterized tests and instantiate and register them.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
internal::ParameterizedTestCaseRegistry& parameterized_test_registry(); internal::ParameterizedTestCaseRegistry& parameterized_test_registry()
GTEST_LOCK_EXCLUDED_(mutex_);
#endif // GTEST_HAS_PARAM_TEST #endif // GTEST_HAS_PARAM_TEST
// Gets the number of successful test cases. // Gets the number of successful test cases.
@ -1152,15 +1200,25 @@ class GTEST_API_ UnitTest {
// Gets the number of failed tests. // Gets the number of failed tests.
int failed_test_count() const; int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const;
// Gets the number of disabled tests. // Gets the number of disabled tests.
int disabled_test_count() const; int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report.
int reportable_test_count() const;
// Gets the number of all tests. // Gets the number of all tests.
int total_test_count() const; int total_test_count() const;
// Gets the number of tests that should run. // Gets the number of tests that should run.
int test_to_run_count() const; int test_to_run_count() const;
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const;
// Gets the elapsed time, in milliseconds. // Gets the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const; TimeInMillis elapsed_time() const;
@ -1175,6 +1233,10 @@ class GTEST_API_ UnitTest {
// total_test_case_count() - 1. If i is not in that range, returns NULL. // total_test_case_count() - 1. If i is not in that range, returns NULL.
const TestCase* GetTestCase(int i) const; const TestCase* GetTestCase(int i) const;
// Returns the TestResult containing information on test failures and
// properties logged outside of individual test cases.
const TestResult& ad_hoc_test_result() const;
// Returns the list of event listeners that can be used to track events // Returns the list of event listeners that can be used to track events
// inside Google Test. // inside Google Test.
TestEventListeners& listeners(); TestEventListeners& listeners();
@ -1198,12 +1260,16 @@ class GTEST_API_ UnitTest {
void AddTestPartResult(TestPartResult::Type result_type, void AddTestPartResult(TestPartResult::Type result_type,
const char* file_name, const char* file_name,
int line_number, int line_number,
const internal::String& message, const std::string& message,
const internal::String& os_stack_trace); const std::string& os_stack_trace)
GTEST_LOCK_EXCLUDED_(mutex_);
// Adds a TestProperty to the current TestResult object. If the result already // Adds a TestProperty to the current TestResult object when invoked from
// contains a property with the same key, the value will be updated. // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
void RecordPropertyForCurrentTest(const char* key, const char* value); // from SetUpTestCase or TearDownTestCase, or to the global property set
// when invoked elsewhere. If the result already contains a property with
// the same key, the value will be updated.
void RecordProperty(const std::string& key, const std::string& value);
// Gets the i-th test case among all the test cases. i can range from 0 to // Gets the i-th test case among all the test cases. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL. // total_test_case_count() - 1. If i is not in that range, returns NULL.
@ -1218,11 +1284,13 @@ class GTEST_API_ UnitTest {
friend class Test; friend class Test;
friend class internal::AssertHelper; friend class internal::AssertHelper;
friend class internal::ScopedTrace; friend class internal::ScopedTrace;
friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper;
friend Environment* AddGlobalTestEnvironment(Environment* env); friend Environment* AddGlobalTestEnvironment(Environment* env);
friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation( friend void internal::ReportFailureInUnknownLocation(
TestPartResult::Type result_type, TestPartResult::Type result_type,
const internal::String& message); const std::string& message);
// Creates an empty UnitTest. // Creates an empty UnitTest.
UnitTest(); UnitTest();
@ -1232,10 +1300,12 @@ class GTEST_API_ UnitTest {
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack. // Google Test trace stack.
void PushGTestTrace(const internal::TraceInfo& trace); void PushGTestTrace(const internal::TraceInfo& trace)
GTEST_LOCK_EXCLUDED_(mutex_);
// Pops a trace from the per-thread Google Test trace stack. // Pops a trace from the per-thread Google Test trace stack.
void PopGTestTrace(); void PopGTestTrace()
GTEST_LOCK_EXCLUDED_(mutex_);
// Protects mutable state in *impl_. This is mutable as some const // Protects mutable state in *impl_. This is mutable as some const
// methods need to lock it too. // methods need to lock it too.
@ -1290,24 +1360,115 @@ GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
namespace internal { namespace internal {
// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
// value of type ToPrint that is an operand of a comparison assertion
// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
// the comparison, and is used to help determine the best way to
// format the value. In particular, when the value is a C string
// (char pointer) and the other operand is an STL string object, we
// want to format the C string as a string, since we know it is
// compared by value with the string object. If the value is a char
// pointer but the other operand is not an STL string object, we don't
// know whether the pointer is supposed to point to a NUL-terminated
// string, and thus want to print it as a pointer to be safe.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
// The default case.
template <typename ToPrint, typename OtherOperand>
class FormatForComparison {
public:
static ::std::string Format(const ToPrint& value) {
return ::testing::PrintToString(value);
}
};
// Array.
template <typename ToPrint, size_t N, typename OtherOperand>
class FormatForComparison<ToPrint[N], OtherOperand> {
public:
static ::std::string Format(const ToPrint* value) {
return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
}
};
// By default, print C string as pointers to be safe, as we don't know
// whether they actually point to a NUL-terminated string.
#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
template <typename OtherOperand> \
class FormatForComparison<CharType*, OtherOperand> { \
public: \
static ::std::string Format(CharType* value) { \
return ::testing::PrintToString(static_cast<const void*>(value)); \
} \
}
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
// If a C string is compared with an STL string object, we know it's meant
// to point to a NUL-terminated string, and thus can print it as a string.
#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
template <> \
class FormatForComparison<CharType*, OtherStringType> { \
public: \
static ::std::string Format(CharType* value) { \
return ::testing::PrintToString(value); \
} \
}
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
#if GTEST_HAS_GLOBAL_STRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string);
#endif
#if GTEST_HAS_GLOBAL_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring);
#endif
#if GTEST_HAS_STD_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
#endif
#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
// operand to be used in a failure message. The type (but not value) // operand to be used in a failure message. The type (but not value)
// of the other operand may affect the format. This allows us to // of the other operand may affect the format. This allows us to
// print a char* as a raw pointer when it is compared against another // print a char* as a raw pointer when it is compared against another
// char*, and print it as a C string when it is compared against an // char* or void*, and print it as a C string when it is compared
// std::string object, for example. // against an std::string object, for example.
//
// The default implementation ignores the type of the other operand.
// Some specialized versions are used to handle formatting wide or
// narrow C strings.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename T1, typename T2> template <typename T1, typename T2>
String FormatForComparisonFailureMessage(const T1& value, std::string FormatForComparisonFailureMessage(
const T2& /* other_operand */) { const T1& value, const T2& /* other_operand */) {
// C++Builder compiles this incorrectly if the namespace isn't explicitly return FormatForComparison<T1, T2>::Format(value);
// given. }
return ::testing::PrintToString(value);
// Separate the error generating code from the code path to reduce the stack
// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
// when calling EXPECT_* in a tight loop.
template <typename T1, typename T2>
AssertionResult CmpHelperEQFailure(const char* expected_expression,
const char* actual_expression,
const T1& expected, const T2& actual) {
return EqFailure(expected_expression,
actual_expression,
FormatForComparisonFailureMessage(expected, actual),
FormatForComparisonFailureMessage(actual, expected),
false);
} }
// The helper function for {ASSERT|EXPECT}_EQ. // The helper function for {ASSERT|EXPECT}_EQ.
@ -1316,25 +1477,14 @@ AssertionResult CmpHelperEQ(const char* expected_expression,
const char* actual_expression, const char* actual_expression,
const T1& expected, const T1& expected,
const T2& actual) { const T2& actual) {
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */)
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4389) // Temporarily disables warning on
// signed/unsigned mismatch.
#endif
if (expected == actual) { if (expected == actual) {
return AssertionSuccess(); return AssertionSuccess();
} }
GTEST_DISABLE_MSC_WARNINGS_POP_()
#ifdef _MSC_VER return CmpHelperEQFailure(expected_expression, actual_expression, expected,
# pragma warning(pop) // Restores the warning state. actual);
#endif
return EqFailure(expected_expression,
actual_expression,
FormatForComparisonFailureMessage(expected, actual),
FormatForComparisonFailureMessage(actual, expected),
false);
} }
// With this overloaded version, we allow anonymous enums to be used // With this overloaded version, we allow anonymous enums to be used
@ -1422,6 +1572,19 @@ class EqHelper<true> {
} }
}; };
// Separate the error generating code from the code path to reduce the stack
// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
// when calling EXPECT_OP in a tight loop.
template <typename T1, typename T2>
AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
const T1& val1, const T2& val2,
const char* op) {
return AssertionFailure()
<< "Expected: (" << expr1 << ") " << op << " (" << expr2
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)
<< " vs " << FormatForComparisonFailureMessage(val2, val1);
}
// A macro for implementing the helper functions needed to implement // A macro for implementing the helper functions needed to implement
// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
// of similar code. // of similar code.
@ -1432,6 +1595,7 @@ class EqHelper<true> {
// with gcc 4. // with gcc 4.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
template <typename T1, typename T2>\ template <typename T1, typename T2>\
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
@ -1439,10 +1603,7 @@ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
if (val1 op val2) {\ if (val1 op val2) {\
return AssertionSuccess();\ return AssertionSuccess();\
} else {\ } else {\
return AssertionFailure() \ return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
<< "Expected: (" << expr1 << ") " #op " (" << expr2\
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
}\ }\
}\ }\
GTEST_API_ AssertionResult CmpHelper##op_name(\ GTEST_API_ AssertionResult CmpHelper##op_name(\
@ -1625,7 +1786,7 @@ class GTEST_API_ AssertHelper {
TestPartResult::Type const type; TestPartResult::Type const type;
const char* const file; const char* const file;
int const line; int const line;
String const message; std::string const message;
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
@ -1684,7 +1845,12 @@ class WithParamInterface {
// references static data, to reduce the opportunity for incorrect uses // references static data, to reduce the opportunity for incorrect uses
// like writing 'WithParamInterface<bool>::GetParam()' for a test that // like writing 'WithParamInterface<bool>::GetParam()' for a test that
// uses a fixture whose parameter type is int. // uses a fixture whose parameter type is int.
const ParamType& GetParam() const { return *parameter_; } const ParamType& GetParam() const {
GTEST_CHECK_(parameter_ != NULL)
<< "GetParam() can only be called inside a value-parameterized test "
<< "-- did you intend to write TEST_P instead of TEST_F?";
return *parameter_;
}
private: private:
// Sets parameter value. The caller is responsible for making sure the value // Sets parameter value. The caller is responsible for making sure the value
@ -1730,12 +1896,6 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// usually want the fail-fast behavior of FAIL and ASSERT_*, but those // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
// writing data-driven tests often find themselves using ADD_FAILURE // writing data-driven tests often find themselves using ADD_FAILURE
// and EXPECT_* more. // and EXPECT_* more.
//
// Examples:
//
// EXPECT_TRUE(server.StatusIsOK());
// ASSERT_FALSE(server.HasPendingRequest(port))
// << "There are still pending requests " << "on port " << port;
// Generates a nonfatal failure with a generic message. // Generates a nonfatal failure with a generic message.
#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
@ -1909,7 +2069,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
#endif #endif
// C String Comparisons. All tests treat NULL and any non-NULL string // C-string Comparisons. All tests treat NULL and any non-NULL string
// as different. Two NULLs are equal. // as different. Two NULLs are equal.
// //
// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
@ -2093,8 +2253,8 @@ bool StaticAssertTypeEq() {
// The convention is to end the test case name with "Test". For // The convention is to end the test case name with "Test". For
// example, a test case for the Foo class can be named FooTest. // example, a test case for the Foo class can be named FooTest.
// //
// The user should put his test code between braces after using this // Test code should appear between braces after an invocation of
// macro. Example: // this macro. Example:
// //
// TEST(FooTest, InitializesCorrectly) { // TEST(FooTest, InitializesCorrectly) {
// Foo foo; // Foo foo;
@ -2150,15 +2310,20 @@ bool StaticAssertTypeEq() {
GTEST_TEST_(test_fixture, test_name, test_fixture, \ GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>()) ::testing::internal::GetTypeId<test_fixture>())
// Use this macro in main() to run all tests. It returns 0 if all } // namespace testing
// Use this function in main() to run all tests. It returns 0 if all
// tests are successful, or 1 otherwise. // tests are successful, or 1 otherwise.
// //
// RUN_ALL_TESTS() should be invoked after the command line has been // RUN_ALL_TESTS() should be invoked after the command line has been
// parsed by InitGoogleTest(). // parsed by InitGoogleTest().
//
// This function was formerly a macro; thus, it is in the global
// namespace and has an all-caps name.
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
#define RUN_ALL_TESTS()\ inline int RUN_ALL_TESTS() {
(::testing::UnitTest::GetInstance()->Run()) return ::testing::UnitTest::GetInstance()->Run();
}
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_H_ #endif // GTEST_INCLUDE_GTEST_GTEST_H_

View File

@ -27,7 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file is AUTOMATICALLY GENERATED on 09/24/2010 by command // This file is AUTOMATICALLY GENERATED on 10/31/2011 by command
// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
// //
// Implements a family of generic predicate assertion macros. // Implements a family of generic predicate assertion macros.

View File

@ -127,11 +127,11 @@ class GTEST_API_ DeathTest {
// the last death test. // the last death test.
static const char* LastMessage(); static const char* LastMessage();
static void set_last_death_test_message(const String& message); static void set_last_death_test_message(const std::string& message);
private: private:
// A string containing a description of the outcome of the last death test. // A string containing a description of the outcome of the last death test.
static String last_death_test_message_; static std::string last_death_test_message_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
}; };
@ -217,12 +217,23 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
// The symbol "fail" here expands to something into which a message // The symbol "fail" here expands to something into which a message
// can be streamed. // can be streamed.
// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
// NDEBUG mode. In this case we need the statements to be executed, the regex is
// ignored, and the macro must accept a streamed message even though the message
// is never printed.
# define GTEST_EXECUTE_STATEMENT_(statement, regex) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} else \
::testing::Message()
// A class representing the parsed contents of the // A class representing the parsed contents of the
// --gtest_internal_run_death_test flag, as it existed when // --gtest_internal_run_death_test flag, as it existed when
// RUN_ALL_TESTS was called. // RUN_ALL_TESTS was called.
class InternalRunDeathTestFlag { class InternalRunDeathTestFlag {
public: public:
InternalRunDeathTestFlag(const String& a_file, InternalRunDeathTestFlag(const std::string& a_file,
int a_line, int a_line,
int an_index, int an_index,
int a_write_fd) int a_write_fd)
@ -234,13 +245,13 @@ class InternalRunDeathTestFlag {
posix::Close(write_fd_); posix::Close(write_fd_);
} }
String file() const { return file_; } const std::string& file() const { return file_; }
int line() const { return line_; } int line() const { return line_; }
int index() const { return index_; } int index() const { return index_; }
int write_fd() const { return write_fd_; } int write_fd() const { return write_fd_; }
private: private:
String file_; std::string file_;
int line_; int line_;
int index_; int index_;
int write_fd_; int write_fd_;

View File

@ -61,11 +61,7 @@ class GTEST_API_ FilePath {
FilePath() : pathname_("") { } FilePath() : pathname_("") { }
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
explicit FilePath(const char* pathname) : pathname_(pathname) { explicit FilePath(const std::string& pathname) : pathname_(pathname) {
Normalize();
}
explicit FilePath(const String& pathname) : pathname_(pathname) {
Normalize(); Normalize();
} }
@ -78,7 +74,7 @@ class GTEST_API_ FilePath {
pathname_ = rhs.pathname_; pathname_ = rhs.pathname_;
} }
String ToString() const { return pathname_; } const std::string& string() const { return pathname_; }
const char* c_str() const { return pathname_.c_str(); } const char* c_str() const { return pathname_.c_str(); }
// Returns the current working directory, or "" if unsuccessful. // Returns the current working directory, or "" if unsuccessful.
@ -111,8 +107,8 @@ class GTEST_API_ FilePath {
const FilePath& base_name, const FilePath& base_name,
const char* extension); const char* extension);
// Returns true iff the path is NULL or "". // Returns true iff the path is "".
bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; } bool IsEmpty() const { return pathname_.empty(); }
// If input name has a trailing separator character, removes it and returns // If input name has a trailing separator character, removes it and returns
// the name, otherwise return the name string unmodified. // the name, otherwise return the name string unmodified.
@ -201,7 +197,7 @@ class GTEST_API_ FilePath {
// separators. Returns NULL if no path separator was found. // separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const; const char* FindLastPathSeparator() const;
String pathname_; std::string pathname_;
}; // class FilePath }; // class FilePath
} // namespace internal } // namespace internal

View File

@ -44,18 +44,22 @@
# include <sys/types.h> # include <sys/types.h>
# include <sys/wait.h> # include <sys/wait.h>
# include <unistd.h> # include <unistd.h>
# include <signal.h>
#endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
#if GTEST_CAN_STREAM_RESULTS_
# include <sys/socket.h> #if GTEST_HAS_EXCEPTIONS
#endif // GTEST_CAN_STREAM_RESULTS_ # include <stdexcept>
#endif
#include <ctype.h> #include <ctype.h>
#include <float.h>
#include <string.h> #include <string.h>
#include <iomanip> #include <iomanip>
#include <limits> #include <limits>
#include <set> #include <set>
#include <string>
#include <vector>
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
#include "gtest/internal/gtest-type-util.h" #include "gtest/internal/gtest-type-util.h"
@ -71,36 +75,6 @@
#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
// Google Test defines the testing::Message class to allow construction of
// test messages via the << operator. The idea is that anything
// streamable to std::ostream can be streamed to a testing::Message.
// This allows a user to use his own types in Google Test assertions by
// overloading the << operator.
//
// util/gtl/stl_logging-inl.h overloads << for STL containers. These
// overloads cannot be defined in the std namespace, as that will be
// undefined behavior. Therefore, they are defined in the global
// namespace instead.
//
// C++'s symbol lookup rule (i.e. Koenig lookup) says that these
// overloads are visible in either the std namespace or the global
// namespace, but not other namespaces, including the testing
// namespace which Google Test's Message class is in.
//
// To allow STL containers (and other types that has a << operator
// defined in the global namespace) to be used in Google Test assertions,
// testing::Message must access the custom << operator from the global
// namespace. Hence this helper function.
//
// Note: Jeffrey Yasskin suggested an alternative fix by "using
// ::operator<<;" in the definition of Message's operator<<. That fix
// doesn't require a helper function, but unfortunately doesn't
// compile with MSVC.
template <typename T>
inline void GTestStreamToHelper(std::ostream* os, const T& val) {
*os << val;
}
class ProtocolMessage; class ProtocolMessage;
namespace proto2 { class Message; } namespace proto2 { class Message; }
@ -126,17 +100,12 @@ class TestInfoImpl; // Opaque implementation of TestInfo
class UnitTestImpl; // Opaque implementation of UnitTest class UnitTestImpl; // Opaque implementation of UnitTest
// How many times InitGoogleTest() has been called. // How many times InitGoogleTest() has been called.
extern int g_init_gtest_count; GTEST_API_ extern int g_init_gtest_count;
// The text used in failure messages to indicate the start of the // The text used in failure messages to indicate the start of the
// stack trace. // stack trace.
GTEST_API_ extern const char kStackTraceMarker[]; GTEST_API_ extern const char kStackTraceMarker[];
// A secret type that Google Test users don't know about. It has no
// definition on purpose. Therefore it's impossible to create a
// Secret object, which is what we want.
class Secret;
// Two overloaded helpers for checking at compile time whether an // Two overloaded helpers for checking at compile time whether an
// expression is a null pointer literal (i.e. NULL or any 0-valued // expression is a null pointer literal (i.e. NULL or any 0-valued
// compile-time integral constant). Their return values have // compile-time integral constant). Their return values have
@ -167,8 +136,23 @@ char (&IsNullLiteralHelper(...))[2]; // NOLINT
#endif // GTEST_ELLIPSIS_NEEDS_POD_ #endif // GTEST_ELLIPSIS_NEEDS_POD_
// Appends the user-supplied message to the Google-Test-generated message. // Appends the user-supplied message to the Google-Test-generated message.
GTEST_API_ String AppendUserMessage(const String& gtest_msg, GTEST_API_ std::string AppendUserMessage(
const Message& user_msg); const std::string& gtest_msg, const Message& user_msg);
#if GTEST_HAS_EXCEPTIONS
// This exception is thrown by (and only by) a failed Google Test
// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
// are enabled). We derive it from std::runtime_error, which is for
// errors presumably detectable only at run time. Since
// std::runtime_error inherits from std::exception, many testing
// frameworks know how to extract and print the message inside it.
class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
public:
explicit GoogleTestFailureException(const TestPartResult& failure);
};
#endif // GTEST_HAS_EXCEPTIONS
// A helper class for creating scoped traces in user programs. // A helper class for creating scoped traces in user programs.
class GTEST_API_ ScopedTrace { class GTEST_API_ ScopedTrace {
@ -189,76 +173,35 @@ class GTEST_API_ ScopedTrace {
// c'tor and d'tor. Therefore it doesn't // c'tor and d'tor. Therefore it doesn't
// need to be used otherwise. // need to be used otherwise.
// Converts a streamable value to a String. A NULL pointer is namespace edit_distance {
// converted to "(null)". When the input value is a ::string, // Returns the optimal edits to go from 'left' to 'right'.
// ::std::string, ::wstring, or ::std::wstring object, each NUL // All edits cost the same, with replace having lower priority than
// character in it is replaced with "\\0". // add/remove.
// Declared here but defined in gtest.h, so that it has access // Simple implementation of the WagnerFischer algorithm.
// to the definition of the Message class, required by the ARM // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
// compiler. enum EditType { kMatch, kAdd, kRemove, kReplace };
template <typename T> GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
String StreamableToString(const T& streamable); const std::vector<size_t>& left, const std::vector<size_t>& right);
// The Symbian compiler has a bug that prevents it from selecting the // Same as above, but the input is represented as strings.
// correct overload of FormatForComparisonFailureMessage (see below) GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
// unless we pass the first argument by reference. If we do that, const std::vector<std::string>& left,
// however, Visual Age C++ 10.1 generates a compiler error. Therefore const std::vector<std::string>& right);
// we only apply the work-around for Symbian.
#if defined(__SYMBIAN32__)
# define GTEST_CREF_WORKAROUND_ const&
#else
# define GTEST_CREF_WORKAROUND_
#endif
// When this operand is a const char* or char*, if the other operand // Create a diff of the input strings in Unified diff format.
// is a ::std::string or ::string, we print this operand as a C string GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
// rather than a pointer (we do the same for wide strings); otherwise const std::vector<std::string>& right,
// we print it as a pointer to be safe. size_t context = 2);
// This internal macro is used to avoid duplicated code. } // namespace edit_distance
#define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\
inline String FormatForComparisonFailureMessage(\
operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \
const operand2_type& /*operand2*/) {\
return operand1_printer(str);\
}\
inline String FormatForComparisonFailureMessage(\
const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \
const operand2_type& /*operand2*/) {\
return operand1_printer(str);\
}
GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted) // Calculate the diff between 'left' and 'right' and return it in unified diff
#if GTEST_HAS_STD_WSTRING // format.
GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted) // If not null, stores in 'total_line_count' the total number of lines found
#endif // GTEST_HAS_STD_WSTRING // in left + right.
GTEST_API_ std::string DiffStrings(const std::string& left,
#if GTEST_HAS_GLOBAL_STRING const std::string& right,
GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted) size_t* total_line_count);
#endif // GTEST_HAS_GLOBAL_STRING
#if GTEST_HAS_GLOBAL_WSTRING
GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted)
#endif // GTEST_HAS_GLOBAL_WSTRING
#undef GTEST_FORMAT_IMPL_
// The next four overloads handle the case where the operand being
// printed is a char/wchar_t pointer and the other operand is not a
// string/wstring object. In such cases, we just print the operand as
// a pointer to be safe.
#define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \
template <typename T> \
String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \
const T&) { \
return PrintToString(static_cast<const void*>(p)); \
}
GTEST_FORMAT_CHAR_PTR_IMPL_(char)
GTEST_FORMAT_CHAR_PTR_IMPL_(const char)
GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t)
GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t)
#undef GTEST_FORMAT_CHAR_PTR_IMPL_
// Constructs and returns the message for an equality assertion // Constructs and returns the message for an equality assertion
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
@ -277,12 +220,12 @@ GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t)
// be inserted into the message. // be inserted into the message.
GTEST_API_ AssertionResult EqFailure(const char* expected_expression, GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
const char* actual_expression, const char* actual_expression,
const String& expected_value, const std::string& expected_value,
const String& actual_value, const std::string& actual_value,
bool ignoring_case); bool ignoring_case);
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GTEST_API_ String GetBoolAssertionFailureMessage( GTEST_API_ std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result, const AssertionResult& assertion_result,
const char* expression_text, const char* expression_text,
const char* actual_predicate_value, const char* actual_predicate_value,
@ -357,7 +300,7 @@ class FloatingPoint {
// bits. Therefore, 4 should be enough for ordinary use. // bits. Therefore, 4 should be enough for ordinary use.
// //
// See the following article for more details on ULP: // See the following article for more details on ULP:
// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
static const size_t kMaxUlps = 4; static const size_t kMaxUlps = 4;
// Constructs a FloatingPoint from a raw floating-point number. // Constructs a FloatingPoint from a raw floating-point number.
@ -384,6 +327,9 @@ class FloatingPoint {
return ReinterpretBits(kExponentBitMask); return ReinterpretBits(kExponentBitMask);
} }
// Returns the maximum representable finite floating-point number.
static RawType Max();
// Non-static methods // Non-static methods
// Returns the bits that represents this number. // Returns the bits that represents this number.
@ -464,6 +410,13 @@ class FloatingPoint {
FloatingPointUnion u_; FloatingPointUnion u_;
}; };
// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
// macro defined by <windows.h>.
template <>
inline float FloatingPoint<float>::Max() { return FLT_MAX; }
template <>
inline double FloatingPoint<double>::Max() { return DBL_MAX; }
// Typedefs the instances of the FloatingPoint template class that we // Typedefs the instances of the FloatingPoint template class that we
// care to use. // care to use.
typedef FloatingPoint<float> Float; typedef FloatingPoint<float> Float;
@ -568,7 +521,8 @@ typedef void (*TearDownTestCaseFunc)();
// The newly created TestInfo instance will assume // The newly created TestInfo instance will assume
// ownership of the factory object. // ownership of the factory object.
GTEST_API_ TestInfo* MakeAndRegisterTestInfo( GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
const char* test_case_name, const char* name, const char* test_case_name,
const char* name,
const char* type_param, const char* type_param,
const char* value_param, const char* value_param,
TypeId fixture_class_id, TypeId fixture_class_id,
@ -628,9 +582,9 @@ inline const char* SkipComma(const char* str) {
// Returns the prefix of 'str' before the first comma in it; returns // Returns the prefix of 'str' before the first comma in it; returns
// the entire string if it contains no comma. // the entire string if it contains no comma.
inline String GetPrefixUntilComma(const char* str) { inline std::string GetPrefixUntilComma(const char* str) {
const char* comma = strchr(str, ','); const char* comma = strchr(str, ',');
return comma == NULL ? String(str) : String(str, comma - str); return comma == NULL ? str : std::string(str, comma);
} }
// TypeParameterizedTest<Fixture, TestSel, Types>::Register() // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
@ -656,9 +610,9 @@ class TypeParameterizedTest {
// First, registers the first type-parameterized test in the type // First, registers the first type-parameterized test in the type
// list. // list.
MakeAndRegisterTestInfo( MakeAndRegisterTestInfo(
String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/", (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/"
case_name, index).c_str(), + StreamableToString(index)).c_str(),
GetPrefixUntilComma(test_names).c_str(), StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
GetTypeName<Type>().c_str(), GetTypeName<Type>().c_str(),
NULL, // No value parameter. NULL, // No value parameter.
GetTypeId<FixtureClass>(), GetTypeId<FixtureClass>(),
@ -715,7 +669,7 @@ class TypeParameterizedTestCase<Fixture, Templates0, Types> {
#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
// Returns the current OS stack trace as a String. // Returns the current OS stack trace as an std::string.
// //
// The maximum number of stack frames to be included is specified by // The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter // the gtest_stack_trace_depth flag. The skip_count parameter
@ -725,8 +679,8 @@ class TypeParameterizedTestCase<Fixture, Templates0, Types> {
// For example, if Foo() calls Bar(), which in turn calls // For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
int skip_count); UnitTest* unit_test, int skip_count);
// Helpers for suppressing warnings on unreachable code or constant // Helpers for suppressing warnings on unreachable code or constant
// condition. // condition.
@ -801,13 +755,19 @@ struct RemoveConst<const T> { typedef T type; }; // NOLINT
// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above
// definition to fail to remove the const in 'const int[3]' and 'const // definition to fail to remove the const in 'const int[3]' and 'const
// char[3][4]'. The following specialization works around the bug. // char[3][4]'. The following specialization works around the bug.
// However, it causes trouble with GCC and thus needs to be
// conditionally compiled.
#if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
template <typename T, size_t N> template <typename T, size_t N>
struct RemoveConst<const T[N]> { struct RemoveConst<const T[N]> {
typedef typename RemoveConst<T>::type type[N]; typedef typename RemoveConst<T>::type type[N];
}; };
#if defined(_MSC_VER) && _MSC_VER < 1400
// This is the only specialization that allows VC++ 7.1 to remove const in
// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC
// and thus needs to be conditionally compiled.
template <typename T, size_t N>
struct RemoveConst<T[N]> {
typedef typename RemoveConst<T>::type type[N];
};
#endif #endif
// A handy wrapper around RemoveConst that works when the argument // A handy wrapper around RemoveConst that works when the argument
@ -856,7 +816,7 @@ class ImplicitlyConvertible {
// MakeFrom() is an expression whose type is From. We cannot simply // MakeFrom() is an expression whose type is From. We cannot simply
// use From(), as the type From may not have a public default // use From(), as the type From may not have a public default
// constructor. // constructor.
static From MakeFrom(); static typename AddReference<From>::type MakeFrom();
// These two functions are overloaded. Given an expression // These two functions are overloaded. Given an expression
// Helper(x), the compiler will pick the first version if x can be // Helper(x), the compiler will pick the first version if x can be
@ -874,25 +834,20 @@ class ImplicitlyConvertible {
// We have to put the 'public' section after the 'private' section, // We have to put the 'public' section after the 'private' section,
// or MSVC refuses to compile the code. // or MSVC refuses to compile the code.
public: public:
// MSVC warns about implicitly converting from double to int for #if defined(__BORLANDC__)
// possible loss of data, so we need to temporarily disable the
// warning.
#ifdef _MSC_VER
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4244) // Temporarily disables warning 4244.
static const bool value =
sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
# pragma warning(pop) // Restores the warning state.
#elif defined(__BORLANDC__)
// C++Builder cannot use member overload resolution during template // C++Builder cannot use member overload resolution during template
// instantiation. The simplest workaround is to use its C++0x type traits // instantiation. The simplest workaround is to use its C++0x type traits
// functions (C++Builder 2009 and above only). // functions (C++Builder 2009 and above only).
static const bool value = __is_convertible(From, To); static const bool value = __is_convertible(From, To);
#else #else
// MSVC warns about implicitly converting from double to int for
// possible loss of data, so we need to temporarily disable the
// warning.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244)
static const bool value = static const bool value =
sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
#endif // _MSV_VER GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif // __BORLANDC__
}; };
template <typename From, typename To> template <typename From, typename To>
const bool ImplicitlyConvertible<From, To>::value; const bool ImplicitlyConvertible<From, To>::value;
@ -1018,11 +973,10 @@ void CopyArray(const T* from, size_t size, U* to) {
// The relation between an NativeArray object (see below) and the // The relation between an NativeArray object (see below) and the
// native array it represents. // native array it represents.
enum RelationToSource { // We use 2 different structs to allow non-copyable types to be used, as long
kReference, // The NativeArray references the native array. // as RelationToSourceReference() is passed.
kCopy // The NativeArray makes a copy of the native array and struct RelationToSourceReference {};
// owns the copy. struct RelationToSourceCopy {};
};
// Adapts a native array to a read-only STL-style container. Instead // Adapts a native array to a read-only STL-style container. Instead
// of the complete STL container concept, this adaptor only implements // of the complete STL container concept, this adaptor only implements
@ -1040,22 +994,23 @@ class NativeArray {
typedef Element* iterator; typedef Element* iterator;
typedef const Element* const_iterator; typedef const Element* const_iterator;
// Constructs from a native array. // Constructs from a native array. References the source.
NativeArray(const Element* array, size_t count, RelationToSource relation) { NativeArray(const Element* array, size_t count, RelationToSourceReference) {
Init(array, count, relation); InitRef(array, count);
}
// Constructs from a native array. Copies the source.
NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
InitCopy(array, count);
} }
// Copy constructor. // Copy constructor.
NativeArray(const NativeArray& rhs) { NativeArray(const NativeArray& rhs) {
Init(rhs.array_, rhs.size_, rhs.relation_to_source_); (this->*rhs.clone_)(rhs.array_, rhs.size_);
} }
~NativeArray() { ~NativeArray() {
// Ensures that the user doesn't instantiate NativeArray with a if (clone_ != &NativeArray::InitRef)
// const or reference type.
static_cast<void>(StaticAssertTypeEqHelper<Element,
GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>());
if (relation_to_source_ == kCopy)
delete[] array_; delete[] array_;
} }
@ -1069,23 +1024,30 @@ class NativeArray {
} }
private: private:
// Initializes this object; makes a copy of the input array if enum {
// 'relation' is kCopy. kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper<
void Init(const Element* array, size_t a_size, RelationToSource relation) { Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value,
if (relation == kReference) { };
array_ = array;
} else { // Initializes this object with a copy of the input.
void InitCopy(const Element* array, size_t a_size) {
Element* const copy = new Element[a_size]; Element* const copy = new Element[a_size];
CopyArray(array, a_size, copy); CopyArray(array, a_size, copy);
array_ = copy; array_ = copy;
}
size_ = a_size; size_ = a_size;
relation_to_source_ = relation; clone_ = &NativeArray::InitCopy;
}
// Initializes this object with a reference of the input.
void InitRef(const Element* array, size_t a_size) {
array_ = array;
size_ = a_size;
clone_ = &NativeArray::InitRef;
} }
const Element* array_; const Element* array_;
size_t size_; size_t size_;
RelationToSource relation_to_source_; void (NativeArray::*clone_)(const Element*, size_t);
GTEST_DISALLOW_ASSIGN_(NativeArray); GTEST_DISALLOW_ASSIGN_(NativeArray);
}; };
@ -1228,3 +1190,4 @@ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_

View File

@ -105,25 +105,35 @@ class linked_ptr_internal {
// framework. // framework.
// Join an existing circle. // Join an existing circle.
// L < g_linked_ptr_mutex void join(linked_ptr_internal const* ptr)
void join(linked_ptr_internal const* ptr) { GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) {
MutexLock lock(&g_linked_ptr_mutex); MutexLock lock(&g_linked_ptr_mutex);
linked_ptr_internal const* p = ptr; linked_ptr_internal const* p = ptr;
while (p->next_ != ptr) p = p->next_; while (p->next_ != ptr) {
assert(p->next_ != this &&
"Trying to join() a linked ring we are already in. "
"Is GMock thread safety enabled?");
p = p->next_;
}
p->next_ = this; p->next_ = this;
next_ = ptr; next_ = ptr;
} }
// Leave whatever circle we're part of. Returns true if we were the // Leave whatever circle we're part of. Returns true if we were the
// last member of the circle. Once this is done, you can join() another. // last member of the circle. Once this is done, you can join() another.
// L < g_linked_ptr_mutex bool depart()
bool depart() { GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) {
MutexLock lock(&g_linked_ptr_mutex); MutexLock lock(&g_linked_ptr_mutex);
if (next_ == this) return true; if (next_ == this) return true;
linked_ptr_internal const* p = next_; linked_ptr_internal const* p = next_;
while (p->next_ != this) p = p->next_; while (p->next_ != this) {
assert(p->next_ != next_ &&
"Trying to depart() a linked ring we are not in. "
"Is GMock thread safety enabled?");
p = p->next_;
}
p->next_ = next_; p->next_ = next_;
return false; return false;
} }

View File

@ -39,7 +39,7 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support.
// and at most $maxtuple arguments in Combine. Please contact // and at most $maxtuple arguments in Combine. Please contact
// googletestframework@googlegroups.com if you need more. // googletestframework@googlegroups.com if you need more.
// Please note that the number of arguments to Combine is limited // Please note that the number of arguments to Combine is limited
// by the maximum arity of the implementation of tr1::tuple which is // by the maximum arity of the implementation of tuple which is
// currently set at $maxtuple. // currently set at $maxtuple.
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
@ -98,7 +98,7 @@ class ValueArray$i {
template <typename T> template <typename T>
operator ParamGenerator<T>() const { operator ParamGenerator<T>() const {
const T array[] = {$for j, [[v$(j)_]]}; const T array[] = {$for j, [[static_cast<T>(v$(j)_)]]};
return ValuesIn(array); return ValuesIn(array);
} }
@ -128,9 +128,9 @@ $range k 2..i
template <$for j, [[typename T$j]]> template <$for j, [[typename T$j]]>
class CartesianProductGenerator$i class CartesianProductGenerator$i
: public ParamGeneratorInterface< ::std::tr1::tuple<$for j, [[T$j]]> > { : public ParamGeneratorInterface< ::testing::tuple<$for j, [[T$j]]> > {
public: public:
typedef ::std::tr1::tuple<$for j, [[T$j]]> ParamType; typedef ::testing::tuple<$for j, [[T$j]]> ParamType;
CartesianProductGenerator$i($for j, [[const ParamGenerator<T$j>& g$j]]) CartesianProductGenerator$i($for j, [[const ParamGenerator<T$j>& g$j]])
: $for j, [[g$(j)_(g$j)]] {} : $for j, [[g$(j)_(g$j)]] {}
@ -269,8 +269,8 @@ class CartesianProductHolder$i {
CartesianProductHolder$i($for j, [[const Generator$j& g$j]]) CartesianProductHolder$i($for j, [[const Generator$j& g$j]])
: $for j, [[g$(j)_(g$j)]] {} : $for j, [[g$(j)_(g$j)]] {}
template <$for j, [[typename T$j]]> template <$for j, [[typename T$j]]>
operator ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >() const { operator ParamGenerator< ::testing::tuple<$for j, [[T$j]]> >() const {
return ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >( return ParamGenerator< ::testing::tuple<$for j, [[T$j]]> >(
new CartesianProductGenerator$i<$for j, [[T$j]]>( new CartesianProductGenerator$i<$for j, [[T$j]]>(
$for j,[[ $for j,[[

View File

@ -494,10 +494,10 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
const string& instantiation_name = gen_it->first; const string& instantiation_name = gen_it->first;
ParamGenerator<ParamType> generator((*gen_it->second)()); ParamGenerator<ParamType> generator((*gen_it->second)());
Message test_case_name_stream; string test_case_name;
if ( !instantiation_name.empty() ) if ( !instantiation_name.empty() )
test_case_name_stream << instantiation_name << "/"; test_case_name = instantiation_name + "/";
test_case_name_stream << test_info->test_case_base_name; test_case_name += test_info->test_case_base_name;
int i = 0; int i = 0;
for (typename ParamGenerator<ParamType>::iterator param_it = for (typename ParamGenerator<ParamType>::iterator param_it =
@ -506,7 +506,7 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
Message test_name_stream; Message test_name_stream;
test_name_stream << test_info->test_base_name << "/" << i; test_name_stream << test_info->test_base_name << "/" << i;
MakeAndRegisterTestInfo( MakeAndRegisterTestInfo(
test_case_name_stream.GetString().c_str(), test_case_name.c_str(),
test_name_stream.GetString().c_str(), test_name_stream.GetString().c_str(),
NULL, // No type parameter. NULL, // No type parameter.
PrintToString(*param_it).c_str(), PrintToString(*param_it).c_str(),

File diff suppressed because it is too large Load Diff

View File

@ -47,50 +47,18 @@
#endif #endif
#include <string.h> #include <string.h>
#include "gtest/internal/gtest-port.h"
#include <string> #include <string>
#include "gtest/internal/gtest-port.h"
namespace testing { namespace testing {
namespace internal { namespace internal {
// String - a UTF-8 string class. // String - an abstract class holding static string utilities.
//
// For historic reasons, we don't use std::string.
//
// TODO(wan@google.com): replace this class with std::string or
// implement it in terms of the latter.
//
// Note that String can represent both NULL and the empty string,
// while std::string cannot represent NULL.
//
// NULL and the empty string are considered different. NULL is less
// than anything (including the empty string) except itself.
//
// This class only provides minimum functionality necessary for
// implementing Google Test. We do not intend to implement a full-fledged
// string class here.
//
// Since the purpose of this class is to provide a substitute for
// std::string on platforms where it cannot be used, we define a copy
// constructor and assignment operators such that we don't need
// conditional compilation in a lot of places.
//
// In order to make the representation efficient, the d'tor of String
// is not virtual. Therefore DO NOT INHERIT FROM String.
class GTEST_API_ String { class GTEST_API_ String {
public: public:
// Static utility methods // Static utility methods
// Returns the input enclosed in double quotes if it's not NULL;
// otherwise returns "(null)". For example, "\"Hello\"" is returned
// for input "Hello".
//
// This is useful for printing a C string in the syntax of a literal.
//
// Known issue: escape sequences are not handled yet.
static String ShowCStringQuoted(const char* c_str);
// Clones a 0-terminated C string, allocating memory using new. The // Clones a 0-terminated C string, allocating memory using new. The
// caller is responsible for deleting the return value using // caller is responsible for deleting the return value using
// delete[]. Returns the cloned string, or NULL if the input is // delete[]. Returns the cloned string, or NULL if the input is
@ -137,11 +105,7 @@ class GTEST_API_ String {
// NULL will be converted to "(null)". If an error occurred during // NULL will be converted to "(null)". If an error occurred during
// the conversion, "(failed to convert from wide string)" is // the conversion, "(failed to convert from wide string)" is
// returned. // returned.
static String ShowWideCString(const wchar_t* wide_c_str); static std::string ShowWideCString(const wchar_t* wide_c_str);
// Similar to ShowWideCString(), except that this function encloses
// the converted string in double quotes.
static String ShowWideCStringQuoted(const wchar_t* wide_c_str);
// Compares two wide C strings. Returns true iff they have the same // Compares two wide C strings. Returns true iff they have the same
// content. // content.
@ -175,174 +139,27 @@ class GTEST_API_ String {
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
const wchar_t* rhs); const wchar_t* rhs);
// Formats a list of arguments to a String, using the same format // Returns true iff the given string ends with the given suffix, ignoring
// spec string as for printf. // case. Any string is considered to end with an empty suffix.
// static bool EndsWithCaseInsensitive(
// We do not use the StringPrintf class as it is not universally const std::string& str, const std::string& suffix);
// available.
//
// The result is limited to 4096 characters (including the tailing
// 0). If 4096 characters are not enough to format the input,
// "<buffer exceeded>" is returned.
static String Format(const char* format, ...);
// C'tors // Formats an int value as "%02d".
static std::string FormatIntWidth2(int value); // "%02d" for width == 2
// The default c'tor constructs a NULL string. // Formats an int value as "%X".
String() : c_str_(NULL), length_(0) {} static std::string FormatHexInt(int value);
// Constructs a String by cloning a 0-terminated C string. // Formats a byte as "%02X".
String(const char* a_c_str) { // NOLINT static std::string FormatByte(unsigned char value);
if (a_c_str == NULL) {
c_str_ = NULL;
length_ = 0;
} else {
ConstructNonNull(a_c_str, strlen(a_c_str));
}
}
// Constructs a String by copying a given number of chars from a
// buffer. E.g. String("hello", 3) creates the string "hel",
// String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "",
// and String(NULL, 1) results in access violation.
String(const char* buffer, size_t a_length) {
ConstructNonNull(buffer, a_length);
}
// The copy c'tor creates a new copy of the string. The two
// String objects do not share content.
String(const String& str) : c_str_(NULL), length_(0) { *this = str; }
// D'tor. String is intended to be a final class, so the d'tor
// doesn't need to be virtual.
~String() { delete[] c_str_; }
// Allows a String to be implicitly converted to an ::std::string or
// ::string, and vice versa. Converting a String containing a NULL
// pointer to ::std::string or ::string is undefined behavior.
// Converting a ::std::string or ::string containing an embedded NUL
// character to a String will result in the prefix up to the first
// NUL character.
String(const ::std::string& str) {
ConstructNonNull(str.c_str(), str.length());
}
operator ::std::string() const { return ::std::string(c_str(), length()); }
#if GTEST_HAS_GLOBAL_STRING
String(const ::string& str) {
ConstructNonNull(str.c_str(), str.length());
}
operator ::string() const { return ::string(c_str(), length()); }
#endif // GTEST_HAS_GLOBAL_STRING
// Returns true iff this is an empty string (i.e. "").
bool empty() const { return (c_str() != NULL) && (length() == 0); }
// Compares this with another String.
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
// if this is greater than rhs.
int Compare(const String& rhs) const;
// Returns true iff this String equals the given C string. A NULL
// string and a non-NULL string are considered not equal.
bool operator==(const char* a_c_str) const { return Compare(a_c_str) == 0; }
// Returns true iff this String is less than the given String. A
// NULL string is considered less than "".
bool operator<(const String& rhs) const { return Compare(rhs) < 0; }
// Returns true iff this String doesn't equal the given C string. A NULL
// string and a non-NULL string are considered not equal.
bool operator!=(const char* a_c_str) const { return !(*this == a_c_str); }
// Returns true iff this String ends with the given suffix. *Any*
// String is considered to end with a NULL or empty suffix.
bool EndsWith(const char* suffix) const;
// Returns true iff this String ends with the given suffix, not considering
// case. Any String is considered to end with a NULL or empty suffix.
bool EndsWithCaseInsensitive(const char* suffix) const;
// Returns the length of the encapsulated string, or 0 if the
// string is NULL.
size_t length() const { return length_; }
// Gets the 0-terminated C string this String object represents.
// The String object still owns the string. Therefore the caller
// should NOT delete the return value.
const char* c_str() const { return c_str_; }
// Assigns a C string to this object. Self-assignment works.
const String& operator=(const char* a_c_str) {
return *this = String(a_c_str);
}
// Assigns a String object to this object. Self-assignment works.
const String& operator=(const String& rhs) {
if (this != &rhs) {
delete[] c_str_;
if (rhs.c_str() == NULL) {
c_str_ = NULL;
length_ = 0;
} else {
ConstructNonNull(rhs.c_str(), rhs.length());
}
}
return *this;
}
private: private:
// Constructs a non-NULL String from the given content. This String(); // Not meant to be instantiated.
// function can only be called when c_str_ has not been allocated.
// ConstructNonNull(NULL, 0) results in an empty string ("").
// ConstructNonNull(NULL, non_zero) is undefined behavior.
void ConstructNonNull(const char* buffer, size_t a_length) {
char* const str = new char[a_length + 1];
memcpy(str, buffer, a_length);
str[a_length] = '\0';
c_str_ = str;
length_ = a_length;
}
const char* c_str_;
size_t length_;
}; // class String }; // class String
// Streams a String to an ostream. Each '\0' character in the String // Gets the content of the stringstream's buffer as an std::string. Each '\0'
// is replaced with "\\0".
inline ::std::ostream& operator<<(::std::ostream& os, const String& str) {
if (str.c_str() == NULL) {
os << "(null)";
} else {
const char* const c_str = str.c_str();
for (size_t i = 0; i != str.length(); i++) {
if (c_str[i] == '\0') {
os << "\\0";
} else {
os << c_str[i];
}
}
}
return os;
}
// Gets the content of the stringstream's buffer as a String. Each '\0'
// character in the buffer is replaced with "\\0". // character in the buffer is replaced with "\\0".
GTEST_API_ String StringStreamToString(::std::stringstream* stream); GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
// Converts a streamable value to a String. A NULL pointer is
// converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0".
// Declared here but defined in gtest.h, so that it has access
// to the definition of the Message class, required by the ARM
// compiler.
template <typename T>
String StreamableToString(const T& streamable);
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing

View File

@ -1,4 +1,6 @@
// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! // This file was GENERATED by command:
// pump.py gtest-tuple.h.pump
// DO NOT EDIT BY HAND!!!
// Copyright 2009 Google Inc. // Copyright 2009 Google Inc.
// All Rights Reserved. // All Rights Reserved.
@ -51,6 +53,14 @@
private: private:
#endif #endif
// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict
// with our own definitions. Therefore using our own tuple does not work on
// those compilers.
#if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */
# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \
GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers."
#endif
// GTEST_n_TUPLE_(T) is the type of an n-tuple. // GTEST_n_TUPLE_(T) is the type of an n-tuple.
#define GTEST_0_TUPLE_(T) tuple<> #define GTEST_0_TUPLE_(T) tuple<>
#define GTEST_1_TUPLE_(T) tuple<T##0, void, void, void, void, void, void, \ #define GTEST_1_TUPLE_(T) tuple<T##0, void, void, void, void, void, void, \
@ -140,34 +150,54 @@ template <bool kIndexValid, int kIndex, class Tuple>
struct TupleElement; struct TupleElement;
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 0, GTEST_10_TUPLE_(T)> { typedef T0 type; }; struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > {
typedef T0 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 1, GTEST_10_TUPLE_(T)> { typedef T1 type; }; struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > {
typedef T1 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 2, GTEST_10_TUPLE_(T)> { typedef T2 type; }; struct TupleElement<true, 2, GTEST_10_TUPLE_(T) > {
typedef T2 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 3, GTEST_10_TUPLE_(T)> { typedef T3 type; }; struct TupleElement<true, 3, GTEST_10_TUPLE_(T) > {
typedef T3 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 4, GTEST_10_TUPLE_(T)> { typedef T4 type; }; struct TupleElement<true, 4, GTEST_10_TUPLE_(T) > {
typedef T4 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 5, GTEST_10_TUPLE_(T)> { typedef T5 type; }; struct TupleElement<true, 5, GTEST_10_TUPLE_(T) > {
typedef T5 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 6, GTEST_10_TUPLE_(T)> { typedef T6 type; }; struct TupleElement<true, 6, GTEST_10_TUPLE_(T) > {
typedef T6 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 7, GTEST_10_TUPLE_(T)> { typedef T7 type; }; struct TupleElement<true, 7, GTEST_10_TUPLE_(T) > {
typedef T7 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 8, GTEST_10_TUPLE_(T)> { typedef T8 type; }; struct TupleElement<true, 8, GTEST_10_TUPLE_(T) > {
typedef T8 type;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct TupleElement<true, 9, GTEST_10_TUPLE_(T)> { typedef T9 type; }; struct TupleElement<true, 9, GTEST_10_TUPLE_(T) > {
typedef T9 type;
};
} // namespace gtest_internal } // namespace gtest_internal
@ -708,37 +738,59 @@ inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
template <typename Tuple> struct tuple_size; template <typename Tuple> struct tuple_size;
template <GTEST_0_TYPENAMES_(T)> template <GTEST_0_TYPENAMES_(T)>
struct tuple_size<GTEST_0_TUPLE_(T)> { static const int value = 0; }; struct tuple_size<GTEST_0_TUPLE_(T) > {
static const int value = 0;
};
template <GTEST_1_TYPENAMES_(T)> template <GTEST_1_TYPENAMES_(T)>
struct tuple_size<GTEST_1_TUPLE_(T)> { static const int value = 1; }; struct tuple_size<GTEST_1_TUPLE_(T) > {
static const int value = 1;
};
template <GTEST_2_TYPENAMES_(T)> template <GTEST_2_TYPENAMES_(T)>
struct tuple_size<GTEST_2_TUPLE_(T)> { static const int value = 2; }; struct tuple_size<GTEST_2_TUPLE_(T) > {
static const int value = 2;
};
template <GTEST_3_TYPENAMES_(T)> template <GTEST_3_TYPENAMES_(T)>
struct tuple_size<GTEST_3_TUPLE_(T)> { static const int value = 3; }; struct tuple_size<GTEST_3_TUPLE_(T) > {
static const int value = 3;
};
template <GTEST_4_TYPENAMES_(T)> template <GTEST_4_TYPENAMES_(T)>
struct tuple_size<GTEST_4_TUPLE_(T)> { static const int value = 4; }; struct tuple_size<GTEST_4_TUPLE_(T) > {
static const int value = 4;
};
template <GTEST_5_TYPENAMES_(T)> template <GTEST_5_TYPENAMES_(T)>
struct tuple_size<GTEST_5_TUPLE_(T)> { static const int value = 5; }; struct tuple_size<GTEST_5_TUPLE_(T) > {
static const int value = 5;
};
template <GTEST_6_TYPENAMES_(T)> template <GTEST_6_TYPENAMES_(T)>
struct tuple_size<GTEST_6_TUPLE_(T)> { static const int value = 6; }; struct tuple_size<GTEST_6_TUPLE_(T) > {
static const int value = 6;
};
template <GTEST_7_TYPENAMES_(T)> template <GTEST_7_TYPENAMES_(T)>
struct tuple_size<GTEST_7_TUPLE_(T)> { static const int value = 7; }; struct tuple_size<GTEST_7_TUPLE_(T) > {
static const int value = 7;
};
template <GTEST_8_TYPENAMES_(T)> template <GTEST_8_TYPENAMES_(T)>
struct tuple_size<GTEST_8_TUPLE_(T)> { static const int value = 8; }; struct tuple_size<GTEST_8_TUPLE_(T) > {
static const int value = 8;
};
template <GTEST_9_TYPENAMES_(T)> template <GTEST_9_TYPENAMES_(T)>
struct tuple_size<GTEST_9_TUPLE_(T)> { static const int value = 9; }; struct tuple_size<GTEST_9_TUPLE_(T) > {
static const int value = 9;
};
template <GTEST_10_TYPENAMES_(T)> template <GTEST_10_TYPENAMES_(T)>
struct tuple_size<GTEST_10_TUPLE_(T)> { static const int value = 10; }; struct tuple_size<GTEST_10_TUPLE_(T) > {
static const int value = 10;
};
template <int k, class Tuple> template <int k, class Tuple>
struct tuple_element { struct tuple_element {

View File

@ -52,6 +52,14 @@ $$ This meta comment fixes auto-indentation in Emacs. }}
private: private:
#endif #endif
// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict
// with our own definitions. Therefore using our own tuple does not work on
// those compilers.
#if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */
# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \
GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers."
#endif
$range i 0..n-1 $range i 0..n-1
$range j 0..n $range j 0..n
@ -118,8 +126,9 @@ struct TupleElement;
$for i [[ $for i [[
template <GTEST_$(n)_TYPENAMES_(T)> template <GTEST_$(n)_TYPENAMES_(T)>
struct TupleElement<true, $i, GTEST_$(n)_TUPLE_(T)> [[]] struct TupleElement<true, $i, GTEST_$(n)_TUPLE_(T) > {
{ typedef T$i type; }; typedef T$i type;
};
]] ]]
@ -220,7 +229,9 @@ template <typename Tuple> struct tuple_size;
$for j [[ $for j [[
template <GTEST_$(j)_TYPENAMES_(T)> template <GTEST_$(j)_TYPENAMES_(T)>
struct tuple_size<GTEST_$(j)_TUPLE_(T)> { static const int value = $j; }; struct tuple_size<GTEST_$(j)_TUPLE_(T) > {
static const int value = $j;
};
]] ]]

View File

@ -45,15 +45,14 @@
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-string.h"
// #ifdef __GNUC__ is too general here. It is possible to use gcc without using // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
// libstdc++ (which is where cxxabi.h comes from). // libstdc++ (which is where cxxabi.h comes from).
# ifdef __GLIBCXX__ # if GTEST_HAS_CXXABI_H_
# include <cxxabi.h> # include <cxxabi.h>
# elif defined(__HP_aCC) # elif defined(__HP_aCC)
# include <acxx_demangle.h> # include <acxx_demangle.h>
# endif // __GLIBCXX__ # endif // GTEST_HASH_CXXABI_H_
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -62,24 +61,24 @@ namespace internal {
// NB: This function is also used in Google Mock, so don't move it inside of // NB: This function is also used in Google Mock, so don't move it inside of
// the typed-test-only section below. // the typed-test-only section below.
template <typename T> template <typename T>
String GetTypeName() { std::string GetTypeName() {
# if GTEST_HAS_RTTI # if GTEST_HAS_RTTI
const char* const name = typeid(T).name(); const char* const name = typeid(T).name();
# if defined(__GLIBCXX__) || defined(__HP_aCC) # if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
int status = 0; int status = 0;
// gcc's implementation of typeid(T).name() mangles the type name, // gcc's implementation of typeid(T).name() mangles the type name,
// so we have to demangle it. // so we have to demangle it.
# ifdef __GLIBCXX__ # if GTEST_HAS_CXXABI_H_
using abi::__cxa_demangle; using abi::__cxa_demangle;
# endif // __GLIBCXX__ # endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, 0, 0, &status); char* const readable_name = __cxa_demangle(name, 0, 0, &status);
const String name_str(status == 0 ? readable_name : name); const std::string name_str(status == 0 ? readable_name : name);
free(readable_name); free(readable_name);
return name_str; return name_str;
# else # else
return name; return name;
# endif // __GLIBCXX__ || __HP_aCC # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
# else # else
@ -3300,7 +3299,9 @@ struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
// INSTANTIATE_TYPED_TEST_CASE_P(). // INSTANTIATE_TYPED_TEST_CASE_P().
template <typename T> template <typename T>
struct TypeList { typedef Types1<T> type; }; struct TypeList {
typedef Types1<T> type;
};
template <typename T1, typename T2, typename T3, typename T4, typename T5, template <typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7, typename T8, typename T9, typename T10, typename T6, typename T7, typename T8, typename T9, typename T10,

View File

@ -43,15 +43,14 @@ $var n = 50 $$ Maximum length of type lists we want to support.
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-string.h"
// #ifdef __GNUC__ is too general here. It is possible to use gcc without using // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
// libstdc++ (which is where cxxabi.h comes from). // libstdc++ (which is where cxxabi.h comes from).
# ifdef __GLIBCXX__ # if GTEST_HAS_CXXABI_H_
# include <cxxabi.h> # include <cxxabi.h>
# elif defined(__HP_aCC) # elif defined(__HP_aCC)
# include <acxx_demangle.h> # include <acxx_demangle.h>
# endif // __GLIBCXX__ # endif // GTEST_HASH_CXXABI_H_
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -60,24 +59,24 @@ namespace internal {
// NB: This function is also used in Google Mock, so don't move it inside of // NB: This function is also used in Google Mock, so don't move it inside of
// the typed-test-only section below. // the typed-test-only section below.
template <typename T> template <typename T>
String GetTypeName() { std::string GetTypeName() {
# if GTEST_HAS_RTTI # if GTEST_HAS_RTTI
const char* const name = typeid(T).name(); const char* const name = typeid(T).name();
# if defined(__GLIBCXX__) || defined(__HP_aCC) # if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
int status = 0; int status = 0;
// gcc's implementation of typeid(T).name() mangles the type name, // gcc's implementation of typeid(T).name() mangles the type name,
// so we have to demangle it. // so we have to demangle it.
# ifdef __GLIBCXX__ # if GTEST_HAS_CXXABI_H_
using abi::__cxa_demangle; using abi::__cxa_demangle;
# endif // __GLIBCXX__ # endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, 0, 0, &status); char* const readable_name = __cxa_demangle(name, 0, 0, &status);
const String name_str(status == 0 ? readable_name : name); const std::string name_str(status == 0 ? readable_name : name);
free(readable_name); free(readable_name);
return name_str; return name_str;
# else # else
return name; return name;
# endif // __GLIBCXX__ || __HP_aCC # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
# else # else
@ -279,7 +278,9 @@ struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> {
// INSTANTIATE_TYPED_TEST_CASE_P(). // INSTANTIATE_TYPED_TEST_CASE_P().
template <typename T> template <typename T>
struct TypeList { typedef Types1<T> type; }; struct TypeList {
typedef Types1<T> type;
};
$range i 1..n $range i 1..n

View File

@ -43,6 +43,11 @@
# include <errno.h> # include <errno.h>
# include <fcntl.h> # include <fcntl.h>
# include <limits.h> # include <limits.h>
# if GTEST_OS_LINUX
# include <signal.h>
# endif // GTEST_OS_LINUX
# include <stdarg.h> # include <stdarg.h>
# if GTEST_OS_WINDOWS # if GTEST_OS_WINDOWS
@ -52,6 +57,10 @@
# include <sys/wait.h> # include <sys/wait.h>
# endif // GTEST_OS_WINDOWS # endif // GTEST_OS_WINDOWS
# if GTEST_OS_QNX
# include <spawn.h>
# endif // GTEST_OS_QNX
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
@ -59,9 +68,9 @@
// Indicates that this translation unit is part of Google Test's // Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is // implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to // included, or there will be a compiler error. This trick exists to
// prevent a user from accidentally including gtest-internal-inl.h in // prevent the accidental inclusion of gtest-internal-inl.h in the
// his code. // user's code.
#define GTEST_IMPLEMENTATION_ 1 #define GTEST_IMPLEMENTATION_ 1
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_ #undef GTEST_IMPLEMENTATION_
@ -100,13 +109,42 @@ GTEST_DEFINE_string_(
"Indicates the file, line number, temporal index of " "Indicates the file, line number, temporal index of "
"the single death test to run, and a file descriptor to " "the single death test to run, and a file descriptor to "
"which a success code may be sent, all separated by " "which a success code may be sent, all separated by "
"colons. This flag is specified if and only if the current " "the '|' characters. This flag is specified if and only if the current "
"process is a sub-process launched for running a thread-safe " "process is a sub-process launched for running a thread-safe "
"death test. FOR INTERNAL USE ONLY."); "death test. FOR INTERNAL USE ONLY.");
} // namespace internal } // namespace internal
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
namespace internal {
// Valid only for fast death tests. Indicates the code is running in the
// child process of a fast style death test.
static bool g_in_fast_death_test_child = false;
// Returns a Boolean value indicating whether the caller is currently
// executing in the context of the death test child process. Tools such as
// Valgrind heap checkers may need this to modify their behavior in death
// tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it.
bool InDeathTestChild() {
# if GTEST_OS_WINDOWS
// On Windows, death tests are thread-safe regardless of the value of the
// death_test_style flag.
return !GTEST_FLAG(internal_run_death_test).empty();
# else
if (GTEST_FLAG(death_test_style) == "threadsafe")
return !GTEST_FLAG(internal_run_death_test).empty();
else
return g_in_fast_death_test_child;
#endif
}
} // namespace internal
// ExitedWithCode constructor. // ExitedWithCode constructor.
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
} }
@ -141,7 +179,7 @@ namespace internal {
// Generates a textual description of a given exit code, in the format // Generates a textual description of a given exit code, in the format
// specified by wait(2). // specified by wait(2).
static String ExitSummary(int exit_code) { static std::string ExitSummary(int exit_code) {
Message m; Message m;
# if GTEST_OS_WINDOWS # if GTEST_OS_WINDOWS
@ -176,7 +214,7 @@ bool ExitedUnsuccessfully(int exit_status) {
// one thread running, or cannot determine the number of threads, prior // one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the // to executing the given statement. It is the responsibility of the
// caller not to pass a thread_count of 1. // caller not to pass a thread_count of 1.
static String DeathTestThreadWarning(size_t thread_count) { static std::string DeathTestThreadWarning(size_t thread_count) {
Message msg; Message msg;
msg << "Death tests use fork(), which is unsafe particularly" msg << "Death tests use fork(), which is unsafe particularly"
<< " in a threaded context. For this test, " << GTEST_NAME_ << " "; << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
@ -210,7 +248,7 @@ enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
// message is propagated back to the parent process. Otherwise, the // message is propagated back to the parent process. Otherwise, the
// message is simply printed to stderr. In either case, the program // message is simply printed to stderr. In either case, the program
// then exits with status 1. // then exits with status 1.
void DeathTestAbort(const String& message) { void DeathTestAbort(const std::string& message) {
// On a POSIX system, this function may be called from a threadsafe-style // On a POSIX system, this function may be called from a threadsafe-style
// death test child process, which operates on a very small stack. Use // death test child process, which operates on a very small stack. Use
// the heap for any additional non-minuscule memory requirements. // the heap for any additional non-minuscule memory requirements.
@ -234,9 +272,10 @@ void DeathTestAbort(const String& message) {
# define GTEST_DEATH_TEST_CHECK_(expression) \ # define GTEST_DEATH_TEST_CHECK_(expression) \
do { \ do { \
if (!::testing::internal::IsTrue(expression)) { \ if (!::testing::internal::IsTrue(expression)) { \
DeathTestAbort(::testing::internal::String::Format( \ DeathTestAbort( \
"CHECK failed: File %s, line %d: %s", \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
__FILE__, __LINE__, #expression)); \ + ::testing::internal::StreamableToString(__LINE__) + ": " \
+ #expression); \
} \ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
@ -254,15 +293,16 @@ void DeathTestAbort(const String& message) {
gtest_retval = (expression); \ gtest_retval = (expression); \
} while (gtest_retval == -1 && errno == EINTR); \ } while (gtest_retval == -1 && errno == EINTR); \
if (gtest_retval == -1) { \ if (gtest_retval == -1) { \
DeathTestAbort(::testing::internal::String::Format( \ DeathTestAbort( \
"CHECK failed: File %s, line %d: %s != -1", \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
__FILE__, __LINE__, #expression)); \ + ::testing::internal::StreamableToString(__LINE__) + ": " \
+ #expression + " != -1"); \
} \ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
// Returns the message describing the last system error in errno. // Returns the message describing the last system error in errno.
String GetLastErrnoDescription() { std::string GetLastErrnoDescription() {
return String(errno == 0 ? "" : posix::StrError(errno)); return errno == 0 ? "" : posix::StrError(errno);
} }
// This is called from a death test parent process to read a failure // This is called from a death test parent process to read a failure
@ -312,11 +352,11 @@ const char* DeathTest::LastMessage() {
return last_death_test_message_.c_str(); return last_death_test_message_.c_str();
} }
void DeathTest::set_last_death_test_message(const String& message) { void DeathTest::set_last_death_test_message(const std::string& message) {
last_death_test_message_ = message; last_death_test_message_ = message;
} }
String DeathTest::last_death_test_message_; std::string DeathTest::last_death_test_message_;
// Provides cross platform implementation for some death functionality. // Provides cross platform implementation for some death functionality.
class DeathTestImpl : public DeathTest { class DeathTestImpl : public DeathTest {
@ -491,7 +531,7 @@ bool DeathTestImpl::Passed(bool status_ok) {
if (!spawned()) if (!spawned())
return false; return false;
const String error_message = GetCapturedStderr(); const std::string error_message = GetCapturedStderr();
bool success = false; bool success = false;
Message buffer; Message buffer;
@ -673,22 +713,19 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
FALSE, // The initial state is non-signalled. FALSE, // The initial state is non-signalled.
NULL)); // The even is unnamed. NULL)); // The even is unnamed.
GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
const String filter_flag = String::Format("--%s%s=%s.%s", const std::string filter_flag =
GTEST_FLAG_PREFIX_, kFilterFlag, std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
info->test_case_name(), info->test_case_name() + "." + info->name();
info->name()); const std::string internal_flag =
const String internal_flag = String::Format( std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
"--%s%s=%s|%d|%d|%u|%Iu|%Iu", "=" + file_ + "|" + StreamableToString(line_) + "|" +
GTEST_FLAG_PREFIX_, StreamableToString(death_test_index) + "|" +
kInternalRunDeathTestFlag, StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
file_, line_, // size_t has the same width as pointers on both 32-bit and 64-bit
death_test_index,
static_cast<unsigned int>(::GetCurrentProcessId()),
// size_t has the same with as pointers on both 32-bit and 64-bit
// Windows platforms. // Windows platforms.
// See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
reinterpret_cast<size_t>(write_handle), "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
reinterpret_cast<size_t>(event_handle_.Get())); "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
char executable_path[_MAX_PATH + 1]; // NOLINT char executable_path[_MAX_PATH + 1]; // NOLINT
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(
@ -696,10 +733,9 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
executable_path, executable_path,
_MAX_PATH)); _MAX_PATH));
String command_line = String::Format("%s %s \"%s\"", std::string command_line =
::GetCommandLineA(), std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
filter_flag.c_str(), internal_flag + "\"";
internal_flag.c_str());
DeathTest::set_last_death_test_message(""); DeathTest::set_last_death_test_message("");
@ -816,6 +852,7 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() {
// Event forwarding to the listeners of event listener API mush be shut // Event forwarding to the listeners of event listener API mush be shut
// down in death test subprocesses. // down in death test subprocesses.
GetUnitTestImpl()->listeners()->SuppressEventForwarding(); GetUnitTestImpl()->listeners()->SuppressEventForwarding();
g_in_fast_death_test_child = true;
return EXECUTE_TEST; return EXECUTE_TEST;
} else { } else {
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
@ -835,6 +872,11 @@ class ExecDeathTest : public ForkingDeathTest {
ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
virtual TestRole AssumeRole(); virtual TestRole AssumeRole();
private: private:
static ::std::vector<testing::internal::string>
GetArgvsForDeathTestChildProcess() {
::std::vector<testing::internal::string> args = GetInjectableArgvs();
return args;
}
// The name of the file in which the death test is located. // The name of the file in which the death test is located.
const char* const file_; const char* const file_;
// The line number on which the death test is located. // The line number on which the death test is located.
@ -869,6 +911,7 @@ class Arguments {
char* const* Argv() { char* const* Argv() {
return &args_[0]; return &args_[0];
} }
private: private:
std::vector<char*> args_; std::vector<char*> args_;
}; };
@ -894,6 +937,7 @@ extern "C" char** environ;
inline char** GetEnviron() { return environ; } inline char** GetEnviron() { return environ; }
# endif // GTEST_OS_MAC # endif // GTEST_OS_MAC
# if !GTEST_OS_QNX
// The main function for a threadsafe-style death test child process. // The main function for a threadsafe-style death test child process.
// This function is called in a clone()-ed process and thus must avoid // This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions. // any potentially unsafe operations like malloc or libc functions.
@ -908,9 +952,8 @@ static int ExecDeathTestChildMain(void* child_arg) {
UnitTest::GetInstance()->original_working_dir(); UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call. // We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) { if (chdir(original_dir) != 0) {
DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
original_dir, GetLastErrnoDescription());
GetLastErrnoDescription().c_str()));
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -920,12 +963,12 @@ static int ExecDeathTestChildMain(void* child_arg) {
// invoke the test program via a valid path that contains at least // invoke the test program via a valid path that contains at least
// one path separator. // one path separator.
execve(args->argv[0], args->argv, GetEnviron()); execve(args->argv[0], args->argv, GetEnviron());
DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s", DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
args->argv[0], original_dir + " failed: " +
original_dir, GetLastErrnoDescription());
GetLastErrnoDescription().c_str()));
return EXIT_FAILURE; return EXIT_FAILURE;
} }
# endif // !GTEST_OS_QNX
// Two utility routines that together determine the direction the stack // Two utility routines that together determine the direction the stack
// grows. // grows.
@ -936,24 +979,76 @@ static int ExecDeathTestChildMain(void* child_arg) {
// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
// StackLowerThanAddress into StackGrowsDown, which then doesn't give // StackLowerThanAddress into StackGrowsDown, which then doesn't give
// correct answer. // correct answer.
bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_; void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
bool StackLowerThanAddress(const void* ptr) { void StackLowerThanAddress(const void* ptr, bool* result) {
int dummy; int dummy;
return &dummy < ptr; *result = (&dummy < ptr);
} }
// Make sure AddressSanitizer does not tamper with the stack here.
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
bool StackGrowsDown() { bool StackGrowsDown() {
int dummy; int dummy;
return StackLowerThanAddress(&dummy); bool result;
StackLowerThanAddress(&dummy, &result);
return result;
} }
// A threadsafe implementation of fork(2) for threadsafe-style death tests // Spawns a child process with the same executable as the current process in
// that uses clone(2). It dies with an error message if anything goes // a thread-safe manner and instructs it to run the death test. The
// wrong. // implementation uses fork(2) + exec. On systems where clone(2) is
static pid_t ExecDeathTestFork(char* const* argv, int close_fd) { // available, it is used instead, being slightly more thread-safe. On QNX,
// fork supports only single-threaded environments, so this function uses
// spawn(2) there instead. The function dies with an error message if
// anything goes wrong.
static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
ExecDeathTestArgs args = { argv, close_fd }; ExecDeathTestArgs args = { argv, close_fd };
pid_t child_pid = -1; pid_t child_pid = -1;
# if GTEST_OS_QNX
// Obtains the current directory and sets it to be closed in the child
// process.
const int cwd_fd = open(".", O_RDONLY);
GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
// We need to execute the test program in the same environment where
// it was originally invoked. Therefore we change to the original
// working directory first.
const char* const original_dir =
UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
GetLastErrnoDescription());
return EXIT_FAILURE;
}
int fd_flags;
// Set close_fd to be closed after spawn.
GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0};
// spawn is a system call.
child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
// Restores the current working directory.
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
# else // GTEST_OS_QNX
# if GTEST_OS_LINUX
// When a SIGPROF signal is received while fork() or clone() are executing,
// the process may hang. To avoid this, we ignore SIGPROF here and re-enable
// it after the call to fork()/clone() is complete.
struct sigaction saved_sigprof_action;
struct sigaction ignore_sigprof_action;
memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
sigemptyset(&ignore_sigprof_action.sa_mask);
ignore_sigprof_action.sa_handler = SIG_IGN;
GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
# endif // GTEST_OS_LINUX
# if GTEST_HAS_CLONE # if GTEST_HAS_CLONE
const bool use_fork = GTEST_FLAG(death_test_use_fork); const bool use_fork = GTEST_FLAG(death_test_use_fork);
@ -964,8 +1059,19 @@ static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, -1, 0); MAP_ANON | MAP_PRIVATE, -1, 0);
GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
// Maximum stack alignment in bytes: For a downward-growing stack, this
// amount is subtracted from size of the stack space to get an address
// that is within the stack space and is aligned on all systems we care
// about. As far as I know there is no ABI with stack alignment greater
// than 64. We assume stack and stack_size already have alignment of
// kMaxStackAlignment.
const size_t kMaxStackAlignment = 64;
void* const stack_top = void* const stack_top =
static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0); static_cast<char*>(stack) +
(stack_grows_down ? stack_size - kMaxStackAlignment : 0);
GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
@ -979,6 +1085,11 @@ static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
ExecDeathTestChildMain(&args); ExecDeathTestChildMain(&args);
_exit(0); _exit(0);
} }
# endif // GTEST_OS_QNX
# if GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &saved_sigprof_action, NULL));
# endif // GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_(child_pid != -1); GTEST_DEATH_TEST_CHECK_(child_pid != -1);
return child_pid; return child_pid;
@ -1006,16 +1117,16 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
// it be closed when the child process does an exec: // it be closed when the child process does an exec:
GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
const String filter_flag = const std::string filter_flag =
String::Format("--%s%s=%s.%s", std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
GTEST_FLAG_PREFIX_, kFilterFlag, + info->test_case_name() + "." + info->name();
info->test_case_name(), info->name()); const std::string internal_flag =
const String internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
String::Format("--%s%s=%s|%d|%d|%d", + file_ + "|" + StreamableToString(line_) + "|"
GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, + StreamableToString(death_test_index) + "|"
file_, line_, death_test_index, pipe_fd[1]); + StreamableToString(pipe_fd[1]);
Arguments args; Arguments args;
args.AddArguments(GetArgvs()); args.AddArguments(GetArgvsForDeathTestChildProcess());
args.AddArgument(filter_flag.c_str()); args.AddArgument(filter_flag.c_str());
args.AddArgument(internal_flag.c_str()); args.AddArgument(internal_flag.c_str());
@ -1026,7 +1137,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
// is necessary. // is necessary.
FlushInfoLog(); FlushInfoLog();
const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]); const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
set_child_pid(child_pid); set_child_pid(child_pid);
set_read_fd(pipe_fd[0]); set_read_fd(pipe_fd[0]);
@ -1052,9 +1163,10 @@ bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
if (flag != NULL) { if (flag != NULL) {
if (death_test_index > flag->index()) { if (death_test_index > flag->index()) {
DeathTest::set_last_death_test_message(String::Format( DeathTest::set_last_death_test_message(
"Death test count (%d) somehow exceeded expected maximum (%d)", "Death test count (" + StreamableToString(death_test_index)
death_test_index, flag->index())); + ") somehow exceeded expected maximum ("
+ StreamableToString(flag->index()) + ")");
return false; return false;
} }
@ -1083,9 +1195,9 @@ bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
# endif // GTEST_OS_WINDOWS # endif // GTEST_OS_WINDOWS
else { // NOLINT - this is more readable than unbalanced brackets inside #if. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
DeathTest::set_last_death_test_message(String::Format( DeathTest::set_last_death_test_message(
"Unknown death test style \"%s\" encountered", "Unknown death test style \"" + GTEST_FLAG(death_test_style)
GTEST_FLAG(death_test_style).c_str())); + "\" encountered");
return false; return false;
} }
@ -1123,8 +1235,8 @@ int GetStatusFileDescriptor(unsigned int parent_process_id,
FALSE, // Non-inheritable. FALSE, // Non-inheritable.
parent_process_id)); parent_process_id));
if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
DeathTestAbort(String::Format("Unable to open parent process %u", DeathTestAbort("Unable to open parent process " +
parent_process_id)); StreamableToString(parent_process_id));
} }
// TODO(vladl@google.com): Replace the following check with a // TODO(vladl@google.com): Replace the following check with a
@ -1144,9 +1256,10 @@ int GetStatusFileDescriptor(unsigned int parent_process_id,
// DUPLICATE_SAME_ACCESS is used. // DUPLICATE_SAME_ACCESS is used.
FALSE, // Request non-inheritable handler. FALSE, // Request non-inheritable handler.
DUPLICATE_SAME_ACCESS)) { DUPLICATE_SAME_ACCESS)) {
DeathTestAbort(String::Format( DeathTestAbort("Unable to duplicate the pipe handle " +
"Unable to duplicate the pipe handle %Iu from the parent process %u", StreamableToString(write_handle_as_size_t) +
write_handle_as_size_t, parent_process_id)); " from the parent process " +
StreamableToString(parent_process_id));
} }
const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
@ -1157,17 +1270,18 @@ int GetStatusFileDescriptor(unsigned int parent_process_id,
0x0, 0x0,
FALSE, FALSE,
DUPLICATE_SAME_ACCESS)) { DUPLICATE_SAME_ACCESS)) {
DeathTestAbort(String::Format( DeathTestAbort("Unable to duplicate the event handle " +
"Unable to duplicate the event handle %Iu from the parent process %u", StreamableToString(event_handle_as_size_t) +
event_handle_as_size_t, parent_process_id)); " from the parent process " +
StreamableToString(parent_process_id));
} }
const int write_fd = const int write_fd =
::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
if (write_fd == -1) { if (write_fd == -1) {
DeathTestAbort(String::Format( DeathTestAbort("Unable to convert pipe handle " +
"Unable to convert pipe handle %Iu to a file descriptor", StreamableToString(write_handle_as_size_t) +
write_handle_as_size_t)); " to a file descriptor");
} }
// Signals the parent that the write end of the pipe has been acquired // Signals the parent that the write end of the pipe has been acquired
@ -1204,9 +1318,8 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
|| !ParseNaturalNumber(fields[3], &parent_process_id) || !ParseNaturalNumber(fields[3], &parent_process_id)
|| !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
|| !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
DeathTestAbort(String::Format( DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
"Bad --gtest_internal_run_death_test flag: %s", GTEST_FLAG(internal_run_death_test));
GTEST_FLAG(internal_run_death_test).c_str()));
} }
write_fd = GetStatusFileDescriptor(parent_process_id, write_fd = GetStatusFileDescriptor(parent_process_id,
write_handle_as_size_t, write_handle_as_size_t,
@ -1217,9 +1330,8 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
|| !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[1], &line)
|| !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[2], &index)
|| !ParseNaturalNumber(fields[3], &write_fd)) { || !ParseNaturalNumber(fields[3], &write_fd)) {
DeathTestAbort(String::Format( DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
"Bad --gtest_internal_run_death_test flag: %s", + GTEST_FLAG(internal_run_death_test));
GTEST_FLAG(internal_run_death_test).c_str()));
} }
# endif // GTEST_OS_WINDOWS # endif // GTEST_OS_WINDOWS

View File

@ -29,6 +29,7 @@
// //
// Authors: keith.ray@gmail.com (Keith Ray) // Authors: keith.ray@gmail.com (Keith Ray)
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
@ -39,8 +40,8 @@
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> # include <direct.h>
# include <io.h> # include <io.h>
#elif GTEST_OS_SYMBIAN || GTEST_OS_NACL #elif GTEST_OS_SYMBIAN
// Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h // Symbian OpenC has PATH_MAX in sys/syslimits.h
# include <sys/syslimits.h> # include <sys/syslimits.h>
#else #else
# include <limits.h> # include <limits.h>
@ -69,7 +70,6 @@ namespace internal {
// of them. // of them.
const char kPathSeparator = '\\'; const char kPathSeparator = '\\';
const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparator = '/';
const char kPathSeparatorString[] = "\\";
const char kAlternatePathSeparatorString[] = "/"; const char kAlternatePathSeparatorString[] = "/";
# if GTEST_OS_WINDOWS_MOBILE # if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have a current directory. You should not use // Windows CE doesn't have a current directory. You should not use
@ -83,7 +83,6 @@ const char kCurrentDirectoryString[] = ".\\";
# endif // GTEST_OS_WINDOWS_MOBILE # endif // GTEST_OS_WINDOWS_MOBILE
#else #else
const char kPathSeparator = '/'; const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
const char kCurrentDirectoryString[] = "./"; const char kCurrentDirectoryString[] = "./";
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
@ -98,7 +97,7 @@ static bool IsPathSeparator(char c) {
// Returns the current working directory, or "" if unsuccessful. // Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() { FilePath FilePath::GetCurrentDir() {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
// Windows CE doesn't have a current directory, so we just return // Windows CE doesn't have a current directory, so we just return
// something reasonable. // something reasonable.
return FilePath(kCurrentDirectoryString); return FilePath(kCurrentDirectoryString);
@ -107,7 +106,14 @@ FilePath FilePath::GetCurrentDir() {
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#else #else
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); char* result = getcwd(cwd, sizeof(cwd));
# if GTEST_OS_NACL
// getcwd will likely fail in NaCl due to the sandbox, so return something
// reasonable. The user may have provided a shim implementation for getcwd,
// however, so fallback only when failure is detected.
return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
# endif // GTEST_OS_NACL
return FilePath(result == NULL ? "" : cwd);
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
} }
@ -116,9 +122,10 @@ FilePath FilePath::GetCurrentDir() {
// FilePath("dir/file"). If a case-insensitive extension is not // FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath. // found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const { FilePath FilePath::RemoveExtension(const char* extension) const {
String dot_extension(String::Format(".%s", extension)); const std::string dot_extension = std::string(".") + extension;
if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) { if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
return FilePath(String(pathname_.c_str(), pathname_.length() - 4)); return FilePath(pathname_.substr(
0, pathname_.length() - dot_extension.length()));
} }
return *this; return *this;
} }
@ -147,7 +154,7 @@ const char* FilePath::FindLastPathSeparator() const {
// On Windows platform, '\' is the path separator, otherwise it is '/'. // On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const { FilePath FilePath::RemoveDirectoryName() const {
const char* const last_sep = FindLastPathSeparator(); const char* const last_sep = FindLastPathSeparator();
return last_sep ? FilePath(String(last_sep + 1)) : *this; return last_sep ? FilePath(last_sep + 1) : *this;
} }
// RemoveFileName returns the directory path with the filename removed. // RemoveFileName returns the directory path with the filename removed.
@ -158,9 +165,9 @@ FilePath FilePath::RemoveDirectoryName() const {
// On Windows platform, '\' is the path separator, otherwise it is '/'. // On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const { FilePath FilePath::RemoveFileName() const {
const char* const last_sep = FindLastPathSeparator(); const char* const last_sep = FindLastPathSeparator();
String dir; std::string dir;
if (last_sep) { if (last_sep) {
dir = String(c_str(), last_sep + 1 - c_str()); dir = std::string(c_str(), last_sep + 1 - c_str());
} else { } else {
dir = kCurrentDirectoryString; dir = kCurrentDirectoryString;
} }
@ -177,11 +184,12 @@ FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name, const FilePath& base_name,
int number, int number,
const char* extension) { const char* extension) {
String file; std::string file;
if (number == 0) { if (number == 0) {
file = String::Format("%s.%s", base_name.c_str(), extension); file = base_name.string() + "." + extension;
} else { } else {
file = String::Format("%s_%d.%s", base_name.c_str(), number, extension); file = base_name.string() + "_" + StreamableToString(number)
+ "." + extension;
} }
return ConcatPaths(directory, FilePath(file)); return ConcatPaths(directory, FilePath(file));
} }
@ -193,8 +201,7 @@ FilePath FilePath::ConcatPaths(const FilePath& directory,
if (directory.IsEmpty()) if (directory.IsEmpty())
return relative_path; return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator()); const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator, return FilePath(dir.string() + kPathSeparator + relative_path.string());
relative_path.c_str()));
} }
// Returns true if pathname describes something findable in the file-system, // Returns true if pathname describes something findable in the file-system,
@ -338,7 +345,7 @@ bool FilePath::CreateFolder() const {
// On Windows platform, uses \ as the separator, other platforms use /. // On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const { FilePath FilePath::RemoveTrailingPathSeparator() const {
return IsDirectory() return IsDirectory()
? FilePath(String(pathname_.c_str(), pathname_.length() - 1)) ? FilePath(pathname_.substr(0, pathname_.length() - 1))
: *this; : *this;
} }

View File

@ -40,7 +40,7 @@
// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
// part of Google Test's implementation; otherwise it's undefined. // part of Google Test's implementation; otherwise it's undefined.
#if !GTEST_IMPLEMENTATION_ #if !GTEST_IMPLEMENTATION_
// A user is trying to include this from his code - just say no. // If this file is included from the user's code, just say no.
# error "gtest-internal-inl.h is part of Google Test's internal implementation." # error "gtest-internal-inl.h is part of Google Test's internal implementation."
# error "It must not be included except by Google Test itself." # error "It must not be included except by Google Test itself."
#endif // GTEST_IMPLEMENTATION_ #endif // GTEST_IMPLEMENTATION_
@ -58,6 +58,11 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT
#endif
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> // NOLINT # include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
@ -112,6 +117,12 @@ GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
// Formats the given time in milliseconds as seconds. // Formats the given time in milliseconds as seconds.
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
// Converts the given time in milliseconds to a date string in the ISO 8601
// format, without the timezone information. N.B.: due to the use the
// non-reentrant localtime() function, this function is not thread safe. Do
// not use it in any code that can be called from multiple threads.
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
// Parses a string for an Int32 flag, in the form of "--flag=value". // Parses a string for an Int32 flag, in the form of "--flag=value".
// //
// On success, stores the value of the flag in *value, and returns // On success, stores the value of the flag in *value, and returns
@ -190,37 +201,35 @@ class GTestFlagSaver {
GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(stream_result_to) = stream_result_to_;
GTEST_FLAG(throw_on_failure) = throw_on_failure_; GTEST_FLAG(throw_on_failure) = throw_on_failure_;
} }
private: private:
// Fields for saving the original values of flags. // Fields for saving the original values of flags.
bool also_run_disabled_tests_; bool also_run_disabled_tests_;
bool break_on_failure_; bool break_on_failure_;
bool catch_exceptions_; bool catch_exceptions_;
String color_; std::string color_;
String death_test_style_; std::string death_test_style_;
bool death_test_use_fork_; bool death_test_use_fork_;
String filter_; std::string filter_;
String internal_run_death_test_; std::string internal_run_death_test_;
bool list_tests_; bool list_tests_;
String output_; std::string output_;
bool print_time_; bool print_time_;
bool pretty_;
internal::Int32 random_seed_; internal::Int32 random_seed_;
internal::Int32 repeat_; internal::Int32 repeat_;
bool shuffle_; bool shuffle_;
internal::Int32 stack_trace_depth_; internal::Int32 stack_trace_depth_;
String stream_result_to_; std::string stream_result_to_;
bool throw_on_failure_; bool throw_on_failure_;
} GTEST_ATTRIBUTE_UNUSED_; } GTEST_ATTRIBUTE_UNUSED_;
// Converts a Unicode code point to a narrow string in UTF-8 encoding. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be // code_point parameter is of type UInt32 because wchar_t may not be
// wide enough to contain a code point. // wide enough to contain a code point.
// The output buffer str must containt at least 32 characters.
// The function returns the address of the output buffer.
// If the code_point is not a valid Unicode code point // If the code_point is not a valid Unicode code point
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
// as '(Invalid Unicode 0xXXXXXXXX)'. // to "(Invalid Unicode 0xXXXXXXXX)".
GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
// Converts a wide string to a narrow string in UTF-8 encoding. // Converts a wide string to a narrow string in UTF-8 encoding.
// The wide string is assumed to have the following encoding: // The wide string is assumed to have the following encoding:
@ -235,7 +244,7 @@ GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
// and contains invalid UTF-16 surrogate pairs, values in those pairs // and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane. // will be encoded as individual Unicode characters from Basic Normal Plane.
GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this // if the variable is present. If a file already exists at this location, this
@ -339,16 +348,15 @@ class TestPropertyKeyIs {
// Constructor. // Constructor.
// //
// TestPropertyKeyIs has NO default constructor. // TestPropertyKeyIs has NO default constructor.
explicit TestPropertyKeyIs(const char* key) explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
: key_(key) {}
// Returns true iff the test name of test property matches on key_. // Returns true iff the test name of test property matches on key_.
bool operator()(const TestProperty& test_property) const { bool operator()(const TestProperty& test_property) const {
return String(test_property.key()).Compare(key_) == 0; return test_property.key() == key_;
} }
private: private:
String key_; std::string key_;
}; };
// Class UnitTestOptions. // Class UnitTestOptions.
@ -366,12 +374,12 @@ class GTEST_API_ UnitTestOptions {
// Functions for processing the gtest_output flag. // Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output. // Returns the output format, or "" for normal printed output.
static String GetOutputFormat(); static std::string GetOutputFormat();
// Returns the absolute path of the requested output file, or the // Returns the absolute path of the requested output file, or the
// default (test_detail.xml in the original working directory) if // default (test_detail.xml in the original working directory) if
// none was explicitly specified. // none was explicitly specified.
static String GetAbsolutePathToOutputFile(); static std::string GetAbsolutePathToOutputFile();
// Functions for processing the gtest_filter flag. // Functions for processing the gtest_filter flag.
@ -384,8 +392,8 @@ class GTEST_API_ UnitTestOptions {
// Returns true iff the user-specified filter matches the test case // Returns true iff the user-specified filter matches the test case
// name and the test name. // name and the test name.
static bool FilterMatchesTest(const String &test_case_name, static bool FilterMatchesTest(const std::string &test_case_name,
const String &test_name); const std::string &test_name);
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag. // Function for supporting the gtest_catch_exception flag.
@ -398,7 +406,7 @@ class GTEST_API_ UnitTestOptions {
// Returns true if "name" matches the ':' separated list of glob-style // Returns true if "name" matches the ':' separated list of glob-style
// filters in "filter". // filters in "filter".
static bool MatchesFilter(const String& name, const char* filter); static bool MatchesFilter(const std::string& name, const char* filter);
}; };
// Returns the current application's name, removing directory path if that // Returns the current application's name, removing directory path if that
@ -411,13 +419,13 @@ class OsStackTraceGetterInterface {
OsStackTraceGetterInterface() {} OsStackTraceGetterInterface() {}
virtual ~OsStackTraceGetterInterface() {} virtual ~OsStackTraceGetterInterface() {}
// Returns the current OS stack trace as a String. Parameters: // Returns the current OS stack trace as an std::string. Parameters:
// //
// max_depth - the maximum number of stack frames to be included // max_depth - the maximum number of stack frames to be included
// in the trace. // in the trace.
// skip_count - the number of top frames to be skipped; doesn't count // skip_count - the number of top frames to be skipped; doesn't count
// against max_depth. // against max_depth.
virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
// UponLeavingGTest() should be called immediately before Google Test calls // UponLeavingGTest() should be called immediately before Google Test calls
// user code. It saves some information about the current stack that // user code. It saves some information about the current stack that
@ -432,8 +440,11 @@ class OsStackTraceGetterInterface {
class OsStackTraceGetter : public OsStackTraceGetterInterface { class OsStackTraceGetter : public OsStackTraceGetterInterface {
public: public:
OsStackTraceGetter() : caller_frame_(NULL) {} OsStackTraceGetter() : caller_frame_(NULL) {}
virtual String CurrentStackTrace(int max_depth, int skip_count);
virtual void UponLeavingGTest(); virtual string CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_);
virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
// This string is inserted in place of stack frames that are part of // This string is inserted in place of stack frames that are part of
// Google Test's implementation. // Google Test's implementation.
@ -455,7 +466,7 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface {
struct TraceInfo { struct TraceInfo {
const char* file; const char* file;
int line; int line;
String message; std::string message;
}; };
// This is the default global test part result reporter used in UnitTestImpl. // This is the default global test part result reporter used in UnitTestImpl.
@ -539,15 +550,25 @@ class GTEST_API_ UnitTestImpl {
// Gets the number of failed tests. // Gets the number of failed tests.
int failed_test_count() const; int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const;
// Gets the number of disabled tests. // Gets the number of disabled tests.
int disabled_test_count() const; int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report.
int reportable_test_count() const;
// Gets the number of all tests. // Gets the number of all tests.
int total_test_count() const; int total_test_count() const;
// Gets the number of tests that should run. // Gets the number of tests that should run.
int test_to_run_count() const; int test_to_run_count() const;
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const { return start_timestamp_; }
// Gets the elapsed time, in milliseconds. // Gets the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; } TimeInMillis elapsed_time() const { return elapsed_time_; }
@ -596,7 +617,7 @@ class GTEST_API_ UnitTestImpl {
// getter, and returns it. // getter, and returns it.
OsStackTraceGetterInterface* os_stack_trace_getter(); OsStackTraceGetterInterface* os_stack_trace_getter();
// Returns the current OS stack trace as a String. // Returns the current OS stack trace as an std::string.
// //
// The maximum number of stack frames to be included is specified by // The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter // the gtest_stack_trace_depth flag. The skip_count parameter
@ -606,7 +627,7 @@ class GTEST_API_ UnitTestImpl {
// For example, if Foo() calls Bar(), which in turn calls // For example, if Foo() calls Bar(), which in turn calls
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
// trace but Bar() and CurrentOsStackTraceExceptTop() won't. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
String CurrentOsStackTraceExceptTop(int skip_count); std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
// Finds and returns a TestCase with the given name. If one doesn't // Finds and returns a TestCase with the given name. If one doesn't
// exist, creates one and returns it. // exist, creates one and returns it.
@ -696,6 +717,12 @@ class GTEST_API_ UnitTestImpl {
ad_hoc_test_result_.Clear(); ad_hoc_test_result_.Clear();
} }
// Adds a TestProperty to the current TestResult object when invoked in a
// context of a test or a test case, or to the global property set. If the
// result already contains a property with the same key, the value will be
// updated.
void RecordProperty(const TestProperty& test_property);
enum ReactionToSharding { enum ReactionToSharding {
HONOR_SHARDING_PROTOCOL, HONOR_SHARDING_PROTOCOL,
IGNORE_SHARDING_PROTOCOL IGNORE_SHARDING_PROTOCOL
@ -880,6 +907,10 @@ class GTEST_API_ UnitTestImpl {
// Our random number generator. // Our random number generator.
internal::Random random_; internal::Random random_;
// The time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp_;
// How long the test took to run, in milliseconds. // How long the test took to run, in milliseconds.
TimeInMillis elapsed_time_; TimeInMillis elapsed_time_;
@ -935,33 +966,7 @@ GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
// Returns the message describing the last system error, regardless of the // Returns the message describing the last system error, regardless of the
// platform. // platform.
GTEST_API_ String GetLastErrnoDescription(); GTEST_API_ std::string GetLastErrnoDescription();
# if GTEST_OS_WINDOWS
// Provides leak-safe Windows kernel handle ownership.
class AutoHandle {
public:
AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
explicit AutoHandle(HANDLE handle) : handle_(handle) {}
~AutoHandle() { Reset(); }
HANDLE Get() const { return handle_; }
void Reset() { Reset(INVALID_HANDLE_VALUE); }
void Reset(HANDLE handle) {
if (handle != handle_) {
if (handle_ != INVALID_HANDLE_VALUE)
::CloseHandle(handle_);
handle_ = handle;
}
}
private:
HANDLE handle_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
};
# endif // GTEST_OS_WINDOWS
// Attempts to parse a string into a positive integer pointed to by the // Attempts to parse a string into a positive integer pointed to by the
// number parameter. Returns true if that is possible. // number parameter. Returns true if that is possible.
@ -1018,8 +1023,9 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
class TestResultAccessor { class TestResultAccessor {
public: public:
static void RecordProperty(TestResult* test_result, static void RecordProperty(TestResult* test_result,
const std::string& xml_element,
const TestProperty& property) { const TestProperty& property) {
test_result->RecordProperty(property); test_result->RecordProperty(xml_element, property);
} }
static void ClearTestPartResults(TestResult* test_result) { static void ClearTestPartResults(TestResult* test_result) {
@ -1032,6 +1038,154 @@ class TestResultAccessor {
} }
}; };
#if GTEST_CAN_STREAM_RESULTS_
// Streams test results to the given port on the given host machine.
class StreamingListener : public EmptyTestEventListener {
public:
// Abstract base class for writing strings to a socket.
class AbstractSocketWriter {
public:
virtual ~AbstractSocketWriter() {}
// Sends a string to the socket.
virtual void Send(const string& message) = 0;
// Closes the socket.
virtual void CloseConnection() {}
// Sends a string and a newline to the socket.
void SendLn(const string& message) {
Send(message + "\n");
}
};
// Concrete class for actually writing strings to a socket.
class SocketWriter : public AbstractSocketWriter {
public:
SocketWriter(const string& host, const string& port)
: sockfd_(-1), host_name_(host), port_num_(port) {
MakeConnection();
}
virtual ~SocketWriter() {
if (sockfd_ != -1)
CloseConnection();
}
// Sends a string to the socket.
virtual void Send(const string& message) {
GTEST_CHECK_(sockfd_ != -1)
<< "Send() can be called only when there is a connection.";
const int len = static_cast<int>(message.length());
if (write(sockfd_, message.c_str(), len) != len) {
GTEST_LOG_(WARNING)
<< "stream_result_to: failed to stream to "
<< host_name_ << ":" << port_num_;
}
}
private:
// Creates a client socket and connects to the server.
void MakeConnection();
// Closes the socket.
void CloseConnection() {
GTEST_CHECK_(sockfd_ != -1)
<< "CloseConnection() can be called only when there is a connection.";
close(sockfd_);
sockfd_ = -1;
}
int sockfd_; // socket file descriptor
const string host_name_;
const string port_num_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
}; // class SocketWriter
// Escapes '=', '&', '%', and '\n' characters in str as "%xx".
static string UrlEncode(const char* str);
StreamingListener(const string& host, const string& port)
: socket_writer_(new SocketWriter(host, port)) { Start(); }
explicit StreamingListener(AbstractSocketWriter* socket_writer)
: socket_writer_(socket_writer) { Start(); }
void OnTestProgramStart(const UnitTest& /* unit_test */) {
SendLn("event=TestProgramStart");
}
void OnTestProgramEnd(const UnitTest& unit_test) {
// Note that Google Test current only report elapsed time for each
// test iteration, not for the entire test program.
SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
// Notify the streaming server to stop.
socket_writer_->CloseConnection();
}
void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
SendLn("event=TestIterationStart&iteration=" +
StreamableToString(iteration));
}
void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
SendLn("event=TestIterationEnd&passed=" +
FormatBool(unit_test.Passed()) + "&elapsed_time=" +
StreamableToString(unit_test.elapsed_time()) + "ms");
}
void OnTestCaseStart(const TestCase& test_case) {
SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
}
void OnTestCaseEnd(const TestCase& test_case) {
SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
+ "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
+ "ms");
}
void OnTestStart(const TestInfo& test_info) {
SendLn(std::string("event=TestStart&name=") + test_info.name());
}
void OnTestEnd(const TestInfo& test_info) {
SendLn("event=TestEnd&passed=" +
FormatBool((test_info.result())->Passed()) +
"&elapsed_time=" +
StreamableToString((test_info.result())->elapsed_time()) + "ms");
}
void OnTestPartResult(const TestPartResult& test_part_result) {
const char* file_name = test_part_result.file_name();
if (file_name == NULL)
file_name = "";
SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
"&line=" + StreamableToString(test_part_result.line_number()) +
"&message=" + UrlEncode(test_part_result.message()));
}
private:
// Sends the given message and a newline to the socket.
void SendLn(const string& message) { socket_writer_->SendLn(message); }
// Called at the start of streaming to notify the receiver what
// protocol we are using.
void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
string FormatBool(bool value) { return value ? "1" : "0"; }
const scoped_ptr<AbstractSocketWriter> socket_writer_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
}; // class StreamingListener
#endif // GTEST_CAN_STREAM_RESULTS_
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing

View File

@ -36,14 +36,14 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS
# include <windows.h> // For TerminateProcess() # include <windows.h>
#elif GTEST_OS_WINDOWS
# include <io.h> # include <io.h>
# include <sys/stat.h> # include <sys/stat.h>
# include <map> // Used in ThreadLocal.
#else #else
# include <unistd.h> # include <unistd.h>
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS
#if GTEST_OS_MAC #if GTEST_OS_MAC
# include <mach/mach_init.h> # include <mach/mach_init.h>
@ -51,6 +51,12 @@
# include <mach/vm_map.h> # include <mach/vm_map.h>
#endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
#if GTEST_OS_QNX
# include <devctl.h>
# include <fcntl.h>
# include <sys/procfs.h>
#endif // GTEST_OS_QNX
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
@ -58,9 +64,9 @@
// Indicates that this translation unit is part of Google Test's // Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is // implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to // included, or there will be a compiler error. This trick exists to
// prevent a user from accidentally including gtest-internal-inl.h in // prevent the accidental inclusion of gtest-internal-inl.h in the
// his code. // user's code.
#define GTEST_IMPLEMENTATION_ 1 #define GTEST_IMPLEMENTATION_ 1
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_ #undef GTEST_IMPLEMENTATION_
@ -98,6 +104,26 @@ size_t GetThreadCount() {
} }
} }
#elif GTEST_OS_QNX
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
size_t GetThreadCount() {
const int fd = open("/proc/self/as", O_RDONLY);
if (fd < 0) {
return 0;
}
procfs_info process_info;
const int status =
devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
close(fd);
if (status == EOK) {
return static_cast<size_t>(process_info.num_threads);
} else {
return 0;
}
}
#else #else
size_t GetThreadCount() { size_t GetThreadCount() {
@ -108,6 +134,389 @@ size_t GetThreadCount() {
#endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
void SleepMilliseconds(int n) {
::Sleep(n);
}
AutoHandle::AutoHandle()
: handle_(INVALID_HANDLE_VALUE) {}
AutoHandle::AutoHandle(Handle handle)
: handle_(handle) {}
AutoHandle::~AutoHandle() {
Reset();
}
AutoHandle::Handle AutoHandle::Get() const {
return handle_;
}
void AutoHandle::Reset() {
Reset(INVALID_HANDLE_VALUE);
}
void AutoHandle::Reset(HANDLE handle) {
// Resetting with the same handle we already own is invalid.
if (handle_ != handle) {
if (IsCloseable()) {
::CloseHandle(handle_);
}
handle_ = handle;
} else {
GTEST_CHECK_(!IsCloseable())
<< "Resetting a valid handle to itself is likely a programmer error "
"and thus not allowed.";
}
}
bool AutoHandle::IsCloseable() const {
// Different Windows APIs may use either of these values to represent an
// invalid handle.
return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
}
Notification::Notification()
: event_(::CreateEvent(NULL, // Default security attributes.
TRUE, // Do not reset automatically.
FALSE, // Initially unset.
NULL)) { // Anonymous event.
GTEST_CHECK_(event_.Get() != NULL);
}
void Notification::Notify() {
GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
}
void Notification::WaitForNotification() {
GTEST_CHECK_(
::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
}
Mutex::Mutex()
: type_(kDynamic),
owner_thread_id_(0),
critical_section_init_phase_(0),
critical_section_(new CRITICAL_SECTION) {
::InitializeCriticalSection(critical_section_);
}
Mutex::~Mutex() {
// Static mutexes are leaked intentionally. It is not thread-safe to try
// to clean them up.
// TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
// nothing to clean it up but is available only on Vista and later.
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
if (type_ == kDynamic) {
::DeleteCriticalSection(critical_section_);
delete critical_section_;
critical_section_ = NULL;
}
}
void Mutex::Lock() {
ThreadSafeLazyInit();
::EnterCriticalSection(critical_section_);
owner_thread_id_ = ::GetCurrentThreadId();
}
void Mutex::Unlock() {
ThreadSafeLazyInit();
// We don't protect writing to owner_thread_id_ here, as it's the
// caller's responsibility to ensure that the current thread holds the
// mutex when this is called.
owner_thread_id_ = 0;
::LeaveCriticalSection(critical_section_);
}
// Does nothing if the current thread holds the mutex. Otherwise, crashes
// with high probability.
void Mutex::AssertHeld() {
ThreadSafeLazyInit();
GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
<< "The current thread is not holding the mutex @" << this;
}
// Initializes owner_thread_id_ and critical_section_ in static mutexes.
void Mutex::ThreadSafeLazyInit() {
// Dynamic mutexes are initialized in the constructor.
if (type_ == kStatic) {
switch (
::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
case 0:
// If critical_section_init_phase_ was 0 before the exchange, we
// are the first to test it and need to perform the initialization.
owner_thread_id_ = 0;
critical_section_ = new CRITICAL_SECTION;
::InitializeCriticalSection(critical_section_);
// Updates the critical_section_init_phase_ to 2 to signal
// initialization complete.
GTEST_CHECK_(::InterlockedCompareExchange(
&critical_section_init_phase_, 2L, 1L) ==
1L);
break;
case 1:
// Somebody else is already initializing the mutex; spin until they
// are done.
while (::InterlockedCompareExchange(&critical_section_init_phase_,
2L,
2L) != 2L) {
// Possibly yields the rest of the thread's time slice to other
// threads.
::Sleep(0);
}
break;
case 2:
break; // The mutex is already initialized and ready for use.
default:
GTEST_CHECK_(false)
<< "Unexpected value of critical_section_init_phase_ "
<< "while initializing a static mutex.";
}
}
}
namespace {
class ThreadWithParamSupport : public ThreadWithParamBase {
public:
static HANDLE CreateThread(Runnable* runnable,
Notification* thread_can_start) {
ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
DWORD thread_id;
// TODO(yukawa): Consider to use _beginthreadex instead.
HANDLE thread_handle = ::CreateThread(
NULL, // Default security.
0, // Default stack size.
&ThreadWithParamSupport::ThreadMain,
param, // Parameter to ThreadMainStatic
0x0, // Default creation flags.
&thread_id); // Need a valid pointer for the call to work under Win98.
GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
<< ::GetLastError() << ".";
if (thread_handle == NULL) {
delete param;
}
return thread_handle;
}
private:
struct ThreadMainParam {
ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
: runnable_(runnable),
thread_can_start_(thread_can_start) {
}
scoped_ptr<Runnable> runnable_;
// Does not own.
Notification* thread_can_start_;
};
static DWORD WINAPI ThreadMain(void* ptr) {
// Transfers ownership.
scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
if (param->thread_can_start_ != NULL)
param->thread_can_start_->WaitForNotification();
param->runnable_->Run();
return 0;
}
// Prohibit instantiation.
ThreadWithParamSupport();
GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
};
} // namespace
ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
Notification* thread_can_start)
: thread_(ThreadWithParamSupport::CreateThread(runnable,
thread_can_start)) {
}
ThreadWithParamBase::~ThreadWithParamBase() {
Join();
}
void ThreadWithParamBase::Join() {
GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
<< "Failed to join the thread with error " << ::GetLastError() << ".";
}
// Maps a thread to a set of ThreadIdToThreadLocals that have values
// instantiated on that thread and notifies them when the thread exits. A
// ThreadLocal instance is expected to persist until all threads it has
// values on have terminated.
class ThreadLocalRegistryImpl {
public:
// Registers thread_local_instance as having value on the current thread.
// Returns a value that can be used to identify the thread from other threads.
static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
const ThreadLocalBase* thread_local_instance) {
DWORD current_thread = ::GetCurrentThreadId();
MutexLock lock(&mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked();
ThreadIdToThreadLocals::iterator thread_local_pos =
thread_to_thread_locals->find(current_thread);
if (thread_local_pos == thread_to_thread_locals->end()) {
thread_local_pos = thread_to_thread_locals->insert(
std::make_pair(current_thread, ThreadLocalValues())).first;
StartWatcherThreadFor(current_thread);
}
ThreadLocalValues& thread_local_values = thread_local_pos->second;
ThreadLocalValues::iterator value_pos =
thread_local_values.find(thread_local_instance);
if (value_pos == thread_local_values.end()) {
value_pos =
thread_local_values
.insert(std::make_pair(
thread_local_instance,
linked_ptr<ThreadLocalValueHolderBase>(
thread_local_instance->NewValueForCurrentThread())))
.first;
}
return value_pos->second.get();
}
static void OnThreadLocalDestroyed(
const ThreadLocalBase* thread_local_instance) {
std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
// Clean up the ThreadLocalValues data structure while holding the lock, but
// defer the destruction of the ThreadLocalValueHolderBases.
{
MutexLock lock(&mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked();
for (ThreadIdToThreadLocals::iterator it =
thread_to_thread_locals->begin();
it != thread_to_thread_locals->end();
++it) {
ThreadLocalValues& thread_local_values = it->second;
ThreadLocalValues::iterator value_pos =
thread_local_values.find(thread_local_instance);
if (value_pos != thread_local_values.end()) {
value_holders.push_back(value_pos->second);
thread_local_values.erase(value_pos);
// This 'if' can only be successful at most once, so theoretically we
// could break out of the loop here, but we don't bother doing so.
}
}
}
// Outside the lock, let the destructor for 'value_holders' deallocate the
// ThreadLocalValueHolderBases.
}
static void OnThreadExit(DWORD thread_id) {
GTEST_CHECK_(thread_id != 0) << ::GetLastError();
std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
// Clean up the ThreadIdToThreadLocals data structure while holding the
// lock, but defer the destruction of the ThreadLocalValueHolderBases.
{
MutexLock lock(&mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked();
ThreadIdToThreadLocals::iterator thread_local_pos =
thread_to_thread_locals->find(thread_id);
if (thread_local_pos != thread_to_thread_locals->end()) {
ThreadLocalValues& thread_local_values = thread_local_pos->second;
for (ThreadLocalValues::iterator value_pos =
thread_local_values.begin();
value_pos != thread_local_values.end();
++value_pos) {
value_holders.push_back(value_pos->second);
}
thread_to_thread_locals->erase(thread_local_pos);
}
}
// Outside the lock, let the destructor for 'value_holders' deallocate the
// ThreadLocalValueHolderBases.
}
private:
// In a particular thread, maps a ThreadLocal object to its value.
typedef std::map<const ThreadLocalBase*,
linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
// Stores all ThreadIdToThreadLocals having values in a thread, indexed by
// thread's ID.
typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
// Holds the thread id and thread handle that we pass from
// StartWatcherThreadFor to WatcherThreadFunc.
typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
static void StartWatcherThreadFor(DWORD thread_id) {
// The returned handle will be kept in thread_map and closed by
// watcher_thread in WatcherThreadFunc.
HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
FALSE,
thread_id);
GTEST_CHECK_(thread != NULL);
// We need to to pass a valid thread ID pointer into CreateThread for it
// to work correctly under Win98.
DWORD watcher_thread_id;
HANDLE watcher_thread = ::CreateThread(
NULL, // Default security.
0, // Default stack size
&ThreadLocalRegistryImpl::WatcherThreadFunc,
reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
CREATE_SUSPENDED,
&watcher_thread_id);
GTEST_CHECK_(watcher_thread != NULL);
// Give the watcher thread the same priority as ours to avoid being
// blocked by it.
::SetThreadPriority(watcher_thread,
::GetThreadPriority(::GetCurrentThread()));
::ResumeThread(watcher_thread);
::CloseHandle(watcher_thread);
}
// Monitors exit from a given thread and notifies those
// ThreadIdToThreadLocals about thread termination.
static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
const ThreadIdAndHandle* tah =
reinterpret_cast<const ThreadIdAndHandle*>(param);
GTEST_CHECK_(
::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
OnThreadExit(tah->first);
::CloseHandle(tah->second);
delete tah;
return 0;
}
// Returns map of thread local instances.
static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
mutex_.AssertHeld();
static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;
return map;
}
// Protects access to GetThreadLocalsMapLocked() and its return value.
static Mutex mutex_;
// Protects access to GetThreadMapLocked() and its return value.
static Mutex thread_map_mutex_;
};
Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
const ThreadLocalBase* thread_local_instance) {
return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
thread_local_instance);
}
void ThreadLocalRegistry::OnThreadLocalDestroyed(
const ThreadLocalBase* thread_local_instance) {
ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
}
#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
#if GTEST_USES_POSIX_RE #if GTEST_USES_POSIX_RE
// Implements RE. Currently only needed for death tests. // Implements RE. Currently only needed for death tests.
@ -222,7 +631,7 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
} }
// Helper function used by ValidateRegex() to format error messages. // Helper function used by ValidateRegex() to format error messages.
String FormatRegexSyntaxError(const char* regex, int index) { std::string FormatRegexSyntaxError(const char* regex, int index) {
return (Message() << "Syntax error at index " << index return (Message() << "Syntax error at index " << index
<< " in simple regular expression \"" << regex << "\": ").GetString(); << " in simple regular expression \"" << regex << "\": ").GetString();
} }
@ -429,15 +838,15 @@ const char kUnknownFile[] = "unknown file";
// Formats a source file path and a line number as they would appear // Formats a source file path and a line number as they would appear
// in an error message from the compiler used to compile this code. // in an error message from the compiler used to compile this code.
GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
const char* const file_name = file == NULL ? kUnknownFile : file; const std::string file_name(file == NULL ? kUnknownFile : file);
if (line < 0) { if (line < 0) {
return String::Format("%s:", file_name).c_str(); return file_name + ":";
} }
#ifdef _MSC_VER #ifdef _MSC_VER
return String::Format("%s(%d):", file_name, line).c_str(); return file_name + "(" + StreamableToString(line) + "):";
#else #else
return String::Format("%s:%d:", file_name, line).c_str(); return file_name + ":" + StreamableToString(line) + ":";
#endif // _MSC_VER #endif // _MSC_VER
} }
@ -448,12 +857,12 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
// to the file location it produces, unlike FormatFileLocation(). // to the file location it produces, unlike FormatFileLocation().
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
const char* file, int line) { const char* file, int line) {
const char* const file_name = file == NULL ? kUnknownFile : file; const std::string file_name(file == NULL ? kUnknownFile : file);
if (line < 0) if (line < 0)
return file_name; return file_name;
else else
return String::Format("%s:%d", file_name, line).c_str(); return file_name + ":" + StreamableToString(line);
} }
@ -477,10 +886,7 @@ GTestLog::~GTestLog() {
} }
// Disable Microsoft deprecation warnings for POSIX functions called from // Disable Microsoft deprecation warnings for POSIX functions called from
// this class (creat, dup, dup2, and close) // this class (creat, dup, dup2, and close)
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
# pragma warning(push)
# pragma warning(disable: 4996)
#endif // _MSC_VER
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
@ -488,8 +894,7 @@ GTestLog::~GTestLog() {
class CapturedStream { class CapturedStream {
public: public:
// The ctor redirects the stream to a temporary file. // The ctor redirects the stream to a temporary file.
CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
# if GTEST_OS_WINDOWS # if GTEST_OS_WINDOWS
char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
@ -506,10 +911,29 @@ class CapturedStream {
<< temp_file_path; << temp_file_path;
filename_ = temp_file_path; filename_ = temp_file_path;
# else # else
// There's no guarantee that a test has write access to the // There's no guarantee that a test has write access to the current
// current directory, so we create the temporary file in the /tmp // directory, so we create the temporary file in the /tmp directory
// directory instead. // instead. We use /tmp on most systems, and /sdcard on Android.
// That's because Android doesn't have /tmp.
# if GTEST_OS_LINUX_ANDROID
// Note: Android applications are expected to call the framework's
// Context.getExternalStorageDirectory() method through JNI to get
// the location of the world-writable SD Card directory. However,
// this requires a Context handle, which cannot be retrieved
// globally from native code. Doing so also precludes running the
// code as part of a regular standalone executable, which doesn't
// run in a Dalvik process (e.g. when running it through 'adb shell').
//
// The location /sdcard is directly accessible from native code
// and is the only location (unofficially) supported by the Android
// team. It's generally a symlink to the real SD Card mount point
// which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
// other OEM-customized locations. Never rely on these, and always
// use /sdcard.
char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
# else
char name_template[] = "/tmp/captured_stream.XXXXXX"; char name_template[] = "/tmp/captured_stream.XXXXXX";
# endif // GTEST_OS_LINUX_ANDROID
const int captured_fd = mkstemp(name_template); const int captured_fd = mkstemp(name_template);
filename_ = name_template; filename_ = name_template;
# endif // GTEST_OS_WINDOWS # endif // GTEST_OS_WINDOWS
@ -522,7 +946,7 @@ class CapturedStream {
remove(filename_.c_str()); remove(filename_.c_str());
} }
String GetCapturedString() { std::string GetCapturedString() {
if (uncaptured_fd_ != -1) { if (uncaptured_fd_ != -1) {
// Restores the original stream. // Restores the original stream.
fflush(NULL); fflush(NULL);
@ -532,14 +956,14 @@ class CapturedStream {
} }
FILE* const file = posix::FOpen(filename_.c_str(), "r"); FILE* const file = posix::FOpen(filename_.c_str(), "r");
const String content = ReadEntireFile(file); const std::string content = ReadEntireFile(file);
posix::FClose(file); posix::FClose(file);
return content; return content;
} }
private: private:
// Reads the entire content of a file as a String. // Reads the entire content of a file as an std::string.
static String ReadEntireFile(FILE* file); static std::string ReadEntireFile(FILE* file);
// Returns the size (in bytes) of a file. // Returns the size (in bytes) of a file.
static size_t GetFileSize(FILE* file); static size_t GetFileSize(FILE* file);
@ -559,7 +983,7 @@ size_t CapturedStream::GetFileSize(FILE* file) {
} }
// Reads the entire content of a file as a string. // Reads the entire content of a file as a string.
String CapturedStream::ReadEntireFile(FILE* file) { std::string CapturedStream::ReadEntireFile(FILE* file) {
const size_t file_size = GetFileSize(file); const size_t file_size = GetFileSize(file);
char* const buffer = new char[file_size]; char* const buffer = new char[file_size];
@ -575,15 +999,13 @@ String CapturedStream::ReadEntireFile(FILE* file) {
bytes_read += bytes_last_read; bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size); } while (bytes_last_read > 0 && bytes_read < file_size);
const String content(buffer, bytes_read); const std::string content(buffer, bytes_read);
delete[] buffer; delete[] buffer;
return content; return content;
} }
# ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_()
# pragma warning(pop)
# endif // _MSC_VER
static CapturedStream* g_captured_stderr = NULL; static CapturedStream* g_captured_stderr = NULL;
static CapturedStream* g_captured_stdout = NULL; static CapturedStream* g_captured_stdout = NULL;
@ -598,8 +1020,8 @@ void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
} }
// Stops capturing the output stream and returns the captured string. // Stops capturing the output stream and returns the captured string.
String GetCapturedStream(CapturedStream** captured_stream) { std::string GetCapturedStream(CapturedStream** captured_stream) {
const String content = (*captured_stream)->GetCapturedString(); const std::string content = (*captured_stream)->GetCapturedString();
delete *captured_stream; delete *captured_stream;
*captured_stream = NULL; *captured_stream = NULL;
@ -618,21 +1040,37 @@ void CaptureStderr() {
} }
// Stops capturing stdout and returns the captured string. // Stops capturing stdout and returns the captured string.
String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } std::string GetCapturedStdout() {
return GetCapturedStream(&g_captured_stdout);
}
// Stops capturing stderr and returns the captured string. // Stops capturing stderr and returns the captured string.
String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } std::string GetCapturedStderr() {
return GetCapturedStream(&g_captured_stderr);
}
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
// A copy of all command line arguments. Set by InitGoogleTest(). // A copy of all command line arguments. Set by InitGoogleTest().
::std::vector<String> g_argvs; ::std::vector<testing::internal::string> g_argvs;
// Returns the command line as a vector of strings. static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
const ::std::vector<String>& GetArgvs() { return g_argvs; } NULL; // Owned.
void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
if (g_injected_test_argvs != argvs)
delete g_injected_test_argvs;
g_injected_test_argvs = argvs;
}
const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
if (g_injected_test_argvs != NULL) {
return *g_injected_test_argvs;
}
return g_argvs;
}
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
@ -647,8 +1085,8 @@ void Abort() {
// Returns the name of the environment variable corresponding to the // Returns the name of the environment variable corresponding to the
// given flag. For example, FlagToEnvVar("foo") will return // given flag. For example, FlagToEnvVar("foo") will return
// "GTEST_FOO" in the open-source version. // "GTEST_FOO" in the open-source version.
static String FlagToEnvVar(const char* flag) { static std::string FlagToEnvVar(const char* flag) {
const String full_flag = const std::string full_flag =
(Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
Message env_var; Message env_var;
@ -705,7 +1143,7 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
// //
// The value is considered true iff it's not "0". // The value is considered true iff it's not "0".
bool BoolFromGTestEnv(const char* flag, bool default_value) { bool BoolFromGTestEnv(const char* flag, bool default_value) {
const String env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str()); const char* const string_value = posix::GetEnv(env_var.c_str());
return string_value == NULL ? return string_value == NULL ?
default_value : strcmp(string_value, "0") != 0; default_value : strcmp(string_value, "0") != 0;
@ -715,7 +1153,7 @@ bool BoolFromGTestEnv(const char* flag, bool default_value) {
// variable corresponding to the given flag; if it isn't set or // variable corresponding to the given flag; if it isn't set or
// doesn't represent a valid 32-bit integer, returns default_value. // doesn't represent a valid 32-bit integer, returns default_value.
Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
const String env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str()); const char* const string_value = posix::GetEnv(env_var.c_str());
if (string_value == NULL) { if (string_value == NULL) {
// The environment variable is not set. // The environment variable is not set.
@ -737,7 +1175,7 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
// Reads and returns the string environment variable corresponding to // Reads and returns the string environment variable corresponding to
// the given flag; if it's not set, returns default_value. // the given flag; if it's not set, returns default_value.
const char* StringFromGTestEnv(const char* flag, const char* default_value) { const char* StringFromGTestEnv(const char* flag, const char* default_value) {
const String env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const value = posix::GetEnv(env_var.c_str()); const char* const value = posix::GetEnv(env_var.c_str());
return value == NULL ? default_value : value; return value == NULL ? default_value : value;
} }

View File

@ -45,6 +45,7 @@
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
#include <ctype.h> #include <ctype.h>
#include <stdio.h> #include <stdio.h>
#include <cwchar>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <string> #include <string>
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
@ -55,15 +56,10 @@ namespace {
using ::std::ostream; using ::std::ostream;
#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
# define snprintf _snprintf
#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
# define snprintf _snprintf_s
#elif _MSC_VER
# define snprintf _snprintf
#endif // GTEST_OS_WINDOWS_MOBILE
// Prints a segment of bytes in the given object. // Prints a segment of bytes in the given object.
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) { size_t count, ostream* os) {
char text[5] = ""; char text[5] = "";
@ -77,7 +73,7 @@ void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
else else
*os << '-'; *os << '-';
} }
snprintf(text, sizeof(text), "%02X", obj_bytes[j]); GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text; *os << text;
} }
} }
@ -184,16 +180,16 @@ static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
*os << static_cast<char>(c); *os << static_cast<char>(c);
return kAsIs; return kAsIs;
} else { } else {
*os << String::Format("\\x%X", static_cast<UnsignedChar>(c)); *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
return kHexEscape; return kHexEscape;
} }
} }
return kSpecialEscape; return kSpecialEscape;
} }
// Prints a char c as if it's part of a string literal, escaping it when // Prints a wchar_t c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted. // necessary; returns how c was formatted.
static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) { static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
switch (c) { switch (c) {
case L'\'': case L'\'':
*os << "'"; *os << "'";
@ -208,8 +204,9 @@ static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
// Prints a char c as if it's part of a string literal, escaping it when // Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted. // necessary; returns how c was formatted.
static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) { static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os); return PrintAsStringLiteralTo(
static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
} }
// Prints a wide or narrow character c and its code. '\0' is printed // Prints a wide or narrow character c and its code. '\0' is printed
@ -228,7 +225,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
// obvious). // obvious).
if (c == 0) if (c == 0)
return; return;
*os << " (" << String::Format("%d", c).c_str(); *os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexidecimal, // For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in // unless c was already printed in the form '\x##' or the code is in
@ -236,8 +233,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
if (format == kHexEscape || (1 <= c && c <= 9)) { if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing. // Do nothing.
} else { } else {
*os << String::Format(", 0x%X", *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
static_cast<UnsignedChar>(c)).c_str();
} }
*os << ")"; *os << ")";
} }
@ -255,48 +251,69 @@ void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os); PrintCharAndCodeTo<wchar_t>(wc, os);
} }
// Prints the given array of characters to the ostream. // Prints the given array of characters to the ostream. CharType must be either
// The array starts at *begin, the length is len, it may include '\0' characters // char or wchar_t.
// and may not be null-terminated. // The array starts at begin, the length is len, it may include '\0' characters
static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) { // and may not be NUL-terminated.
*os << "\""; template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
static void PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) {
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
*os << kQuoteBegin;
bool is_previous_hex = false; bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) { for (size_t index = 0; index < len; ++index) {
const char cur = begin[index]; const CharType cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) { if (is_previous_hex && IsXDigit(cur)) {
// Previous character is of '\x..' form and this character can be // Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to // interpreted as another hexadecimal digit in its number. Break string to
// disambiguate. // disambiguate.
*os << "\" \""; *os << "\" " << kQuoteBegin;
} }
is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape; is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
} }
*os << "\""; *os << "\"";
} }
// Prints a (const) char/wchar_t array of 'len' elements, starting at address
// 'begin'. CharType must be either char or wchar_t.
template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
static void UniversalPrintCharArray(
const CharType* begin, size_t len, ostream* os) {
// The code
// const char kFoo[] = "foo";
// generates an array of 4, not 3, elements, with the last one being '\0'.
//
// Therefore when printing a char array, we don't print the last element if
// it's '\0', such that the output matches the string literal as it's
// written in the source code.
if (len > 0 && begin[len - 1] == '\0') {
PrintCharsAsStringTo(begin, len - 1, os);
return;
}
// If, however, the last element in the array is not '\0', e.g.
// const char kFoo[] = { 'f', 'o', 'o' };
// we must print the entire array. We also print a message to indicate
// that the array is not NUL-terminated.
PrintCharsAsStringTo(begin, len, os);
*os << " (no terminating NUL)";
}
// Prints a (const) char array of 'len' elements, starting at address 'begin'. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) { void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
PrintCharsAsStringTo(begin, len, os); UniversalPrintCharArray(begin, len, os);
} }
// Prints the given array of wide characters to the ostream. // Prints a (const) wchar_t array of 'len' elements, starting at address
// The array starts at *begin, the length is len, it may include L'\0' // 'begin'.
// characters and may not be null-terminated. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len, UniversalPrintCharArray(begin, len, os);
ostream* os) {
*os << "L\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const wchar_t cur = begin[index];
if (is_previous_hex && isascii(cur) && IsXDigit(static_cast<char>(cur))) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" L\"";
}
is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
} }
// Prints the given C string to the ostream. // Prints the given C string to the ostream.
@ -322,7 +339,7 @@ void PrintTo(const wchar_t* s, ostream* os) {
*os << "NULL"; *os << "NULL";
} else { } else {
*os << ImplicitCast_<const void*>(s) << " pointing to "; *os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintWideCharsAsStringTo(s, wcslen(s), os); PrintCharsAsStringTo(s, std::wcslen(s), os);
} }
} }
#endif // wchar_t is native #endif // wchar_t is native
@ -341,13 +358,13 @@ void PrintStringTo(const ::std::string& s, ostream* os) {
// Prints a ::wstring object. // Prints a ::wstring object.
#if GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_GLOBAL_WSTRING
void PrintWideStringTo(const ::wstring& s, ostream* os) { void PrintWideStringTo(const ::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os); PrintCharsAsStringTo(s.data(), s.size(), os);
} }
#endif // GTEST_HAS_GLOBAL_WSTRING #endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) { void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os); PrintCharsAsStringTo(s.data(), s.size(), os);
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING

View File

@ -35,9 +35,9 @@
// Indicates that this translation unit is part of Google Test's // Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is // implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to // included, or there will be a compiler error. This trick exists to
// prevent a user from accidentally including gtest-internal-inl.h in // prevent the accidental inclusion of gtest-internal-inl.h in the
// his code. // user's code.
#define GTEST_IMPLEMENTATION_ 1 #define GTEST_IMPLEMENTATION_ 1
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_ #undef GTEST_IMPLEMENTATION_
@ -48,10 +48,10 @@ using internal::GetUnitTestImpl;
// Gets the summary of the failure message by omitting the stack trace // Gets the summary of the failure message by omitting the stack trace
// in it. // in it.
internal::String TestPartResult::ExtractSummary(const char* message) { std::string TestPartResult::ExtractSummary(const char* message) {
const char* const stack_trace = strstr(message, internal::kStackTraceMarker); const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
return stack_trace == NULL ? internal::String(message) : return stack_trace == NULL ? message :
internal::String(message, stack_trace - message); std::string(message, stack_trace);
} }
// Prints a TestPartResult object. // Prints a TestPartResult object.

View File

@ -45,6 +45,15 @@ static const char* SkipSpaces(const char* str) {
return str; return str;
} }
static std::vector<std::string> SplitIntoTestNames(const char* src) {
std::vector<std::string> name_vec;
src = SkipSpaces(src);
for (; src != NULL; src = SkipComma(src)) {
name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
}
return name_vec;
}
// Verifies that registered_tests match the test names in // Verifies that registered_tests match the test names in
// defined_test_names_; returns registered_tests if successful, or // defined_test_names_; returns registered_tests if successful, or
// aborts the program otherwise. // aborts the program otherwise.
@ -53,15 +62,14 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames(
typedef ::std::set<const char*>::const_iterator DefinedTestIter; typedef ::std::set<const char*>::const_iterator DefinedTestIter;
registered_ = true; registered_ = true;
// Skip initial whitespace in registered_tests since some std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
// preprocessors prefix stringizied literals with whitespace.
registered_tests = SkipSpaces(registered_tests);
Message errors; Message errors;
::std::set<String> tests;
for (const char* names = registered_tests; names != NULL; std::set<std::string> tests;
names = SkipComma(names)) { for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
const String name = GetPrefixUntilComma(names); name_it != name_vec.end(); ++name_it) {
const std::string& name = *name_it;
if (tests.count(name) != 0) { if (tests.count(name) != 0) {
errors << "Test " << name << " is listed more than once.\n"; errors << "Test " << name << " is listed more than once.\n";
continue; continue;
@ -93,7 +101,7 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames(
} }
} }
const String& errors_str = errors.GetString(); const std::string& errors_str = errors.GetString();
if (errors_str != "") { if (errors_str != "") {
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
errors_str.c_str()); errors_str.c_str());

File diff suppressed because it is too large Load Diff

View File

@ -27,13 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream> #include <stdio.h>
#include "gtest/gtest.h" #include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) { GTEST_API_ int main(int argc, char **argv) {
std::cout << "Running main() from gtest_main.cc\n"; printf("Running main() from gtest_main.cc\n");
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }