diff options
author | Iain Merrick <husky@google.com> | 2010-11-01 12:19:54 +0000 |
---|---|---|
committer | Iain Merrick <husky@google.com> | 2010-11-03 10:21:10 +0000 |
commit | 731df977c0511bca2206b5f333555b1205ff1f43 (patch) | |
tree | 0e750b949b3f00a1ac11fda25d3c2de512f2b465 /testing | |
parent | 5add15e10e7bb80512f2c597ca57221314abe577 (diff) | |
download | external_chromium-731df977c0511bca2206b5f333555b1205ff1f43.zip external_chromium-731df977c0511bca2206b5f333555b1205ff1f43.tar.gz external_chromium-731df977c0511bca2206b5f333555b1205ff1f43.tar.bz2 |
Merge Chromium at r63472 : Initial merge by git.
Change-Id: Ifb9ee821af006a5f2211e81471be93ae440a1f5a
Diffstat (limited to 'testing')
105 files changed, 2501 insertions, 3581 deletions
diff --git a/testing/gtest/CMakeLists.txt b/testing/gtest/CMakeLists.txt index 4a978a1..130719f 100644 --- a/testing/gtest/CMakeLists.txt +++ b/testing/gtest/CMakeLists.txt @@ -1,8 +1,5 @@ ######################################################################## -# Experimental CMake build script for Google Test. -# -# Consider this a prototype. It will change drastically. For now, -# this is only for people on the cutting edge. +# CMake build script for Google Test. # # To run the tests for Google Test itself on Linux, use 'make test' or # ctest. You can select which tests to run using 'ctest -R regex'. @@ -23,6 +20,9 @@ option(gtest_build_tests "Build all of gtest's own tests." OFF) option(gtest_build_samples "Build gtest's sample programs." OFF) +option(gtest_disable_pthreads "Disable uses of pthreads in gtest." OFF) + +# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). include(cmake/hermetic_build.cmake OPTIONAL) if (COMMAND pre_project_set_up_hermetic_build) @@ -46,10 +46,10 @@ if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() -# Defines functions and variables used by Google Test. +# Define helper functions and macros used by Google Test. include(cmake/internal_utils.cmake) -fix_default_settings() # Defined in internal_utils.cmake. +config_compiler_and_linker() # Defined in internal_utils.cmake. # Where Google Test's .h files can be found. include_directories( @@ -142,6 +142,8 @@ if (gtest_build_tests) cxx_library(gtest_no_exception "${cxx_no_exception}" src/gtest-all.cc) + cxx_library(gtest_main_no_exception "${cxx_no_exception}" + src/gtest-all.cc src/gtest_main.cc) cxx_library(gtest_main_no_rtti "${cxx_no_rtti}" src/gtest-all.cc src/gtest_main.cc) @@ -180,6 +182,18 @@ if (gtest_build_tests) cxx_executable(gtest_break_on_failure_unittest_ test gtest) py_test(gtest_break_on_failure_unittest) + cxx_executable_with_flags( + gtest_catch_exceptions_no_ex_test_ + "${cxx_no_exception}" + gtest_main_no_exception + test/gtest_catch_exceptions_test_.cc) + cxx_executable_with_flags( + gtest_catch_exceptions_ex_test_ + "${cxx_exception}" + gtest_main + test/gtest_catch_exceptions_test_.cc) + py_test(gtest_catch_exceptions_test) + cxx_executable(gtest_color_test_ test gtest) py_test(gtest_color_test) diff --git a/testing/gtest/Makefile.am b/testing/gtest/Makefile.am index c661db0..e4628aa 100644 --- a/testing/gtest/Makefile.am +++ b/testing/gtest/Makefile.am @@ -7,9 +7,9 @@ EXTRA_DIST = \ CHANGES \ CONTRIBUTORS \ include/gtest/gtest-param-test.h.pump \ + include/gtest/internal/gtest-param-util-generated.h.pump \ include/gtest/internal/gtest-tuple.h.pump \ include/gtest/internal/gtest-type-util.h.pump \ - include/gtest/internal/gtest-param-util-generated.h.pump \ make/Makefile \ scripts/fuse_gtest_files.py \ scripts/gen_gtest_pred_impl.py \ @@ -19,14 +19,14 @@ EXTRA_DIST = \ # gtest source files that we don't compile directly. They are # #included by gtest-all.cc. GTEST_SRC = \ - src/gtest.cc \ src/gtest-death-test.cc \ src/gtest-filepath.cc \ src/gtest-internal-inl.h \ src/gtest-port.cc \ src/gtest-printers.cc \ src/gtest-test-part.cc \ - src/gtest-typed-test.cc + src/gtest-typed-test.cc \ + src/gtest.cc EXTRA_DIST += $(GTEST_SRC) @@ -45,56 +45,56 @@ EXTRA_DIST += \ # C++ test files that we don't compile directly. EXTRA_DIST += \ test/gtest-death-test_test.cc \ - test/gtest_environment_test.cc \ test/gtest-filepath_test.cc \ test/gtest-linked_ptr_test.cc \ + test/gtest-listener_test.cc \ test/gtest-message_test.cc \ - test/gtest_no_test_unittest.cc \ test/gtest-options_test.cc \ - test/gtest-param-test_test.cc \ test/gtest-param-test2_test.cc \ + test/gtest-param-test2_test.cc \ + test/gtest-param-test_test.cc \ + test/gtest-param-test_test.cc \ test/gtest-param-test_test.h \ test/gtest-port_test.cc \ test/gtest-printers_test.cc \ - test/gtest_pred_impl_unittest.cc \ - test/gtest_prod_test.cc \ - test/production.cc \ - test/production.h \ - test/gtest_repeat_test.cc \ - test/gtest_sole_header_test.cc \ - test/gtest_stress_test.cc \ test/gtest-test-part_test.cc \ - test/gtest_throw_on_failure_ex_test.cc \ - test/gtest-typed-test_test.cc \ + test/gtest-tuple_test.cc \ test/gtest-typed-test2_test.cc \ + test/gtest-typed-test_test.cc \ test/gtest-typed-test_test.h \ - test/gtest_unittest.cc \ test/gtest-unittest-api_test.cc \ - test/gtest-listener_test.cc \ - test/gtest_main_unittest.cc \ - test/gtest_unittest.cc \ - test/gtest-tuple_test.cc \ - test/gtest-param-test_test.cc \ - test/gtest-param-test2_test.cc \ test/gtest_break_on_failure_unittest_.cc \ + test/gtest_catch_exceptions_test_.cc \ test/gtest_color_test_.cc \ test/gtest_env_var_test_.cc \ + test/gtest_environment_test.cc \ test/gtest_filter_unittest_.cc \ test/gtest_help_test_.cc \ test/gtest_list_tests_unittest_.cc \ + test/gtest_main_unittest.cc \ + test/gtest_no_test_unittest.cc \ test/gtest_output_test_.cc \ + test/gtest_pred_impl_unittest.cc \ + test/gtest_prod_test.cc \ + test/gtest_repeat_test.cc \ test/gtest_shuffle_test_.cc \ + test/gtest_sole_header_test.cc \ + test/gtest_stress_test.cc \ + test/gtest_throw_on_failure_ex_test.cc \ test/gtest_throw_on_failure_test_.cc \ test/gtest_uninitialized_test_.cc \ + test/gtest_unittest.cc \ + test/gtest_unittest.cc \ test/gtest_xml_outfile1_test_.cc \ test/gtest_xml_outfile2_test_.cc \ - test/gtest_xml_output_unittest_.cc + test/gtest_xml_output_unittest_.cc \ + test/production.cc \ + test/production.h # Python tests that we don't run. EXTRA_DIST += \ - test/gtest_test_utils.py \ - test/gtest_xml_test_utils.py \ test/gtest_break_on_failure_unittest.py \ + test/gtest_catch_exceptions_test.py \ test/gtest_color_test.py \ test/gtest_env_var_test.py \ test/gtest_filter_unittest.py \ @@ -102,14 +102,13 @@ EXTRA_DIST += \ test/gtest_list_tests_unittest.py \ test/gtest_output_test.py \ test/gtest_output_test_golden_lin.txt \ - test/gtest_output_test_golden_win.txt \ test/gtest_shuffle_test.py \ + test/gtest_test_utils.py \ test/gtest_throw_on_failure_test.py \ test/gtest_uninitialized_test.py \ test/gtest_xml_outfiles_test.py \ test/gtest_xml_output_unittest.py \ - test/run_tests_util.py \ - test/run_tests_util_test.py + test/gtest_xml_test_utils.py # CMake script EXTRA_DIST += \ @@ -118,8 +117,8 @@ EXTRA_DIST += \ # MSVC project files EXTRA_DIST += \ msvc/gtest-md.sln \ - msvc/gtest.sln \ msvc/gtest-md.vcproj \ + msvc/gtest.sln \ msvc/gtest.vcproj \ msvc/gtest_main-md.vcproj \ msvc/gtest_main.vcproj \ @@ -137,27 +136,27 @@ EXTRA_DIST += \ xcode/Config/StaticLibraryTarget.xcconfig \ xcode/Config/TestTarget.xcconfig \ xcode/Resources/Info.plist \ - xcode/Scripts/versiongenerate.py \ xcode/Scripts/runtests.sh \ + xcode/Scripts/versiongenerate.py \ xcode/gtest.xcodeproj/project.pbxproj # xcode sample files EXTRA_DIST += \ xcode/Samples/FrameworkSample/Info.plist \ + xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj \ xcode/Samples/FrameworkSample/runtests.sh \ - xcode/Samples/FrameworkSample/widget_test.cc \ xcode/Samples/FrameworkSample/widget.cc \ xcode/Samples/FrameworkSample/widget.h \ - xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj + xcode/Samples/FrameworkSample/widget_test.cc # C++Builder project files EXTRA_DIST += \ + codegear/gtest.cbproj \ + codegear/gtest.groupproj \ codegear/gtest_all.cc \ codegear/gtest_link.cc \ - codegear/gtest.cbproj \ codegear/gtest_main.cbproj \ - codegear/gtest_unittest.cbproj \ - codegear/gtest.groupproj + codegear/gtest_unittest.cbproj # Scripts and utilities bin_SCRIPTS = scripts/gtest-config @@ -185,16 +184,17 @@ lib_LTLIBRARIES = lib/libgtest.la lib/libgtest_main.la lib_libgtest_la_SOURCES = src/gtest-all.cc -pkginclude_HEADERS = include/gtest/gtest.h \ - include/gtest/gtest-death-test.h \ - include/gtest/gtest-message.h \ - include/gtest/gtest-param-test.h \ - include/gtest/gtest_pred_impl.h \ - include/gtest/gtest-printers.h \ - include/gtest/gtest_prod.h \ - include/gtest/gtest-spi.h \ - include/gtest/gtest-test-part.h \ - include/gtest/gtest-typed-test.h +pkginclude_HEADERS = \ + include/gtest/gtest-death-test.h \ + include/gtest/gtest-message.h \ + include/gtest/gtest-param-test.h \ + include/gtest/gtest-printers.h \ + include/gtest/gtest-spi.h \ + include/gtest/gtest-test-part.h \ + include/gtest/gtest-typed-test.h \ + include/gtest/gtest.h \ + include/gtest/gtest_pred_impl.h \ + include/gtest/gtest_prod.h pkginclude_internaldir = $(pkgincludedir)/internal pkginclude_internal_HEADERS = \ @@ -221,13 +221,14 @@ lib_libgtest_main_la_LIBADD = lib/libgtest.la noinst_LTLIBRARIES = samples/libsamples.la -samples_libsamples_la_SOURCES = samples/sample1.cc \ - samples/sample1.h \ - samples/sample2.cc \ - samples/sample2.h \ - samples/sample3-inl.h \ - samples/sample4.cc \ - samples/sample4.h +samples_libsamples_la_SOURCES = \ + samples/sample1.cc \ + samples/sample1.h \ + samples/sample2.cc \ + samples/sample2.h \ + samples/sample3-inl.h \ + samples/sample4.cc \ + samples/sample4.h TESTS= TESTS_ENVIRONMENT = GTEST_SOURCE_DIR="$(srcdir)/test" \ @@ -257,8 +258,8 @@ test_gtest_all_test_LDADD = lib/libgtest_main.la # Tests that fused gtest files compile and work. FUSED_GTEST_SRC = \ fused-src/gtest/gtest-all.cc \ - fused-src/gtest/gtest_main.cc \ - fused-src/gtest/gtest.h + fused-src/gtest/gtest.h \ + fused-src/gtest/gtest_main.cc TESTS += test/fused_gtest_test check_PROGRAMS += test/fused_gtest_test diff --git a/testing/gtest/README b/testing/gtest/README index 792abf3..51a9376 100644 --- a/testing/gtest/README +++ b/testing/gtest/README @@ -262,7 +262,7 @@ 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 +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.). @@ -288,7 +288,7 @@ 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 +To compile *gtest* as a shared library, add -DGTEST_CREATE_SHARED_LIBRARY=1 @@ -296,12 +296,20 @@ 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 +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 diff --git a/testing/gtest/cmake/internal_utils.cmake b/testing/gtest/cmake/internal_utils.cmake index 01dda3f..e2e224b 100644 --- a/testing/gtest/cmake/internal_utils.cmake +++ b/testing/gtest/cmake/internal_utils.cmake @@ -1,13 +1,22 @@ -# NOTE: This file can be included both into Google Test's and Google Mock's -# build scripts, so actions and functions defined here need to be -# idempotent. - -# Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. -find_package(Threads) +# Defines functions and macros useful for building Google Test and +# Google Mock. +# +# Note: +# +# - This file will be run twice when building Google Mock (once via +# Google Test's CMakeLists.txt, and once via Google Mock's). +# Therefore it shouldn't have any side effects other than defining +# the functions and macros. +# +# - The functions/macros defined in this file may depend on Google +# Test and Google Mock's option() definitions, and thus must be +# called *after* the options have been defined. -# macro is required here, as inside a function string() will update -# variables only at the function scope. -macro(fix_default_settings) +# Tweaks CMake's default compiler/linker settings to suit Google Test's needs. +# +# This must be a macro(), as inside a function string() can only +# update variables in the function scope. +macro(fix_default_compiler_settings_) if (MSVC) # For MSVC, CMake sets certain flags to defaults we want to override. # This replacement code is taken from sample in the CMake Wiki at @@ -33,62 +42,69 @@ macro(fix_default_settings) endif() endmacro() -# Defines the compiler/linker flags used to build gtest. You can -# tweak these definitions to suit your need. A variable's value is -# empty before it's explicitly assigned to. - -if (MSVC) - # Newlines inside flags variables break CMake's NMake generator. - # 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 "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32") - set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN") - set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") - set(cxx_no_exception_flags "-D_HAS_EXCEPTIONS=0") - set(cxx_no_rtti_flags "-GR-") -elseif (CMAKE_COMPILER_IS_GNUCXX) - set(cxx_base_flags "-Wall -Wshadow") - set(cxx_exception_flags "-fexceptions") - set(cxx_no_exception_flags "-fno-exceptions") - # Until version 4.3.2, GCC doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI - # explicitly. - set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") - set(cxx_strict_flags "-Wextra") -elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro") - set(cxx_exception_flags "-features=except") - # Sun Pro doesn't provide macros to indicate whether exceptions and - # RTTI are enabled, so we define GTEST_HAS_* explicitly. - set(cxx_no_exception_flags "-features=no%except -DGTEST_HAS_EXCEPTIONS=0") - set(cxx_no_rtti_flags "-features=no%rtti -DGTEST_HAS_RTTI=0") -elseif (CMAKE_CXX_COMPILER_ID STREQUAL "VisualAge" OR - CMAKE_CXX_COMPILER_ID STREQUAL "XL") - # CMake 2.8 changes Visual Age's compiler ID to "XL". - set(cxx_exception_flags "-qeh") - set(cxx_no_exception_flags "-qnoeh") - # Until version 9.0, Visual Age doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI - # explicitly. - set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0") -endif() - -if (CMAKE_USE_PTHREADS_INIT) # The pthreads library is available. - set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=1") -endif() - -# For building gtest's own tests and samples. -set(cxx_exception "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_exception_flags}") -set(cxx_no_exception +# Defines the compiler/linker flags used to build Google Test and +# Google Mock. You can tweak these definitions to suit your need. A +# variable's value is empty before it's explicitly assigned to. +macro(config_compiler_and_linker) + if (NOT gtest_disable_pthreads) + # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. + find_package(Threads) + endif() + + fix_default_compiler_settings_() + if (MSVC) + # Newlines inside flags variables break CMake's NMake generator. + # TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds. + set(cxx_base_flags "-GS -W4 -WX -wd4127 -wd4251 -wd4275 -nologo -J -Zi") + set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32") + set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN") + set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") + set(cxx_no_exception_flags "-D_HAS_EXCEPTIONS=0") + set(cxx_no_rtti_flags "-GR-") + elseif (CMAKE_COMPILER_IS_GNUCXX) + set(cxx_base_flags "-Wall -Wshadow") + set(cxx_exception_flags "-fexceptions") + set(cxx_no_exception_flags "-fno-exceptions") + # Until version 4.3.2, GCC doesn't define a macro to indicate + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # explicitly. + set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") + set(cxx_strict_flags "-Wextra") + elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro") + set(cxx_exception_flags "-features=except") + # Sun Pro doesn't provide macros to indicate whether exceptions and + # RTTI are enabled, so we define GTEST_HAS_* explicitly. + set(cxx_no_exception_flags "-features=no%except -DGTEST_HAS_EXCEPTIONS=0") + set(cxx_no_rtti_flags "-features=no%rtti -DGTEST_HAS_RTTI=0") + elseif (CMAKE_CXX_COMPILER_ID STREQUAL "VisualAge" OR + CMAKE_CXX_COMPILER_ID STREQUAL "XL") + # CMake 2.8 changes Visual Age's compiler ID to "XL". + set(cxx_exception_flags "-qeh") + set(cxx_no_exception_flags "-qnoeh") + # Until version 9.0, Visual Age doesn't define a macro to indicate + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # explicitly. + set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0") + endif() + + if (CMAKE_USE_PTHREADS_INIT) # The pthreads library is available and allowed. + set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=1") + else() + set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=0") + endif() + + # For building gtest's own tests and samples. + set(cxx_exception "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_exception_flags}") + set(cxx_no_exception "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_no_exception_flags}") -set(cxx_default "${cxx_exception}") -set(cxx_no_rtti "${cxx_default} ${cxx_no_rtti_flags}") -set(cxx_use_own_tuple "${cxx_default} -DGTEST_USE_OWN_TR1_TUPLE=1") + set(cxx_default "${cxx_exception}") + set(cxx_no_rtti "${cxx_default} ${cxx_no_rtti_flags}") + set(cxx_use_own_tuple "${cxx_default} -DGTEST_USE_OWN_TR1_TUPLE=1") -# For building the gtest libraries. -set(cxx_strict "${cxx_default} ${cxx_strict_flags}") + # For building the gtest libraries. + set(cxx_strict "${cxx_default} ${cxx_strict_flags}") +endmacro() -######################################################################## -# # Defines the gtest & gtest_main libraries. User tests should link # with one of them. function(cxx_library_with_type name type cxx_flags) @@ -108,6 +124,10 @@ function(cxx_library_with_type name type cxx_flags) endif() endfunction() +######################################################################## +# +# Helper functions for creating build targets. + function(cxx_shared_library name cxx_flags) cxx_library_with_type(${name} SHARED "${cxx_flags}" ${ARGN}) endfunction() @@ -184,7 +204,7 @@ function(py_test name) # only at ctest runtime (by calling ctest -c <Configuration>), so # we have to escape $ to delay variable substitution here. add_test(${name} - ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE}) + ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py + --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE}) endif() endfunction() diff --git a/testing/gtest/include/gtest/gtest-death-test.h b/testing/gtest/include/gtest/gtest-death-test.h index 121dc1f..0d1cb36 100644 --- a/testing/gtest/include/gtest/gtest-death-test.h +++ b/testing/gtest/include/gtest/gtest-death-test.h @@ -38,7 +38,7 @@ #ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ -#include <gtest/internal/gtest-death-test-internal.h> +#include "gtest/internal/gtest-death-test-internal.h" namespace testing { diff --git a/testing/gtest/include/gtest/gtest-message.h b/testing/gtest/include/gtest/gtest-message.h index f135b69..ecc04e7 100644 --- a/testing/gtest/include/gtest/gtest-message.h +++ b/testing/gtest/include/gtest/gtest-message.h @@ -48,8 +48,8 @@ #include <limits> -#include <gtest/internal/gtest-string.h> -#include <gtest/internal/gtest-internal.h> +#include "gtest/internal/gtest-string.h" +#include "gtest/internal/gtest-internal.h" namespace testing { @@ -58,7 +58,7 @@ namespace testing { // Typical usage: // // 1. You stream a bunch of values to a Message object. -// It will remember the text in a StrStream. +// It will remember the text in a stringstream. // 2. Then you stream the Message object to an ostream. // This causes the text in the Message to be streamed // to the ostream. @@ -74,7 +74,7 @@ namespace testing { // Message is not intended to be inherited from. In particular, its // destructor is not virtual. // -// Note that StrStream behaves differently in gcc and in MSVC. You +// Note that stringstream behaves differently in gcc and in MSVC. You // can stream a NULL char pointer to it in the former, but not in the // latter (it causes an access violation if you do). The Message // class hides this difference by treating a NULL char pointer as @@ -87,27 +87,26 @@ class GTEST_API_ Message { public: // Constructs an empty Message. - // We allocate the StrStream separately because it otherwise each use of + // We allocate the stringstream separately because otherwise each use of // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's // stack frame leading to huge stack frames in some cases; gcc does not reuse // the stack space. - Message() : ss_(new internal::StrStream) { + 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. - Message(const Message& msg) : ss_(new internal::StrStream) { // NOLINT + Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT *ss_ << msg.GetString(); } // Constructs a Message from a C-string. - explicit Message(const char* str) : ss_(new internal::StrStream) { + explicit Message(const char* str) : ss_(new ::std::stringstream) { *ss_ << str; } - ~Message() { delete ss_; } #if GTEST_OS_SYMBIAN // Streams a value (either a pointer or not) to this object. template <typename T> @@ -119,7 +118,7 @@ class GTEST_API_ Message { // Streams a non-pointer value to this object. template <typename T> inline Message& operator <<(const T& val) { - ::GTestStreamToHelper(ss_, val); + ::GTestStreamToHelper(ss_.get(), val); return *this; } @@ -141,7 +140,7 @@ class GTEST_API_ Message { if (pointer == NULL) { *ss_ << "(null)"; } else { - ::GTestStreamToHelper(ss_, pointer); + ::GTestStreamToHelper(ss_.get(), pointer); } return *this; } @@ -189,7 +188,7 @@ class GTEST_API_ Message { // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. internal::String GetString() const { - return internal::StrStreamToString(ss_); + return internal::StringStreamToString(ss_.get()); } private: @@ -203,17 +202,17 @@ class GTEST_API_ Message { if (pointer == NULL) { *ss_ << "(null)"; } else { - ::GTestStreamToHelper(ss_, pointer); + ::GTestStreamToHelper(ss_.get(), pointer); } } template <typename T> inline void StreamHelper(internal::false_type /*dummy*/, const T& value) { - ::GTestStreamToHelper(ss_, value); + ::GTestStreamToHelper(ss_.get(), value); } #endif // GTEST_OS_SYMBIAN // We'll hold the text streamed to this object here. - internal::StrStream* const ss_; + const internal::scoped_ptr< ::std::stringstream> ss_; // We declare (but don't implement) this to prevent the compiler // from implementing the assignment operator. diff --git a/testing/gtest/include/gtest/gtest-param-test.h b/testing/gtest/include/gtest/gtest-param-test.h index 8100696..fb6ec8f 100644 --- a/testing/gtest/include/gtest/gtest-param-test.h +++ b/testing/gtest/include/gtest/gtest-param-test.h @@ -149,7 +149,7 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); #endif // 0 -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" #if !GTEST_OS_SYMBIAN #include <utility> @@ -158,9 +158,9 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. -#include <gtest/internal/gtest-internal.h> -#include <gtest/internal/gtest-param-util.h> -#include <gtest/internal/gtest-param-util-generated.h> +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util-generated.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/include/gtest/gtest-param-test.h.pump b/testing/gtest/include/gtest/gtest-param-test.h.pump index a231188..cff9972 100644 --- a/testing/gtest/include/gtest/gtest-param-test.h.pump +++ b/testing/gtest/include/gtest/gtest-param-test.h.pump @@ -147,7 +147,7 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); #endif // 0 -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" #if !GTEST_OS_SYMBIAN #include <utility> @@ -156,9 +156,9 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. -#include <gtest/internal/gtest-internal.h> -#include <gtest/internal/gtest-param-util.h> -#include <gtest/internal/gtest-param-util-generated.h> +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util-generated.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/include/gtest/gtest-printers.h b/testing/gtest/include/gtest/gtest-printers.h index 0466c9c..7d90f00 100644 --- a/testing/gtest/include/gtest/gtest-printers.h +++ b/testing/gtest/include/gtest/gtest-printers.h @@ -100,8 +100,8 @@ #include <string> #include <utility> #include <vector> -#include <gtest/internal/gtest-port.h> -#include <gtest/internal/gtest-internal.h> +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-internal.h" namespace testing { @@ -115,16 +115,23 @@ GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ::std::ostream* os); -// TypeWithoutFormatter<T, kIsProto>::PrintValue(value, os) is called +// For selecting which printer to use when a given type has neither << +// nor PrintTo(). +enum TypeKind { + kProtobuf, // a protobuf type + kConvertibleToInteger, // a type implicitly convertible to BiggestInt + // (e.g. a named or unnamed enum type) + kOtherType, // anything else +}; + +// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called // by the universal printer to print a value of type T when neither -// operator<< nor PrintTo() is defined for type T. When T is -// ProtocolMessage, proto2::Message, or a subclass of those, kIsProto -// will be true and the short debug string of the protocol message -// value will be printed; otherwise kIsProto will be false and the -// bytes in the value will be printed. -template <typename T, bool kIsProto> +// operator<< nor PrintTo() is defined for T, where kTypeKind is the +// "kind" of T as defined by enum TypeKind. +template <typename T, TypeKind kTypeKind> class TypeWithoutFormatter { public: + // This default version is called when kTypeKind is kOtherType. static void PrintValue(const T& value, ::std::ostream* os) { PrintBytesInObjectTo(reinterpret_cast<const unsigned char*>(&value), sizeof(value), os); @@ -137,22 +144,39 @@ class TypeWithoutFormatter { const size_t kProtobufOneLinerMaxLength = 50; template <typename T> -class TypeWithoutFormatter<T, true> { +class TypeWithoutFormatter<T, kProtobuf> { public: static void PrintValue(const T& value, ::std::ostream* os) { const ::testing::internal::string short_str = value.ShortDebugString(); const ::testing::internal::string pretty_str = short_str.length() <= kProtobufOneLinerMaxLength ? short_str : ("\n" + value.DebugString()); - ::std::operator<<(*os, "<" + pretty_str + ">"); + *os << ("<" + pretty_str + ">"); + } +}; + +template <typename T> +class TypeWithoutFormatter<T, kConvertibleToInteger> { + public: + // Since T has no << operator or PrintTo() but can be implicitly + // converted to BiggestInt, we print it as a BiggestInt. + // + // Most likely T is an enum type (either named or unnamed), in which + // case printing it as an integer is the desired behavior. In case + // T is not an enum, printing it as an integer is the best we can do + // given that it has no user-defined printer. + static void PrintValue(const T& value, ::std::ostream* os) { + const internal::BiggestInt kBigInt = value; + *os << kBigInt; } }; // Prints the given value to the given ostream. If the value is a -// protocol message, its short debug string is printed; otherwise the -// bytes in the value are printed. This is what -// UniversalPrinter<T>::Print() does when it knows nothing about type -// T and T has no << operator. +// protocol message, its debug string is printed; if it's an enum or +// of a type implicitly convertible to BiggestInt, it's printed as an +// integer; otherwise the bytes in the value are printed. This is +// what UniversalPrinter<T>::Print() does when it knows nothing about +// type T and T has neither << operator nor PrintTo(). // // A user can override this behavior for a class type Foo by defining // a << operator in the namespace where Foo is defined. @@ -174,8 +198,10 @@ class TypeWithoutFormatter<T, true> { template <typename Char, typename CharTraits, typename T> ::std::basic_ostream<Char, CharTraits>& operator<<( ::std::basic_ostream<Char, CharTraits>& os, const T& x) { - TypeWithoutFormatter<T, ::testing::internal::IsAProtocolMessage<T>::value>:: - PrintValue(x, &os); + TypeWithoutFormatter<T, + (internal::IsAProtocolMessage<T>::value ? kProtobuf : + internal::ImplicitlyConvertible<const T&, internal::BiggestInt>::value ? + kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); return os; } @@ -280,12 +306,23 @@ void DefaultPrintTo(IsNotContainer /* dummy */, if (p == NULL) { *os << "NULL"; } else { - // We want to print p as a const void*. However, we cannot cast - // it to const void* directly, even using reinterpret_cast, as - // earlier versions of gcc (e.g. 3.4.5) cannot compile the cast - // when p is a function pointer. Casting to UInt64 first solves - // the problem. - *os << reinterpret_cast<const void*>(reinterpret_cast<internal::UInt64>(p)); + // C++ doesn't allow casting from a function pointer to any object + // pointer. + if (ImplicitlyConvertible<T*, const void*>::value) { + // T is not a function type. We just call << to print p, + // relying on ADL to pick up user-defined << for their pointer + // types, if any. + *os << p; + } else { + // T is a function type, so '*os << p' doesn't do what we want + // (it just prints p as bool). We want to print p as a const + // void*. However, we cannot cast it to const void* directly, + // even using reinterpret_cast, as earlier versions of gcc + // (e.g. 3.4.5) cannot compile the cast when p is a function + // pointer. Casting to UInt64 first solves the problem. + *os << reinterpret_cast<const void*>( + reinterpret_cast<internal::UInt64>(p)); + } } } @@ -341,13 +378,8 @@ void PrintTo(const T& value, ::std::ostream* os) { // types, strings, plain arrays, and pointers). // Overloads for various char types. -GTEST_API_ void PrintCharTo(char c, int char_code, ::std::ostream* os); -inline void PrintTo(unsigned char c, ::std::ostream* os) { - PrintCharTo(c, c, os); -} -inline void PrintTo(signed char c, ::std::ostream* os) { - PrintCharTo(c, c, os); -} +GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); +GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); inline void PrintTo(char c, ::std::ostream* os) { // When printing a plain char, we always treat it as unsigned. This // way, the output won't be affected by whether the compiler thinks @@ -375,6 +407,21 @@ inline void PrintTo(char* s, ::std::ostream* os) { PrintTo(implicit_cast<const char*>(s), os); } +// signed/unsigned char is often used for representing binary data, so +// we print pointers to it as void* to be safe. +inline void PrintTo(const signed char* s, ::std::ostream* os) { + PrintTo(implicit_cast<const void*>(s), os); +} +inline void PrintTo(signed char* s, ::std::ostream* os) { + PrintTo(implicit_cast<const void*>(s), os); +} +inline void PrintTo(const unsigned char* s, ::std::ostream* os) { + PrintTo(implicit_cast<const void*>(s), os); +} +inline void PrintTo(unsigned char* s, ::std::ostream* os) { + PrintTo(implicit_cast<const void*>(s), os); +} + // MSVC can be configured to define wchar_t as a typedef of unsigned // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native // type. When wchar_t is a typedef, defining an overload for const diff --git a/testing/gtest/include/gtest/gtest-spi.h b/testing/gtest/include/gtest/gtest-spi.h index c41da48..b226e55 100644 --- a/testing/gtest/include/gtest/gtest-spi.h +++ b/testing/gtest/include/gtest/gtest-spi.h @@ -35,7 +35,7 @@ #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace testing { @@ -98,12 +98,12 @@ class GTEST_API_ SingleFailureChecker { // The constructor remembers the arguments. SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, - const char* substr); + const string& substr); ~SingleFailureChecker(); private: const TestPartResultArray* const results_; const TestPartResult::Type type_; - const String substr_; + const string substr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); }; diff --git a/testing/gtest/include/gtest/gtest-test-part.h b/testing/gtest/include/gtest/gtest-test-part.h index f714759..8aeea14 100644 --- a/testing/gtest/include/gtest/gtest-test-part.h +++ b/testing/gtest/include/gtest/gtest-test-part.h @@ -35,8 +35,8 @@ #include <iosfwd> #include <vector> -#include <gtest/internal/gtest-internal.h> -#include <gtest/internal/gtest-string.h> +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" namespace testing { diff --git a/testing/gtest/include/gtest/gtest-typed-test.h b/testing/gtest/include/gtest/gtest-typed-test.h index 1ec8eb8..eb6b0b8 100644 --- a/testing/gtest/include/gtest/gtest-typed-test.h +++ b/testing/gtest/include/gtest/gtest-typed-test.h @@ -146,8 +146,8 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); #endif // 0 -#include <gtest/internal/gtest-port.h> -#include <gtest/internal/gtest-type-util.h> +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-type-util.h" // Implements typed tests. diff --git a/testing/gtest/include/gtest/gtest.h b/testing/gtest/include/gtest/gtest.h index 937f476..c725e4c 100644 --- a/testing/gtest/include/gtest/gtest.h +++ b/testing/gtest/include/gtest/gtest.h @@ -54,15 +54,15 @@ #include <limits> #include <vector> -#include <gtest/internal/gtest-internal.h> -#include <gtest/internal/gtest-string.h> -#include <gtest/gtest-death-test.h> -#include <gtest/gtest-message.h> -#include <gtest/gtest-param-test.h> -#include <gtest/gtest-printers.h> -#include <gtest/gtest_prod.h> -#include <gtest/gtest-test-part.h> -#include <gtest/gtest-typed-test.h> +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" +#include "gtest/gtest-death-test.h" +#include "gtest/gtest-message.h" +#include "gtest/gtest-param-test.h" +#include "gtest/gtest-printers.h" +#include "gtest/gtest_prod.h" +#include "gtest/gtest-test-part.h" +#include "gtest/gtest-typed-test.h" // Depending on the platform, different string classes are available. // On Linux, in addition to ::std::string, Google also makes use of @@ -137,6 +137,11 @@ GTEST_DECLARE_int32_(stack_trace_depth); // non-zero code otherwise. GTEST_DECLARE_bool_(throw_on_failure); +// When this flag is set with a "host:port" string, on supported +// platforms test results are streamed to the specified port on +// the specified host machine. +GTEST_DECLARE_string_(stream_result_to); + // The upper limit for valid stack trace depths. const int kMaxStackTraceDepth = 100; @@ -148,7 +153,6 @@ class ExecDeathTest; class NoExecDeathTest; class FinalSuccessChecker; class GTestFlagSaver; -class TestInfoImpl; class TestResultAccessor; class TestEventListenersAccessor; class TestEventRepeater; @@ -156,8 +160,6 @@ class WindowsDeathTest; class UnitTestImpl* GetUnitTestImpl(); void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const String& message); -class PrettyUnitTestResultPrinter; -class XmlUnitTestResultPrinter; // Converts a streamable value to a String. A NULL pointer is // converted to "(null)". When the input value is a ::string, @@ -173,6 +175,14 @@ String StreamableToString(const T& streamable) { } // namespace internal +// The friend relationship of some of these classes is cyclic. +// If we don't forward declare them the compiler might confuse the classes +// in friendship clauses with same named classes on the scope. +class Test; +class TestCase; +class TestInfo; +class UnitTest; + // A class for indicating whether an assertion was successful. When // the assertion wasn't successful, the AssertionResult object // remembers a non-empty message that describes how it failed. @@ -341,7 +351,7 @@ GTEST_API_ AssertionResult AssertionFailure(const Message& msg); // Test is not copyable. class GTEST_API_ Test { public: - friend class internal::TestInfoImpl; + friend class TestInfo; // Defines types for pointers to functions that set up and tear down // a test case. @@ -418,6 +428,10 @@ class GTEST_API_ Test { // Sets up, executes, and tears down the test. void Run(); + // Deletes self. We deliberately pick an unusual name for this + // internal method to avoid clashing with names used in user TESTs. + void DeleteSelf_() { delete this; } + // Uses a GTestFlagSaver to save and restore all Google Test flags. const internal::GTestFlagSaver* const gtest_flag_saver_; @@ -532,7 +546,6 @@ class GTEST_API_ TestResult { friend class UnitTest; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::ExecDeathTest; - friend class internal::TestInfoImpl; friend class internal::TestResultAccessor; friend class internal::UnitTestImpl; friend class internal::WindowsDeathTest; @@ -612,16 +625,16 @@ class GTEST_API_ TestInfo { ~TestInfo(); // Returns the test case name. - const char* test_case_name() const; + const char* test_case_name() const { return test_case_name_.c_str(); } // Returns the test name. - const char* name() const; + const char* name() const { return name_.c_str(); } // Returns the test case comment. - const char* test_case_comment() const; + const char* test_case_comment() const { return test_case_comment_.c_str(); } // Returns the test comment. - const char* comment() const; + const char* comment() const { return comment_.c_str(); } // Returns true if this test should run, that is if the test is not disabled // (or it is disabled but the also_run_disabled_tests flag has been specified) @@ -639,10 +652,10 @@ class GTEST_API_ TestInfo { // // For example, *A*:Foo.* is a filter that matches any string that // contains the character 'A' or starts with "Foo.". - bool should_run() const; + bool should_run() const { return should_run_; } // Returns the result of the test. - const TestResult* result() const; + const TestResult* result() const { return &result_; } private: #if GTEST_HAS_DEATH_TEST @@ -650,7 +663,6 @@ class GTEST_API_ TestInfo { #endif // GTEST_HAS_DEATH_TEST friend class Test; friend class TestCase; - friend class internal::TestInfoImpl; friend class internal::UnitTestImpl; friend TestInfo* internal::MakeAndRegisterTestInfo( const char* test_case_name, const char* name, @@ -660,17 +672,6 @@ class GTEST_API_ TestInfo { Test::TearDownTestCaseFunc tear_down_tc, internal::TestFactoryBase* factory); - // Returns true if this test matches the user-specified filter. - bool matches_filter() const; - - // Increments the number of death tests encountered in this test so - // far. - int increment_death_test_count(); - - // Accessors for the implementation object. - internal::TestInfoImpl* impl() { return impl_; } - const internal::TestInfoImpl* impl() const { return impl_; } - // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. TestInfo(const char* test_case_name, const char* name, @@ -678,8 +679,36 @@ class GTEST_API_ TestInfo { internal::TypeId fixture_class_id, internal::TestFactoryBase* factory); - // An opaque implementation object. - internal::TestInfoImpl* impl_; + // Increments the number of death tests encountered in this test so + // far. + int increment_death_test_count() { + return result_.increment_death_test_count(); + } + + // Creates the test object, runs it, records its result, and then + // deletes it. + void Run(); + + static void ClearTestResult(TestInfo* test_info) { + test_info->result_.Clear(); + } + + // These fields are immutable properties of the test. + const std::string test_case_name_; // Test case name + const std::string name_; // Test name + const std::string test_case_comment_; // Test case comment + const std::string comment_; // Test comment + const internal::TypeId fixture_class_id_; // ID of the test fixture class + bool should_run_; // True iff this test should run + bool is_disabled_; // True iff this test is disabled + bool matches_filter_; // True if this test matches the + // user-specified filter. + internal::TestFactoryBase* const factory_; // The factory that creates + // the test object + + // This field is mutable and needs to be reset before running the + // test for the second time. + TestResult result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); }; @@ -777,17 +806,33 @@ class GTEST_API_ TestCase { // Runs every test in this TestCase. void Run(); + // Runs SetUpTestCase() for this TestCase. This wrapper is needed + // for catching exceptions thrown from SetUpTestCase(). + void RunSetUpTestCase() { (*set_up_tc_)(); } + + // Runs TearDownTestCase() for this TestCase. This wrapper is + // needed for catching exceptions thrown from TearDownTestCase(). + void RunTearDownTestCase() { (*tear_down_tc_)(); } + // Returns true iff test passed. - static bool TestPassed(const TestInfo * test_info); + static bool TestPassed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Passed(); + } // Returns true iff test failed. - static bool TestFailed(const TestInfo * test_info); + static bool TestFailed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Failed(); + } // 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_; + } // 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(); + } // Shuffles the tests in this test case. void ShuffleTests(internal::Random* random); @@ -877,7 +922,7 @@ class TestEventListener { // Fired before the test starts. virtual void OnTestStart(const TestInfo& test_info) = 0; - // Fired after a failed assertion or a SUCCESS(). + // Fired after a failed assertion or a SUCCEED() invocation. virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; // Fired after the test ends. @@ -962,10 +1007,10 @@ class GTEST_API_ TestEventListeners { private: friend class TestCase; + friend class TestInfo; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::NoExecDeathTest; friend class internal::TestEventListenersAccessor; - friend class internal::TestInfoImpl; friend class internal::UnitTestImpl; // Returns repeater that broadcasts the TestEventListener events to all @@ -1207,30 +1252,6 @@ GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); namespace internal { -// These overloaded versions handle ::std::string and ::std::wstring. -GTEST_API_ inline String FormatForFailureMessage(const ::std::string& str) { - return (Message() << '"' << str << '"').GetString(); -} - -#if GTEST_HAS_STD_WSTRING -GTEST_API_ inline String FormatForFailureMessage(const ::std::wstring& wstr) { - return (Message() << "L\"" << wstr << '"').GetString(); -} -#endif // GTEST_HAS_STD_WSTRING - -// These overloaded versions handle ::string and ::wstring. -#if GTEST_HAS_GLOBAL_STRING -GTEST_API_ inline String FormatForFailureMessage(const ::string& str) { - return (Message() << '"' << str << '"').GetString(); -} -#endif // GTEST_HAS_GLOBAL_STRING - -#if GTEST_HAS_GLOBAL_WSTRING -GTEST_API_ inline String FormatForFailureMessage(const ::wstring& wstr) { - return (Message() << "L\"" << wstr << '"').GetString(); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - // 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) // of the other operand may affect the format. This allows us to @@ -1246,7 +1267,7 @@ GTEST_API_ inline String FormatForFailureMessage(const ::wstring& wstr) { template <typename T1, typename T2> String FormatForComparisonFailureMessage(const T1& value, const T2& /* other_operand */) { - return FormatForFailureMessage(value); + return PrintToString(value); } // The helper function for {ASSERT|EXPECT}_EQ. @@ -1364,11 +1385,10 @@ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ - Message msg;\ - msg << "Expected: (" << expr1 << ") " #op " (" << expr2\ + return AssertionFailure() \ + << "Expected: (" << expr1 << ") " #op " (" << expr2\ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ << " vs " << FormatForComparisonFailureMessage(val2, val1);\ - return AssertionFailure(msg);\ }\ }\ GTEST_API_ AssertionResult CmpHelper##op_name(\ @@ -1496,18 +1516,18 @@ AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, return AssertionSuccess(); } - StrStream expected_ss; + ::std::stringstream expected_ss; expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << expected; - StrStream actual_ss; + ::std::stringstream actual_ss; actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << actual; return EqFailure(expected_expression, actual_expression, - StrStreamToString(&expected_ss), - StrStreamToString(&actual_ss), + StringStreamToString(&expected_ss), + StringStreamToString(&actual_ss), false); } @@ -1651,6 +1671,12 @@ const T* TestWithParam<T>::parameter_ = NULL; // Generates a nonfatal failure with a generic message. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") +// Generates a nonfatal failure at the given source file location with +// a generic message. +#define ADD_FAILURE_AT(file, line) \ + GTEST_MESSAGE_AT_(file, line, "Failed", \ + ::testing::TestPartResult::kNonFatalFailure) + // Generates a fatal failure with a generic message. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") @@ -1709,7 +1735,7 @@ const T* TestWithParam<T>::parameter_ = NULL; // Includes the auto-generated header that implements a family of // generic predicate assertion macros. -#include <gtest/gtest_pred_impl.h> +#include "gtest/gtest_pred_impl.h" // Macros for testing equalities and inequalities. // @@ -1772,21 +1798,48 @@ const T* TestWithParam<T>::parameter_ = NULL; #define EXPECT_GT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) -#define ASSERT_EQ(expected, actual) \ +#define GTEST_ASSERT_EQ(expected, actual) \ ASSERT_PRED_FORMAT2(::testing::internal:: \ EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \ expected, actual) -#define ASSERT_NE(val1, val2) \ +#define GTEST_ASSERT_NE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) -#define ASSERT_LE(val1, val2) \ +#define GTEST_ASSERT_LE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define ASSERT_LT(val1, val2) \ +#define GTEST_ASSERT_LT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define ASSERT_GE(val1, val2) \ +#define GTEST_ASSERT_GE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define ASSERT_GT(val1, val2) \ +#define GTEST_ASSERT_GT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) +// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of +// ASSERT_XY(), which clashes with some users' own code. + +#if !GTEST_DONT_DEFINE_ASSERT_EQ +#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_NE +#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LE +#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LT +#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GE +#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GT +#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) +#endif + // C String Comparisons. All tests treat NULL and any non-NULL string // as different. Two NULLs are equal. // diff --git a/testing/gtest/include/gtest/gtest_pred_impl.h b/testing/gtest/include/gtest/gtest_pred_impl.h index e1e2f8c..d33f5d5 100644 --- a/testing/gtest/include/gtest/gtest_pred_impl.h +++ b/testing/gtest/include/gtest/gtest_pred_impl.h @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// This file is AUTOMATICALLY GENERATED on 10/02/2008 by command +// This file is AUTOMATICALLY GENERATED on 09/24/2010 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // // Implements a family of generic predicate assertion macros. @@ -90,11 +90,9 @@ AssertionResult AssertPred1Helper(const char* pred_text, const T1& v1) { if (pred(v1)) return AssertionSuccess(); - Message msg; - msg << pred_text << "(" - << e1 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1; - return AssertionFailure(msg); + return AssertionFailure() << pred_text << "(" + << e1 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. @@ -136,13 +134,11 @@ AssertionResult AssertPred2Helper(const char* pred_text, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); - Message msg; - msg << pred_text << "(" - << e1 << ", " - << e2 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2; - return AssertionFailure(msg); + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. @@ -189,15 +185,13 @@ AssertionResult AssertPred3Helper(const char* pred_text, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); - Message msg; - msg << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3; - return AssertionFailure(msg); + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. @@ -249,17 +243,15 @@ AssertionResult AssertPred4Helper(const char* pred_text, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); - Message msg; - msg << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4; - return AssertionFailure(msg); + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. @@ -316,19 +308,17 @@ AssertionResult AssertPred5Helper(const char* pred_text, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); - Message msg; - msg << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ", " - << e5 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4 - << "\n" << e5 << " evaluates to " << v5; - return AssertionFailure(msg); + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ", " + << e5 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4 + << "\n" << e5 << " evaluates to " << v5; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. diff --git a/testing/gtest/include/gtest/internal/gtest-death-test-internal.h b/testing/gtest/include/gtest/internal/gtest-death-test-internal.h index e433084..9242bd3 100644 --- a/testing/gtest/include/gtest/internal/gtest-death-test-internal.h +++ b/testing/gtest/include/gtest/internal/gtest-death-test-internal.h @@ -37,7 +37,7 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ -#include <gtest/internal/gtest-internal.h> +#include "gtest/internal/gtest-internal.h" namespace testing { namespace internal { @@ -176,6 +176,8 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status); gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ break; \ } \ + default: \ + break; \ } \ } \ } else \ diff --git a/testing/gtest/include/gtest/internal/gtest-filepath.h b/testing/gtest/include/gtest/internal/gtest-filepath.h index 4b76d79..b36b3cf 100644 --- a/testing/gtest/include/gtest/internal/gtest-filepath.h +++ b/testing/gtest/include/gtest/internal/gtest-filepath.h @@ -40,7 +40,7 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ -#include <gtest/internal/gtest-string.h> +#include "gtest/internal/gtest-string.h" namespace testing { namespace internal { diff --git a/testing/gtest/include/gtest/internal/gtest-internal.h b/testing/gtest/include/gtest/internal/gtest-internal.h index bf8412b..3307855 100644 --- a/testing/gtest/include/gtest/internal/gtest-internal.h +++ b/testing/gtest/include/gtest/internal/gtest-internal.h @@ -37,7 +37,7 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" #if GTEST_OS_LINUX #include <stdlib.h> @@ -52,9 +52,9 @@ #include <limits> #include <set> -#include <gtest/internal/gtest-string.h> -#include <gtest/internal/gtest-filepath.h> -#include <gtest/internal/gtest-type-util.h> +#include "gtest/internal/gtest-string.h" +#include "gtest/internal/gtest-filepath.h" +#include "gtest/internal/gtest-type-util.h" // Due to C++ preprocessor weirdness, we need double indirection to // concatenate two tokens when one of them is __LINE__. Writing @@ -102,7 +102,7 @@ namespace proto2 { class Message; } namespace testing { -// Forward declaration of classes. +// Forward declarations. class AssertionResult; // Result of an assertion. class Message; // Represents a failure message. @@ -111,6 +111,9 @@ class TestInfo; // Information about a test. class TestPartResult; // Result of a test part. class UnitTest; // A collection of test cases. +template <typename T> +::std::string PrintToString(const T& value); + namespace internal { struct TraceInfo; // Information about a trace point. @@ -192,72 +195,23 @@ class GTEST_API_ ScopedTrace { template <typename T> String StreamableToString(const T& streamable); -// Formats a value to be used in a failure message. - -#ifdef GTEST_NEEDS_IS_POINTER_ - -// These are needed as the Nokia Symbian and IBM XL C/C++ compilers -// cannot decide between const T& and const T* in a function template. -// These compilers _can_ decide between class template specializations -// for T and T*, so a tr1::type_traits-like is_pointer works, and we -// can overload on that. - -// This overload makes sure that all pointers (including -// those to char or wchar_t) are printed as raw pointers. -template <typename T> -inline String FormatValueForFailureMessage(internal::true_type /*dummy*/, - T* pointer) { - return StreamableToString(static_cast<const void*>(pointer)); -} - -template <typename T> -inline String FormatValueForFailureMessage(internal::false_type /*dummy*/, - const T& value) { - return StreamableToString(value); -} - -template <typename T> -inline String FormatForFailureMessage(const T& value) { - return FormatValueForFailureMessage( - typename internal::is_pointer<T>::type(), value); -} - -#else - -// These are needed as the above solution using is_pointer has the -// limitation that T cannot be a type without external linkage, when -// compiled using MSVC. - -template <typename T> -inline String FormatForFailureMessage(const T& value) { - return StreamableToString(value); -} - -// This overload makes sure that all pointers (including -// those to char or wchar_t) are printed as raw pointers. -template <typename T> -inline String FormatForFailureMessage(T* pointer) { - return StreamableToString(static_cast<const void*>(pointer)); -} - -#endif // GTEST_NEEDS_IS_POINTER_ - -// These overloaded versions handle narrow and wide characters. -GTEST_API_ String FormatForFailureMessage(char ch); -GTEST_API_ String FormatForFailureMessage(wchar_t wchar); - -// When this operand is a const char* or char*, and the other operand +// When this operand is a const char* or char*, if the other operand // is a ::std::string or ::string, we print this operand as a C string -// rather than a pointer. We do the same for wide strings. +// rather than a pointer (we do the same for wide strings); otherwise +// we print it as a pointer to be safe. // This internal macro is used to avoid duplicated code. +// Making the first operand const reference works around a bug in the +// Symbian compiler which is unable to select the correct specialization of +// FormatForComparisonFailureMessage. #define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\ inline String FormatForComparisonFailureMessage(\ - operand2_type::value_type* str, const operand2_type& /*operand2*/) {\ + operand2_type::value_type* const& str, const operand2_type& /*operand2*/) {\ return operand1_printer(str);\ }\ inline String FormatForComparisonFailureMessage(\ - const operand2_type::value_type* str, const operand2_type& /*operand2*/) {\ + const operand2_type::value_type* const& str, \ + const operand2_type& /*operand2*/) {\ return operand1_printer(str);\ } @@ -275,6 +229,27 @@ GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted) #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. +// +// Making the first operand const reference works around a bug in the +// Symbian compiler which is unable to select the correct specialization of +// FormatForComparisonFailureMessage. +#define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \ + template <typename T> \ + String FormatForComparisonFailureMessage(CharType* const& 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 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // @@ -607,7 +582,7 @@ GTEST_API_ TestInfo* MakeAndRegisterTestInfo( // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. -bool SkipPrefix(const char* prefix, const char** pstr); +GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P @@ -650,7 +625,7 @@ inline const char* SkipComma(const char* str) { if (comma == NULL) { return NULL; } - while (isspace(*(++comma))) {} + while (IsSpace(*(++comma))) {} return comma; } @@ -1089,10 +1064,13 @@ class NativeArray { } // namespace internal } // namespace testing -#define GTEST_MESSAGE_(message, result_type) \ - ::testing::internal::AssertHelper(result_type, __FILE__, __LINE__, message) \ +#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ + ::testing::internal::AssertHelper(result_type, file, line, message) \ = ::testing::Message() +#define GTEST_MESSAGE_(message, result_type) \ + GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) + #define GTEST_FATAL_FAILURE_(message) \ return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) diff --git a/testing/gtest/include/gtest/internal/gtest-linked_ptr.h b/testing/gtest/include/gtest/internal/gtest-linked_ptr.h index 540ef4c..57147b4 100644 --- a/testing/gtest/include/gtest/internal/gtest-linked_ptr.h +++ b/testing/gtest/include/gtest/internal/gtest-linked_ptr.h @@ -71,7 +71,7 @@ #include <stdlib.h> #include <assert.h> -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" namespace testing { namespace internal { @@ -172,15 +172,6 @@ class linked_ptr { T* get() const { return value_; } T* operator->() const { return value_; } T& operator*() const { return *value_; } - // Release ownership of the pointed object and returns it. - // Sole ownership by this linked_ptr object is required. - T* release() { - bool last = link_.depart(); - assert(last); - T* v = value_; - value_ = NULL; - return v; - } bool operator==(T* p) const { return value_ == p; } bool operator!=(T* p) const { return value_ != p; } diff --git a/testing/gtest/include/gtest/internal/gtest-param-util-generated.h b/testing/gtest/include/gtest/internal/gtest-param-util-generated.h index ab4ab56..306a5e5 100644 --- a/testing/gtest/include/gtest/internal/gtest-param-util-generated.h +++ b/testing/gtest/include/gtest/internal/gtest-param-util-generated.h @@ -47,8 +47,8 @@ // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. -#include <gtest/internal/gtest-param-util.h> -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-port.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/include/gtest/internal/gtest-param-util-generated.h.pump b/testing/gtest/include/gtest/internal/gtest-param-util-generated.h.pump index baedfbc..f261eb7 100644 --- a/testing/gtest/include/gtest/internal/gtest-param-util-generated.h.pump +++ b/testing/gtest/include/gtest/internal/gtest-param-util-generated.h.pump @@ -48,8 +48,8 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. -#include <gtest/internal/gtest-param-util.h> -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-port.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/include/gtest/internal/gtest-param-util.h b/testing/gtest/include/gtest/internal/gtest-param-util.h index 98bcca7..d923b7d 100644 --- a/testing/gtest/include/gtest/internal/gtest-param-util.h +++ b/testing/gtest/include/gtest/internal/gtest-param-util.h @@ -41,10 +41,10 @@ // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. -#include <gtest/internal/gtest-internal.h> -#include <gtest/internal/gtest-linked_ptr.h> -#include <gtest/internal/gtest-port.h> -#include <gtest/gtest-printers.h> +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-linked_ptr.h" +#include "gtest/internal/gtest-port.h" +#include "gtest/gtest-printers.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/include/gtest/internal/gtest-port.h b/testing/gtest/include/gtest/internal/gtest-port.h index f2c80f3..a9c7cae 100644 --- a/testing/gtest/include/gtest/internal/gtest-port.h +++ b/testing/gtest/include/gtest/internal/gtest-port.h @@ -50,6 +50,8 @@ // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::wstring, which is different to std::wstring). +// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular +// expressions are/aren't available. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h> // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't @@ -62,6 +64,10 @@ // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // compiler supports Microsoft's "Structured // Exception Handling". +// GTEST_HAS_STREAM_REDIRECTION +// - Define it to 1/0 to indicate whether the +// platform supports I/O stream redirection using +// dup() and dup2(). // GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google // Test's own tr1 tuple implementation should be // used. Unused when the user sets @@ -107,7 +113,9 @@ // GTEST_HAS_PARAM_TEST - value-parameterized tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests -// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. +// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with +// GTEST_HAS_POSIX_RE (see above) which users can +// define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above two are mutually exclusive. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). @@ -135,8 +143,9 @@ // // Regular expressions: // RE - a simple regular expression class using the POSIX -// Extended Regular Expression syntax. Not available on -// Windows. +// Extended Regular Expression syntax on UNIX-like +// platforms, or a reduced regular exception syntax on +// other platforms, including Windows. // // Logging: // GTEST_LOG_() - logs messages at the specified severity level. @@ -169,11 +178,13 @@ // Int32FromGTestEnv() - parses an Int32 environment variable. // StringFromGTestEnv() - parses a string environment variable. -#include <stddef.h> // For ptrdiff_t +#include <ctype.h> // for isspace, etc +#include <stddef.h> // for ptrdiff_t #include <stdlib.h> #include <stdio.h> #include <string.h> #ifndef _WIN32_WCE +#include <sys/types.h> #include <sys/stat.h> #endif // !_WIN32_WCE @@ -221,28 +232,37 @@ #define GTEST_OS_AIX 1 #endif // __CYGWIN__ -#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_SYMBIAN || \ - GTEST_OS_SOLARIS || GTEST_OS_AIX +// Brings in definitions for functions used in the testing::internal::posix +// namespace (read, write, close, chdir, isatty, stat). We do not currently +// use them on Windows Mobile. +#if !GTEST_OS_WINDOWS +// This assumes that non-Windows OSes provide unistd.h. For OSes where this +// is not the case, we need to include headers that provide the functions +// mentioned above. +#include <unistd.h> +#include <strings.h> +#elif !GTEST_OS_WINDOWS_MOBILE +#include <direct.h> +#include <io.h> +#endif + +// Defines this to true iff Google Test can use POSIX regular expressions. +#ifndef GTEST_HAS_POSIX_RE +#define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) +#endif + +#if GTEST_HAS_POSIX_RE // On some platforms, <regex.h> needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already // included <stdlib.h>, which is guaranteed to define size_t through // <stddef.h>. #include <regex.h> // NOLINT -#include <strings.h> // NOLINT -#include <sys/types.h> // NOLINT -#include <time.h> // NOLINT -#include <unistd.h> // NOLINT #define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS -#if !GTEST_OS_WINDOWS_MOBILE -#include <direct.h> // NOLINT -#include <io.h> // NOLINT -#endif - // <regex.h> is not available on Windows. Use our own simple regex // implementation instead. #define GTEST_USES_SIMPLE_RE 1 @@ -253,8 +273,7 @@ // simple regex implementation instead. #define GTEST_USES_SIMPLE_RE 1 -#endif // GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC || - // GTEST_OS_SYMBIAN || GTEST_OS_SOLARIS || GTEST_OS_AIX +#endif // GTEST_HAS_POSIX_RE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need @@ -308,8 +327,7 @@ // TODO(wan@google.com): uses autoconf to detect whether ::std::wstring // is available. -// Cygwin 1.5 and below doesn't support ::std::wstring. -// Cygwin 1.7 might add wstring support; this should be updated when clear. +// Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. #define GTEST_HAS_STD_WSTRING (!(GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) @@ -379,6 +397,15 @@ #define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC) #endif // GTEST_HAS_PTHREAD +#if GTEST_HAS_PTHREAD +// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is +// true. +#include <pthread.h> // NOLINT + +// For timespec and nanosleep, used below. +#include <time.h> // NOLINT +#endif + // Determines whether Google Test can use tr1/tuple. You can define // this macro to 0 to prevent Google Test from using tuple (any // feature depending on tuple with be disabled in this mode). @@ -414,7 +441,7 @@ #if GTEST_HAS_TR1_TUPLE #if GTEST_USE_OWN_TR1_TUPLE -#include <gtest/internal/gtest-tuple.h> +#include "gtest/internal/gtest-tuple.h" #elif GTEST_OS_SYMBIAN // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to @@ -474,9 +501,15 @@ // Determines whether to support stream redirection. This is used to test // output correctness and to implement death tests. -#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN -#define GTEST_HAS_STREAM_REDIRECTION_ 1 +#ifndef GTEST_HAS_STREAM_REDIRECTION +// By default, we assume that stream redirection is supported on all +// platforms except known mobile ones. +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN +#define GTEST_HAS_STREAM_REDIRECTION 0 +#else +#define GTEST_HAS_STREAM_REDIRECTION 1 #endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN +#endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // Google Test does not support death tests for VC 7.1 and earlier as @@ -516,6 +549,11 @@ #define GTEST_WIDE_STRING_USES_UTF16_ \ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) +// Determines whether test results can be streamed to a socket. +#if GTEST_OS_LINUX +#define GTEST_CAN_STREAM_RESULTS_ 1 +#endif + // Defines some utility macros. // The GNU compiler emits a warning if nested "if" statements are followed by @@ -529,7 +567,7 @@ #ifdef __INTEL_COMPILER #define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else -#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: // NOLINT +#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to @@ -694,8 +732,6 @@ typedef ::wstring wstring; typedef ::std::wstring wstring; #endif // GTEST_HAS_GLOBAL_WSTRING -typedef ::std::stringstream StrStream; - // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); @@ -942,7 +978,7 @@ Derived* CheckedDowncastToActualType(Base* base) { #endif } -#if GTEST_HAS_STREAM_REDIRECTION_ +#if GTEST_HAS_STREAM_REDIRECTION // Defines the stderr capturer: // CaptureStdout - starts capturing stdout. @@ -955,7 +991,7 @@ GTEST_API_ String GetCapturedStdout(); GTEST_API_ void CaptureStderr(); GTEST_API_ String GetCapturedStderr(); -#endif // GTEST_HAS_STREAM_REDIRECTION_ +#endif // GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_DEATH_TEST @@ -1089,10 +1125,6 @@ class ThreadWithParam : public ThreadWithParamBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; -// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is -// true. -#include <pthread.h> - // MutexBase and Mutex implement mutex on pthreads-based platforms. They // are used in conjunction with class MutexLock: // @@ -1397,6 +1429,39 @@ typedef __int64 BiggestInt; typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS +// Utilities for char. + +// isspace(int ch) and friends accept an unsigned char or EOF. char +// may be signed, depending on the compiler (or compiler flags). +// Therefore we need to cast a char to unsigned char before calling +// isspace(), etc. + +inline bool IsAlpha(char ch) { + return isalpha(static_cast<unsigned char>(ch)) != 0; +} +inline bool IsAlNum(char ch) { + return isalnum(static_cast<unsigned char>(ch)) != 0; +} +inline bool IsDigit(char ch) { + return isdigit(static_cast<unsigned char>(ch)) != 0; +} +inline bool IsLower(char ch) { + return islower(static_cast<unsigned char>(ch)) != 0; +} +inline bool IsSpace(char ch) { + return isspace(static_cast<unsigned char>(ch)) != 0; +} +inline bool IsUpper(char ch) { + return isupper(static_cast<unsigned char>(ch)) != 0; +} + +inline char ToLower(char ch) { + return static_cast<char>(tolower(static_cast<unsigned char>(ch))); +} +inline char ToUpper(char ch) { + return static_cast<char>(toupper(static_cast<unsigned char>(ch))); +} + // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these diff --git a/testing/gtest/include/gtest/internal/gtest-string.h b/testing/gtest/include/gtest/internal/gtest-string.h index aff093d..8cbb797 100644 --- a/testing/gtest/include/gtest/internal/gtest-string.h +++ b/testing/gtest/include/gtest/internal/gtest-string.h @@ -47,7 +47,7 @@ #endif #include <string.h> -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" #include <string> @@ -329,9 +329,9 @@ inline ::std::ostream& operator<<(::std::ostream& os, const String& str) { return os; } -// Gets the content of the StrStream's buffer as a String. Each '\0' +// Gets the content of the stringstream's buffer as a String. Each '\0' // character in the buffer is replaced with "\\0". -GTEST_API_ String StrStreamToString(StrStream* stream); +GTEST_API_ 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, diff --git a/testing/gtest/include/gtest/internal/gtest-type-util.h b/testing/gtest/include/gtest/internal/gtest-type-util.h index 093eee6..7a98646 100644 --- a/testing/gtest/include/gtest/internal/gtest-type-util.h +++ b/testing/gtest/include/gtest/internal/gtest-type-util.h @@ -44,8 +44,8 @@ #ifndef 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-string.h> +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-string.h" #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P diff --git a/testing/gtest/include/gtest/internal/gtest-type-util.h.pump b/testing/gtest/include/gtest/internal/gtest-type-util.h.pump index 5aed1e5..04906b7 100644 --- a/testing/gtest/include/gtest/internal/gtest-type-util.h.pump +++ b/testing/gtest/include/gtest/internal/gtest-type-util.h.pump @@ -42,8 +42,8 @@ $var n = 50 $$ Maximum length of type lists we want to support. #ifndef 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-string.h> +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-string.h" #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P diff --git a/testing/gtest/msvc/gtest-md.vcproj b/testing/gtest/msvc/gtest-md.vcproj index c78a4a4..1c35c3a 100644 --- a/testing/gtest/msvc/gtest-md.vcproj +++ b/testing/gtest/msvc/gtest-md.vcproj @@ -100,82 +100,7 @@ Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
- RelativePath="..\src\gtest-death-test.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-filepath.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-port.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-test-part.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-typed-test.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest.cc">
+ RelativePath="..\src\gtest-all.cc">
<FileConfiguration
Name="Debug|Win32">
<Tool
@@ -194,42 +119,6 @@ Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
- <File
- RelativePath="..\include\gtest\internal\gtest-death-test-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-death-test.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-filepath.h">
- </File>
- <File
- RelativePath="..\src\gtest-internal-inl.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-message.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-port.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-spi.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-string.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_pred_impl.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_prod.h">
- </File>
</Filter>
</Files>
<Globals>
diff --git a/testing/gtest/msvc/gtest.vcproj b/testing/gtest/msvc/gtest.vcproj index bd2ed81..a8373ce 100644 --- a/testing/gtest/msvc/gtest.vcproj +++ b/testing/gtest/msvc/gtest.vcproj @@ -100,82 +100,7 @@ Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
- RelativePath="..\src\gtest-death-test.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-filepath.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-test-part.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-port.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest-typed-test.cc">
- <FileConfiguration
- Name="Debug|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32">
- <Tool
- Name="VCCLCompilerTool"
- AdditionalIncludeDirectories=""..";"..\include""/>
- </FileConfiguration>
- </File>
- <File
- RelativePath="..\src\gtest.cc">
+ RelativePath="..\src\gtest-all.cc">
<FileConfiguration
Name="Debug|Win32">
<Tool
@@ -194,42 +119,6 @@ Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
- <File
- RelativePath="..\include\gtest\internal\gtest-death-test-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-death-test.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-filepath.h">
- </File>
- <File
- RelativePath="..\src\gtest-internal-inl.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-message.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-port.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-spi.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-string.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_pred_impl.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_prod.h">
- </File>
</Filter>
</Files>
<Globals>
diff --git a/testing/gtest/msvc/gtest_main-md.vcproj b/testing/gtest/msvc/gtest_main-md.vcproj index 321667f..b5379fe 100644 --- a/testing/gtest/msvc/gtest_main-md.vcproj +++ b/testing/gtest/msvc/gtest_main-md.vcproj @@ -122,42 +122,6 @@ Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
- <File
- RelativePath="..\include\gtest\internal\gtest-death-test-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-death-test.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-filepath.h">
- </File>
- <File
- RelativePath="..\src\gtest-internal-inl.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-message.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-port.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-spi.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-string.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_pred_impl.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_prod.h">
- </File>
</Filter>
</Files>
<Globals>
diff --git a/testing/gtest/msvc/gtest_main.vcproj b/testing/gtest/msvc/gtest_main.vcproj index 13cc1d4..e8b763c 100644 --- a/testing/gtest/msvc/gtest_main.vcproj +++ b/testing/gtest/msvc/gtest_main.vcproj @@ -122,42 +122,6 @@ Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
- <File
- RelativePath="..\include\gtest\internal\gtest-death-test-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-death-test.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-filepath.h">
- </File>
- <File
- RelativePath="..\src\gtest-internal-inl.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-internal.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-message.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-port.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest-spi.h">
- </File>
- <File
- RelativePath="..\include\gtest\internal\gtest-string.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_pred_impl.h">
- </File>
- <File
- RelativePath="..\include\gtest\gtest_prod.h">
- </File>
</Filter>
</Files>
<Globals>
diff --git a/testing/gtest/run_tests.py b/testing/gtest/run_tests.py deleted file mode 100755 index e108405..0000000 --- a/testing/gtest/run_tests.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008, Google Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Runs the specified tests for Google Test. - -This script requires Python 2.3 or higher. To learn the usage, run it -with -h. -""" - -import os -import sys - -SCRIPT_DIR = os.path.dirname(__file__) or '.' - -sys.path.append(os.path.join(SCRIPT_DIR, 'test')) -import run_tests_util - - -def _Main(): - """Runs all tests for Google Test.""" - - options, args = run_tests_util.ParseArgs('gtest') - test_runner = run_tests_util.TestRunner(script_dir=SCRIPT_DIR) - tests = test_runner.GetTestsToRun(args, - options.configurations, - options.built_configurations) - if not tests: - sys.exit(1) # Incorrect parameters given, abort execution. - - sys.exit(test_runner.RunTests(tests[0], tests[1])) - -if __name__ == '__main__': - _Main() diff --git a/testing/gtest/samples/sample10_unittest.cc b/testing/gtest/samples/sample10_unittest.cc index 3ad6fd6..2813d04 100644 --- a/testing/gtest/samples/sample10_unittest.cc +++ b/testing/gtest/samples/sample10_unittest.cc @@ -34,7 +34,7 @@ #include <stdio.h> #include <stdlib.h> -#include <gtest/gtest.h> +#include "gtest/gtest.h" using ::testing::EmptyTestEventListener; using ::testing::InitGoogleTest; diff --git a/testing/gtest/samples/sample1_unittest.cc b/testing/gtest/samples/sample1_unittest.cc index 01eb546..a8a7c79 100644 --- a/testing/gtest/samples/sample1_unittest.cc +++ b/testing/gtest/samples/sample1_unittest.cc @@ -45,7 +45,7 @@ #include <limits.h> #include "sample1.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" // Step 2. Use the TEST macro to define your tests. diff --git a/testing/gtest/samples/sample2_unittest.cc b/testing/gtest/samples/sample2_unittest.cc index 32232d9..3792fa5 100644 --- a/testing/gtest/samples/sample2_unittest.cc +++ b/testing/gtest/samples/sample2_unittest.cc @@ -41,7 +41,7 @@ // needed. #include "sample2.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" // In this example, we test the MyString class (a simple string). diff --git a/testing/gtest/samples/sample3_unittest.cc b/testing/gtest/samples/sample3_unittest.cc index 34c1ca8..bf3877d 100644 --- a/testing/gtest/samples/sample3_unittest.cc +++ b/testing/gtest/samples/sample3_unittest.cc @@ -64,7 +64,7 @@ // </TechnicalDetails> #include "sample3-inl.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" // To use a test fixture, derive a class from testing::Test. class QueueTest : public testing::Test { diff --git a/testing/gtest/samples/sample4_unittest.cc b/testing/gtest/samples/sample4_unittest.cc index b4fb373..fa5afc7 100644 --- a/testing/gtest/samples/sample4_unittest.cc +++ b/testing/gtest/samples/sample4_unittest.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include "sample4.h" // Tests the Increment() method. diff --git a/testing/gtest/samples/sample5_unittest.cc b/testing/gtest/samples/sample5_unittest.cc index 49dae7c..e7cab01 100644 --- a/testing/gtest/samples/sample5_unittest.cc +++ b/testing/gtest/samples/sample5_unittest.cc @@ -47,7 +47,7 @@ #include <limits.h> #include <time.h> #include "sample3-inl.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include "sample1.h" // In this sample, we want to ensure that every test finishes within diff --git a/testing/gtest/samples/sample6_unittest.cc b/testing/gtest/samples/sample6_unittest.cc index dd0df31..8f2036a 100644 --- a/testing/gtest/samples/sample6_unittest.cc +++ b/testing/gtest/samples/sample6_unittest.cc @@ -35,7 +35,7 @@ // The interface and its implementations are in this header. #include "prime_tables.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" // First, we define some factory functions for creating instances of // the implementations. You may be able to skip this step if all your diff --git a/testing/gtest/samples/sample7_unittest.cc b/testing/gtest/samples/sample7_unittest.cc index f455282..441acf9 100644 --- a/testing/gtest/samples/sample7_unittest.cc +++ b/testing/gtest/samples/sample7_unittest.cc @@ -38,7 +38,7 @@ // The interface and its implementations are in this header. #include "prime_tables.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/samples/sample8_unittest.cc b/testing/gtest/samples/sample8_unittest.cc index ccf61d9..5ad2e2c 100644 --- a/testing/gtest/samples/sample8_unittest.cc +++ b/testing/gtest/samples/sample8_unittest.cc @@ -36,7 +36,7 @@ // Use class definitions to test from this header. #include "prime_tables.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_HAS_COMBINE diff --git a/testing/gtest/samples/sample9_unittest.cc b/testing/gtest/samples/sample9_unittest.cc index d828ef4..b2e2079 100644 --- a/testing/gtest/samples/sample9_unittest.cc +++ b/testing/gtest/samples/sample9_unittest.cc @@ -34,7 +34,7 @@ #include <stdio.h> -#include <gtest/gtest.h> +#include "gtest/gtest.h" using ::testing::EmptyTestEventListener; using ::testing::InitGoogleTest; @@ -69,7 +69,7 @@ class TersePrinter : public EmptyTestEventListener { fflush(stdout); } - // Called after a failed assertion or a SUCCESS(). + // Called after a failed assertion or a SUCCEED() invocation. virtual void OnTestPartResult(const TestPartResult& test_part_result) { fprintf(stdout, "%s in %s:%d\n%s\n", diff --git a/testing/gtest/scripts/fuse_gtest_files.py b/testing/gtest/scripts/fuse_gtest_files.py index 148444c..57ef72f 100755 --- a/testing/gtest/scripts/fuse_gtest_files.py +++ b/testing/gtest/scripts/fuse_gtest_files.py @@ -67,8 +67,8 @@ import sys # Test root directory. DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') -# Regex for matching '#include <gtest/...>'. -INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*<(gtest/.+)>') +# Regex for matching '#include "gtest/..."'. +INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"') # Regex for matching '#include "src/..."'. INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"') @@ -162,7 +162,7 @@ def FuseGTestH(gtest_root, output_dir): for line in file(os.path.join(gtest_root, gtest_header_path), 'r'): m = INCLUDE_GTEST_FILE_REGEX.match(line) if m: - # It's '#include <gtest/...>' - let's process it recursively. + # It's '#include "gtest/..."' - let's process it recursively. ProcessFile('include/' + m.group(1)) else: # Otherwise we copy the line unchanged to the output file. @@ -191,19 +191,19 @@ def FuseGTestAllCcToFile(gtest_root, output_file): m = INCLUDE_GTEST_FILE_REGEX.match(line) if m: if 'include/' + m.group(1) == GTEST_SPI_H_SEED: - # It's '#include <gtest/gtest-spi.h>'. This file is not - # #included by <gtest/gtest.h>, so we need to process it. + # It's '#include "gtest/gtest-spi.h"'. This file is not + # #included by "gtest/gtest.h", so we need to process it. ProcessFile(GTEST_SPI_H_SEED) else: - # It's '#include <gtest/foo.h>' where foo is not gtest-spi. - # We treat it as '#include <gtest/gtest.h>', as all other + # It's '#include "gtest/foo.h"' where foo is not gtest-spi. + # We treat it as '#include "gtest/gtest.h"', as all other # gtest headers are being fused into gtest.h and cannot be # #included directly. - # There is no need to #include <gtest/gtest.h> more than once. + # There is no need to #include "gtest/gtest.h" more than once. if not GTEST_H_SEED in processed_files: processed_files.add(GTEST_H_SEED) - output_file.write('#include <%s>\n' % (GTEST_H_OUTPUT,)) + output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,)) else: m = INCLUDE_SRC_FILE_REGEX.match(line) if m: diff --git a/testing/gtest/scripts/gen_gtest_pred_impl.py b/testing/gtest/scripts/gen_gtest_pred_impl.py index 8307134..d35b4f0 100755 --- a/testing/gtest/scripts/gen_gtest_pred_impl.py +++ b/testing/gtest/scripts/gen_gtest_pred_impl.py @@ -238,21 +238,19 @@ AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS impl += """) { if (pred(%(vs)s)) return AssertionSuccess(); - Message msg; """ % DEFS - impl += ' msg << pred_text << "("' + impl += ' return AssertionFailure() << pred_text << "("' impl += Iter(n, """ - << e%s""", sep=' << ", "') + << e%s""", sep=' << ", "') impl += ' << ") evaluates to false, where"' impl += Iter(n, """ - << "\\n" << e%s << " evaluates to " << v%s""") + << "\\n" << e%s << " evaluates to " << v%s""") impl += """; - return AssertionFailure(msg); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s. @@ -386,8 +384,8 @@ def UnitTestPreamble(): #include <iostream> -#include <gtest/gtest.h> -#include <gtest/gtest-spi.h> +#include "gtest/gtest.h" +#include "gtest/gtest-spi.h" // A user-defined data type. struct Bool { @@ -478,15 +476,14 @@ testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS if (PredFunction%(n)s(%(vs)s)) return testing::AssertionSuccess(); - testing::Message msg; - msg << """ % DEFS + return testing::AssertionFailure() + << """ % DEFS tests += Iter(n, 'e%s', sep=' << " + " << ') tests += """ << " is expected to be positive, but evaluates to " << %(v_sum)s << "."; - return testing::AssertionFailure(msg); } """ % DEFS diff --git a/testing/gtest/src/gtest-all.cc b/testing/gtest/src/gtest-all.cc index f3e22dd..0a9cee5 100644 --- a/testing/gtest/src/gtest-all.cc +++ b/testing/gtest/src/gtest-all.cc @@ -36,7 +36,7 @@ // This line ensures that gtest.h can be compiled on its own, even // when it's fused. -#include <gtest/gtest.h> +#include "gtest/gtest.h" // The following lines pull in the real gtest *.cc files. #include "src/gtest.cc" diff --git a/testing/gtest/src/gtest-death-test.cc b/testing/gtest/src/gtest-death-test.cc index 66bf189..e11f504 100644 --- a/testing/gtest/src/gtest-death-test.cc +++ b/testing/gtest/src/gtest-death-test.cc @@ -31,8 +31,8 @@ // // This file implements death tests. -#include <gtest/gtest-death-test.h> -#include <gtest/internal/gtest-port.h> +#include "gtest/gtest-death-test.h" +#include "gtest/internal/gtest-port.h" #if GTEST_HAS_DEATH_TEST @@ -54,8 +54,8 @@ #endif // GTEST_HAS_DEATH_TEST -#include <gtest/gtest-message.h> -#include <gtest/internal/gtest-string.h> +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-string.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is @@ -526,11 +526,11 @@ bool DeathTestImpl::Passed(bool status_ok) { // class WindowsDeathTest : public DeathTestImpl { public: - WindowsDeathTest(const char* statement, - const RE* regex, + WindowsDeathTest(const char* a_statement, + const RE* a_regex, const char* file, int line) - : DeathTestImpl(statement, regex), file_(file), line_(line) {} + : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} // All of these virtual functions are inherited from DeathTest. virtual int Wait(); @@ -587,12 +587,12 @@ int WindowsDeathTest::Wait() { GTEST_DEATH_TEST_CHECK_( WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), INFINITE)); - DWORD status; - GTEST_DEATH_TEST_CHECK_(::GetExitCodeProcess(child_handle_.Get(), &status) - != FALSE); + DWORD status_code; + GTEST_DEATH_TEST_CHECK_( + ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); child_handle_.Reset(); - set_status(static_cast<int>(status)); - return this->status(); + set_status(static_cast<int>(status_code)); + return status(); } // The AssumeRole process for a Windows death test. It creates a child diff --git a/testing/gtest/src/gtest-filepath.cc b/testing/gtest/src/gtest-filepath.cc index c1ef918..96557f3 100644 --- a/testing/gtest/src/gtest-filepath.cc +++ b/testing/gtest/src/gtest-filepath.cc @@ -29,8 +29,8 @@ // // Authors: keith.ray@gmail.com (Keith Ray) -#include <gtest/internal/gtest-filepath.h> -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-filepath.h" +#include "gtest/internal/gtest-port.h" #include <stdlib.h> @@ -57,7 +57,7 @@ #define GTEST_PATH_MAX_ _POSIX_PATH_MAX #endif // GTEST_OS_WINDOWS -#include <gtest/internal/gtest-string.h> +#include "gtest/internal/gtest-string.h" namespace testing { namespace internal { diff --git a/testing/gtest/src/gtest-internal-inl.h b/testing/gtest/src/gtest-internal-inl.h index 9e63aed..e0f4af5 100644 --- a/testing/gtest/src/gtest-internal-inl.h +++ b/testing/gtest/src/gtest-internal-inl.h @@ -56,14 +56,14 @@ #include <string> #include <vector> -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" #if GTEST_OS_WINDOWS #include <windows.h> // For DWORD. #endif // GTEST_OS_WINDOWS -#include <gtest/gtest.h> // NOLINT -#include <gtest/gtest-spi.h> +#include "gtest/gtest.h" // NOLINT +#include "gtest/gtest-spi.h" namespace testing { @@ -93,6 +93,7 @@ const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; +const char kStreamResultToFlag[] = "stream_result_to"; const char kThrowOnFailureFlag[] = "throw_on_failure"; // A valid random seed must be in [1, kMaxRandomSeed]. @@ -165,6 +166,7 @@ class GTestFlagSaver { repeat_ = GTEST_FLAG(repeat); shuffle_ = GTEST_FLAG(shuffle); stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); + stream_result_to_ = GTEST_FLAG(stream_result_to); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } @@ -185,6 +187,7 @@ class GTestFlagSaver { GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; + GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } private: @@ -205,6 +208,7 @@ class GTestFlagSaver { internal::Int32 repeat_; bool shuffle_; internal::Int32 stack_trace_depth_; + String stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; @@ -340,85 +344,6 @@ class TestPropertyKeyIs { String key_; }; -class TestInfoImpl { - public: - TestInfoImpl(TestInfo* parent, const char* test_case_name, - const char* name, const char* test_case_comment, - const char* comment, TypeId fixture_class_id, - internal::TestFactoryBase* factory); - ~TestInfoImpl(); - - // Returns true if this test should run. - bool should_run() const { return should_run_; } - - // Sets the should_run member. - void set_should_run(bool should) { should_run_ = should; } - - // Returns true if this test is disabled. Disabled tests are not run. - bool is_disabled() const { return is_disabled_; } - - // Sets the is_disabled member. - void set_is_disabled(bool is) { is_disabled_ = is; } - - // Returns true if this test matches the filter specified by the user. - bool matches_filter() const { return matches_filter_; } - - // Sets the matches_filter member. - void set_matches_filter(bool matches) { matches_filter_ = matches; } - - // Returns the test case name. - const char* test_case_name() const { return test_case_name_.c_str(); } - - // Returns the test name. - const char* name() const { return name_.c_str(); } - - // Returns the test case comment. - const char* test_case_comment() const { return test_case_comment_.c_str(); } - - // Returns the test comment. - const char* comment() const { return comment_.c_str(); } - - // Returns the ID of the test fixture class. - TypeId fixture_class_id() const { return fixture_class_id_; } - - // Returns the test result. - TestResult* result() { return &result_; } - const TestResult* result() const { return &result_; } - - // Creates the test object, runs it, records its result, and then - // deletes it. - void Run(); - - // Clears the test result. - void ClearResult() { result_.Clear(); } - - // Clears the test result in the given TestInfo object. - static void ClearTestResult(TestInfo * test_info) { - test_info->impl()->ClearResult(); - } - - private: - // These fields are immutable properties of the test. - TestInfo* const parent_; // The owner of this object - const String test_case_name_; // Test case name - const String name_; // Test name - const String test_case_comment_; // Test case comment - const String comment_; // Test comment - const TypeId fixture_class_id_; // ID of the test fixture class - bool should_run_; // True iff this test should run - bool is_disabled_; // True iff this test is disabled - bool matches_filter_; // True if this test matches the - // user-specified filter. - internal::TestFactoryBase* const factory_; // The factory that creates - // the test object - - // This field is mutable and needs to be reset before running the - // test for the second time. - TestResult result_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl); -}; - // Class UnitTestOptions. // // This class contains functions for processing options the user @@ -747,16 +672,18 @@ class GTEST_API_ UnitTestImpl { void RegisterParameterizedTests(); // Runs all tests in this UnitTest object, prints the result, and - // returns 0 if all tests are successful, or 1 otherwise. If any - // exception is thrown during a test on Windows, this test is - // considered to be failed, but the rest of the tests will still be - // run. (We disable exceptions on Linux and Mac OS X, so the issue - // doesn't apply there.) - int RunAllTests(); - - // Clears the results of all tests, including the ad hoc test. - void ClearResult() { + // returns true if all tests are successful. If any exception is + // thrown during a test, this test is considered to be failed, but + // the rest of the tests will still be run. + bool RunAllTests(); + + // Clears the results of all tests, except the ad hoc tests. + void ClearNonAdHocTestResult() { ForEach(test_cases_, TestCase::ClearTestCaseResult); + } + + // Clears the results of ad-hoc test assertions. + void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } @@ -818,6 +745,12 @@ class GTEST_API_ UnitTestImpl { // UnitTestOptions. Must not be called before InitGoogleTest. void ConfigureXmlOutput(); +#if GTEST_CAN_STREAM_RESULTS_ + // Initializes the event listener for streaming test results to a socket. + // Must not be called before InitGoogleTest. + void ConfigureStreamingOutput(); +#endif + // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest @@ -838,9 +771,17 @@ class GTEST_API_ UnitTestImpl { // Restores the test cases and tests to their order before the first shuffle. void UnshuffleTests(); + // Returns the value of GTEST_FLAG(catch_exceptions) at the moment + // UnitTest::Run() starts. + bool catch_exceptions() const { return catch_exceptions_; } + private: friend class ::testing::UnitTest; + // Used by UnitTest::Run() to capture the state of + // GTEST_FLAG(catch_exceptions) at the moment it starts. + void set_catch_exceptions(bool value) { catch_exceptions_ = value; } + // The UnitTest object that owns this implementation object. UnitTest* const parent_; @@ -943,6 +884,10 @@ class GTEST_API_ UnitTestImpl { // A per-thread stack of traces created by the SCOPED_TRACE() macro. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; + // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() + // starts. + bool catch_exceptions_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); }; // class UnitTestImpl @@ -952,14 +897,16 @@ inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } +#if GTEST_USES_SIMPLE_RE + // Internal helper functions for implementing the simple regular // expression matcher. GTEST_API_ bool IsInSet(char ch, const char* str); -GTEST_API_ bool IsDigit(char ch); -GTEST_API_ bool IsPunct(char ch); +GTEST_API_ bool IsAsciiDigit(char ch); +GTEST_API_ bool IsAsciiPunct(char ch); GTEST_API_ bool IsRepeat(char ch); -GTEST_API_ bool IsWhiteSpace(char ch); -GTEST_API_ bool IsWordChar(char ch); +GTEST_API_ bool IsAsciiWhiteSpace(char ch); +GTEST_API_ bool IsAsciiWordChar(char ch); GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); @@ -968,6 +915,8 @@ GTEST_API_ bool MatchRepetitionAndRegexAtHead( bool escaped, char ch, char repeat, const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); +#endif // GTEST_USES_SIMPLE_RE + // Parses the command line for Google Test flags, without initializing // other parts of Google Test. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); @@ -1014,7 +963,7 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // Fail fast if the given string does not begin with a digit; // this bypasses strtoXXX's "optional leading whitespace and plus // or minus sign" semantics, which are undesirable here. - if (str.empty() || !isdigit(str[0])) { + if (str.empty() || !IsDigit(str[0])) { return false; } errno = 0; diff --git a/testing/gtest/src/gtest-port.cc b/testing/gtest/src/gtest-port.cc index b9504f5..ae0c663 100644 --- a/testing/gtest/src/gtest-port.cc +++ b/testing/gtest/src/gtest-port.cc @@ -29,11 +29,12 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" #include <limits.h> #include <stdlib.h> #include <stdio.h> +#include <string.h> #if GTEST_OS_WINDOWS_MOBILE #include <windows.h> // For TerminateProcess() @@ -50,9 +51,9 @@ #include <mach/vm_map.h> #endif // GTEST_OS_MAC -#include <gtest/gtest-spi.h> -#include <gtest/gtest-message.h> -#include <gtest/internal/gtest-string.h> +#include "gtest/gtest-spi.h" +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-string.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is @@ -180,20 +181,20 @@ bool IsInSet(char ch, const char* str) { // Returns true iff ch belongs to the given classification. Unlike // similar functions in <ctype.h>, these aren't affected by the // current locale. -bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; } -bool IsPunct(char ch) { +bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } +bool IsAsciiPunct(char ch) { return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); } bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } -bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } -bool IsWordChar(char ch) { +bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } +bool IsAsciiWordChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true iff "\\c" is a supported escape sequence. bool IsValidEscape(char c) { - return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW")); + return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } // Returns true iff the given atom (specified by escaped and pattern) @@ -201,19 +202,19 @@ bool IsValidEscape(char c) { bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { - case 'd': return IsDigit(ch); - case 'D': return !IsDigit(ch); + case 'd': return IsAsciiDigit(ch); + case 'D': return !IsAsciiDigit(ch); case 'f': return ch == '\f'; case 'n': return ch == '\n'; case 'r': return ch == '\r'; - case 's': return IsWhiteSpace(ch); - case 'S': return !IsWhiteSpace(ch); + case 's': return IsAsciiWhiteSpace(ch); + case 'S': return !IsAsciiWhiteSpace(ch); case 't': return ch == '\t'; case 'v': return ch == '\v'; - case 'w': return IsWordChar(ch); - case 'W': return !IsWordChar(ch); + case 'w': return IsAsciiWordChar(ch); + case 'W': return !IsAsciiWordChar(ch); } - return IsPunct(pattern_char) && pattern_char == ch; + return IsAsciiPunct(pattern_char) && pattern_char == ch; } return (pattern_char == '.' && ch != '\n') || pattern_char == ch; @@ -448,7 +449,7 @@ GTestLog::~GTestLog() { #pragma warning(disable: 4996) #endif // _MSC_VER -#if GTEST_HAS_STREAM_REDIRECTION_ +#if GTEST_HAS_STREAM_REDIRECTION // Object that captures an output stream (stdout/stderr). class CapturedStream { @@ -588,7 +589,7 @@ String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } // Stops capturing stderr and returns the captured string. String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } -#endif // GTEST_HAS_STREAM_REDIRECTION_ +#endif // GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_DEATH_TEST @@ -618,7 +619,7 @@ static String FlagToEnvVar(const char* flag) { Message env_var; for (size_t i = 0; i != full_flag.length(); i++) { - env_var << static_cast<char>(toupper(full_flag.c_str()[i])); + env_var << ToUpper(full_flag.c_str()[i]); } return env_var.GetString(); diff --git a/testing/gtest/src/gtest-printers.cc b/testing/gtest/src/gtest-printers.cc index 611180e..147f8b2 100644 --- a/testing/gtest/src/gtest-printers.cc +++ b/testing/gtest/src/gtest-printers.cc @@ -42,12 +42,12 @@ // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that // defines Foo. -#include <gtest/gtest-printers.h> +#include "gtest/gtest-printers.h" #include <ctype.h> #include <stdio.h> #include <ostream> // NOLINT #include <string> -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" namespace testing { @@ -72,9 +72,10 @@ void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, if (i != 0) { // Organizes the bytes into groups of 2 for easy parsing by // human. - if ((j % 2) == 0) { - *os << " "; - } + if ((j % 2) == 0) + *os << ' '; + else + *os << '-'; } snprintf(text, sizeof(text), "%02X", obj_bytes[j]); *os << text; @@ -123,10 +124,31 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, namespace internal { -// Prints a wide char as a char literal without the quotes, escaping it -// when necessary. -static void PrintAsWideCharLiteralTo(wchar_t c, ostream* os) { - switch (c) { +// Depending on the value of a char (or wchar_t), we print it in one +// of three formats: +// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), +// - as a hexidecimal escape sequence (e.g. '\x7F'), or +// - as a special escape sequence (e.g. '\r', '\n'). +enum CharFormat { + kAsIs, + kHexEscape, + kSpecialEscape +}; + +// Returns true if c is a printable ASCII character. We test the +// value of c directly instead of calling isprint(), which is buggy on +// Windows Mobile. +static inline bool IsPrintableAscii(wchar_t c) { + return 0x20 <= c && c <= 0x7E; +} + +// Prints a wide or narrow char c as a character literal without the +// quotes, escaping it when necessary; returns how c was formatted. +// The template argument UnsignedChar is the unsigned version of Char, +// which is the type of c. +template <typename UnsignedChar, typename Char> +static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { + switch (static_cast<wchar_t>(c)) { case L'\0': *os << "\\0"; break; @@ -161,19 +183,15 @@ static void PrintAsWideCharLiteralTo(wchar_t c, ostream* os) { *os << "\\v"; break; default: - // Checks whether c is printable or not. Printable characters are in - // the range [0x20,0x7E]. - // We test the value of c directly instead of calling isprint(), as - // isprint() is buggy on Windows mobile. - if (0x20 <= c && c <= 0x7E) { + if (IsPrintableAscii(c)) { *os << static_cast<char>(c); + return kAsIs; } else { - // Buffer size enough for the maximum number of digits and \0. - char text[2 * sizeof(unsigned long) + 1] = ""; - snprintf(text, sizeof(text), "%lX", static_cast<unsigned long>(c)); - *os << "\\x" << text; + *os << String::Format("\\x%X", static_cast<UnsignedChar>(c)); + return kHexEscape; } } + return kSpecialEscape; } // Prints a char as if it's part of a string literal, escaping it when @@ -187,50 +205,57 @@ static void PrintAsWideStringLiteralTo(wchar_t c, ostream* os) { *os << "\\\""; break; default: - PrintAsWideCharLiteralTo(c, os); + PrintAsCharLiteralTo<wchar_t>(c, os); } } -// Prints a char as a char literal without the quotes, escaping it -// when necessary. -static void PrintAsCharLiteralTo(char c, ostream* os) { - PrintAsWideCharLiteralTo(static_cast<unsigned char>(c), os); -} - // Prints a char as if it's part of a string literal, escaping it when // necessary. -static void PrintAsStringLiteralTo(char c, ostream* os) { +static void PrintAsNarrowStringLiteralTo(char c, ostream* os) { PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os); } -// Prints a char and its code. The '\0' char is printed as "'\\0'", -// other unprintable characters are also properly escaped using the -// standard C++ escape sequence. -void PrintCharTo(char c, int char_code, ostream* os) { +// Prints a wide or narrow character c and its code. '\0' is printed +// as "'\\0'", other unprintable characters are also properly escaped +// using the standard C++ escape sequence. The template argument +// UnsignedChar is the unsigned version of Char, which is the type of c. +template <typename UnsignedChar, typename Char> +void PrintCharAndCodeTo(Char c, ostream* os) { + // First, print c as a literal in the most readable form we can find. + *os << ((sizeof(c) > 1) ? "L'" : "'"); + const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os); *os << "'"; - PrintAsCharLiteralTo(c, os); - *os << "'"; - if (c != '\0') - *os << " (" << char_code << ")"; + + // To aid user debugging, we also print c's code in decimal, unless + // it's 0 (in which case c was printed as '\\0', making the code + // obvious). + if (c == 0) + return; + *os << " (" << String::Format("%d", c).c_str(); + + // 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 + // [1, 9]. + if (format == kHexEscape || (1 <= c && c <= 9)) { + // Do nothing. + } else { + *os << String::Format(", 0x%X", + static_cast<UnsignedChar>(c)).c_str(); + } + *os << ")"; +} + +void PrintTo(unsigned char c, ::std::ostream* os) { + PrintCharAndCodeTo<unsigned char>(c, os); +} +void PrintTo(signed char c, ::std::ostream* os) { + PrintCharAndCodeTo<unsigned char>(c, os); } // Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its decimal code (except for L'\0'). -// The L'\0' char is printed as "L'\\0'". The decimal code is printed -// as signed integer when wchar_t is implemented by the compiler -// as a signed type and is printed as an unsigned integer when wchar_t -// is implemented as an unsigned type. +// code otherwise and also as its code. L'\0' is printed as "L'\\0'". void PrintTo(wchar_t wc, ostream* os) { - *os << "L'"; - PrintAsWideCharLiteralTo(wc, os); - *os << "'"; - if (wc != L'\0') { - // Type Int64 is used because it provides more storage than wchar_t thus - // when the compiler converts signed or unsigned implementation of wchar_t - // to Int64 it fills higher bits with either zeros or the sign bit - // passing it to operator <<() as either signed or unsigned integer. - *os << " (" << static_cast<Int64>(wc) << ")"; - } + PrintCharAndCodeTo<wchar_t>(wc, os); } // Prints the given array of characters to the ostream. @@ -239,7 +264,7 @@ void PrintTo(wchar_t wc, ostream* os) { static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) { *os << "\""; for (size_t index = 0; index < len; ++index) { - PrintAsStringLiteralTo(begin[index], os); + PrintAsNarrowStringLiteralTo(begin[index], os); } *os << "\""; } diff --git a/testing/gtest/src/gtest-test-part.cc b/testing/gtest/src/gtest-test-part.cc index 5d183a4..5ddc67c 100644 --- a/testing/gtest/src/gtest-test-part.cc +++ b/testing/gtest/src/gtest-test-part.cc @@ -31,7 +31,7 @@ // // The Google C++ Testing Framework (Google Test) -#include <gtest/gtest-test-part.h> +#include "gtest/gtest-test-part.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is diff --git a/testing/gtest/src/gtest-typed-test.cc b/testing/gtest/src/gtest-typed-test.cc index 3cc4b5d..a5cc88f 100644 --- a/testing/gtest/src/gtest-typed-test.cc +++ b/testing/gtest/src/gtest-typed-test.cc @@ -29,8 +29,8 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/gtest-typed-test.h> -#include <gtest/gtest.h> +#include "gtest/gtest-typed-test.h" +#include "gtest/gtest.h" namespace testing { namespace internal { @@ -40,7 +40,7 @@ namespace internal { // Skips to the first non-space char in str. Returns an empty string if str // contains only whitespace characters. static const char* SkipSpaces(const char* str) { - while (isspace(*str)) + while (IsSpace(*str)) str++; return str; } diff --git a/testing/gtest/src/gtest.cc b/testing/gtest/src/gtest.cc index e136a18..0d41e46 100644 --- a/testing/gtest/src/gtest.cc +++ b/testing/gtest/src/gtest.cc @@ -31,8 +31,8 @@ // // The Google C++ Testing Framework (Google Test) -#include <gtest/gtest.h> -#include <gtest/gtest-spi.h> +#include "gtest/gtest.h" +#include "gtest/gtest-spi.h" #include <ctype.h> #include <math.h> @@ -43,7 +43,7 @@ #include <wctype.h> #include <algorithm> -#include <ostream> +#include <ostream> // NOLINT #include <sstream> #include <vector> @@ -53,16 +53,15 @@ // gettimeofday(). #define GTEST_HAS_GETTIMEOFDAY_ 1 -#include <fcntl.h> -#include <limits.h> -#include <sched.h> +#include <fcntl.h> // NOLINT +#include <limits.h> // NOLINT +#include <sched.h> // NOLINT // Declares vsnprintf(). This header is not available on Windows. -#include <strings.h> -#include <sys/mman.h> -#include <sys/time.h> -#include <unistd.h> +#include <strings.h> // NOLINT +#include <sys/mman.h> // NOLINT +#include <sys/time.h> // NOLINT +#include <unistd.h> // NOLINT #include <string> -#include <vector> #elif GTEST_OS_SYMBIAN #define GTEST_HAS_GETTIMEOFDAY_ 1 @@ -119,6 +118,11 @@ #include <stdexcept> #endif +#if GTEST_CAN_STREAM_RESULTS_ +#include <arpa/inet.h> // NOLINT +#include <netdb.h> // NOLINT +#endif + // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to @@ -258,6 +262,13 @@ GTEST_DEFINE_int32_( "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); +GTEST_DEFINE_string_( + stream_result_to, + internal::StringFromGTestEnv("stream_result_to", ""), + "This flag specifies the host name and the port number on which to stream " + "test results. Example: \"localhost:555\". The flag is effective only on " + "Linux."); + GTEST_DEFINE_bool_( throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false), @@ -490,20 +501,33 @@ bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, !MatchesFilter(full_name, negative.c_str())); } -#if GTEST_OS_WINDOWS +#if GTEST_HAS_SEH // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { - // Google Test should handle an exception if: + // Google Test should handle a SEH exception if: // 1. the user wants it to, AND - // 2. this is not a breakpoint exception. - return (GTEST_FLAG(catch_exceptions) && - exception_code != EXCEPTION_BREAKPOINT) ? - EXCEPTION_EXECUTE_HANDLER : - EXCEPTION_CONTINUE_SEARCH; + // 2. this is not a breakpoint exception, AND + // 3. this is not a C++ exception (VC++ implements them via SEH, + // apparently). + // + // SEH exception code for C++ exceptions. + // (see http://support.microsoft.com/kb/185294 for more information). + const DWORD kCxxExceptionCode = 0xe06d7363; + + bool should_handle = true; + + if (!GTEST_FLAG(catch_exceptions)) + should_handle = false; + else if (exception_code == EXCEPTION_BREAKPOINT) + should_handle = false; + else if (exception_code == kCxxExceptionCode) + should_handle = false; + + return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; } -#endif // GTEST_OS_WINDOWS +#endif // GTEST_HAS_SEH } // namespace internal @@ -583,7 +607,7 @@ AssertionResult HasOneFailure(const char* /* results_expr */, const char* /* substr_expr */, const TestPartResultArray& results, TestPartResult::Type type, - const char* substr) { + const string& substr) { const String expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); @@ -594,23 +618,21 @@ AssertionResult HasOneFailure(const char* /* results_expr */, for (int i = 0; i < results.size(); i++) { msg << "\n" << results.GetTestPartResult(i); } - return AssertionFailure(msg); + return AssertionFailure() << msg; } const TestPartResult& r = results.GetTestPartResult(0); if (r.type() != type) { - msg << "Expected: " << expected << "\n" - << " Actual:\n" - << r; - return AssertionFailure(msg); + return AssertionFailure() << "Expected: " << expected << "\n" + << " Actual:\n" + << r; } - if (strstr(r.message(), substr) == NULL) { - msg << "Expected: " << expected << " containing \"" - << substr << "\"\n" - << " Actual:\n" - << r; - return AssertionFailure(msg); + if (strstr(r.message(), substr.c_str()) == NULL) { + return AssertionFailure() << "Expected: " << expected << " containing \"" + << substr << "\"\n" + << " Actual:\n" + << r; } return AssertionSuccess(); @@ -622,7 +644,7 @@ AssertionResult HasOneFailure(const char* /* results_expr */, SingleFailureChecker:: SingleFailureChecker( const TestPartResultArray* results, TestPartResult::Type type, - const char* substr) + const string& substr) : results_(results), type_(type), substr_(substr) {} @@ -632,7 +654,7 @@ SingleFailureChecker:: SingleFailureChecker( // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. SingleFailureChecker::~SingleFailureChecker() { - EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str()); + EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( @@ -918,48 +940,6 @@ Message& Message::operator <<(const ::wstring& wstr) { } #endif // GTEST_HAS_GLOBAL_WSTRING -namespace internal { - -// Formats a value to be used in a failure message. - -// For a char value, we print it as a C++ char literal and as an -// unsigned integer (both in decimal and in hexadecimal). -String FormatForFailureMessage(char ch) { - const unsigned int ch_as_uint = ch; - // A String object cannot contain '\0', so we print "\\0" when ch is - // '\0'. - return String::Format("'%s' (%u, 0x%X)", - ch ? String::Format("%c", ch).c_str() : "\\0", - ch_as_uint, ch_as_uint); -} - -// For a wchar_t value, we print it as a C++ wchar_t literal and as an -// unsigned integer (both in decimal and in hexidecimal). -String FormatForFailureMessage(wchar_t wchar) { - // The C++ standard doesn't specify the exact size of the wchar_t - // type. It just says that it shall have the same size as another - // integral type, called its underlying type. - // - // Therefore, in order to print a wchar_t value in the numeric form, - // we first convert it to the largest integral type (UInt64) and - // then print the converted value. - // - // We use streaming to print the value as "%llu" doesn't work - // correctly with MSVC 7.1. - const UInt64 wchar_as_uint64 = wchar; - Message msg; - // A String object cannot contain '\0', so we print "\\0" when wchar is - // L'\0'. - char buffer[32]; // CodePointToUtf8 requires a buffer that big. - msg << "L'" - << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0") - << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16) - << wchar_as_uint64 << ")"; - return msg.GetString(); -} - -} // namespace internal - // AssertionResult constructors. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) @@ -1029,7 +1009,7 @@ AssertionResult EqFailure(const char* expected_expression, msg << "\nWhich is: " << expected_value; } - return AssertionFailure(msg); + return AssertionFailure() << msg; } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. @@ -1059,13 +1039,12 @@ AssertionResult DoubleNearPredFormat(const char* expr1, // TODO(wan): do not print the value of an expression if it's // already a literal. - Message msg; - msg << "The difference between " << expr1 << " and " << expr2 + return AssertionFailure() + << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << expr1 << " evaluates to " << val1 << ",\n" << expr2 << " evaluates to " << val2 << ", and\n" << abs_error_expr << " evaluates to " << abs_error << "."; - return AssertionFailure(msg); } @@ -1090,20 +1069,18 @@ AssertionResult FloatingPointLE(const char* expr1, // val2 is NaN, as the IEEE floating-point standard requires that // any predicate involving a NaN must return false. - StrStream val1_ss; + ::std::stringstream val1_ss; val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val1; - StrStream val2_ss; + ::std::stringstream val2_ss; val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val2; - Message msg; - msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" - << " Actual: " << StrStreamToString(&val1_ss) << " vs " - << StrStreamToString(&val2_ss); - - return AssertionFailure(msg); + return AssertionFailure() + << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" + << " Actual: " << StringStreamToString(&val1_ss) << " vs " + << StringStreamToString(&val2_ss); } } // namespace internal @@ -1150,11 +1127,10 @@ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ - Message msg;\ - msg << "Expected: (" << expr1 << ") " #op " (" << expr2\ + return AssertionFailure() \ + << "Expected: (" << expr1 << ") " #op " (" << expr2\ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ << " vs " << FormatForComparisonFailureMessage(val2, val1);\ - return AssertionFailure(msg);\ }\ } @@ -1216,11 +1192,9 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { - Message msg; - msg << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; - return AssertionFailure(msg); + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: \"" + << s1 << "\" vs \"" << s2 << "\""; } } @@ -1232,11 +1206,10 @@ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { - Message msg; - msg << "Expected: (" << s1_expression << ") != (" + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" << s2_expression << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; - return AssertionFailure(msg); } } @@ -1285,13 +1258,12 @@ AssertionResult IsSubstringImpl( const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; - return AssertionFailure( - Message() + return AssertionFailure() << "Value of: " << needle_expr << "\n" << " Actual: " << begin_string_quote << needle << "\"\n" << "Expected: " << (expected_to_be_substring ? "" : "not ") << "a substring of " << haystack_expr << "\n" - << "Which is: " << begin_string_quote << haystack << "\""); + << "Which is: " << begin_string_quote << haystack << "\""; } } // namespace @@ -1380,18 +1352,16 @@ AssertionResult HRESULTFailureHelper(const char* expr, kBufSize, // buf size NULL); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing cr-lf) - for (; message_length && isspace(error_text[message_length - 1]); + for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } #endif // GTEST_OS_WINDOWS_MOBILE const String error_hex(String::Format("0x%08X ", hr)); - Message msg; - msg << "Expected: " << expr << " " << expected << ".\n" + return ::testing::AssertionFailure() + << "Expected: " << expr << " " << expected << ".\n" << " Actual: " << error_hex << error_text << "\n"; - - return ::testing::AssertionFailure(msg); } } // namespace @@ -1526,7 +1496,7 @@ String WideStringToUtf8(const wchar_t* str, int num_chars) { if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); - StrStream stream; + ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { UInt32 unicode_code_point; @@ -1543,7 +1513,7 @@ String WideStringToUtf8(const wchar_t* str, int num_chars) { char buffer[32]; // CodePointToUtf8 requires a buffer this big. stream << CodePointToUtf8(unicode_code_point, buffer); } - return StrStreamToString(&stream); + return StringStreamToString(&stream); } // Converts a wide C string to a String using the UTF-8 encoding. @@ -1602,12 +1572,10 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, return AssertionSuccess(); } - Message msg; - msg << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: " - << String::ShowWideCStringQuoted(s1) - << " vs " << String::ShowWideCStringQuoted(s2); - return AssertionFailure(msg); + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: " + << String::ShowWideCStringQuoted(s1) + << " vs " << String::ShowWideCStringQuoted(s2); } // Compares two C strings, ignoring case. Returns true iff they have @@ -1638,9 +1606,9 @@ bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { // current locale. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { - if ( lhs == NULL ) return rhs == NULL; + if (lhs == NULL) return rhs == NULL; - if ( rhs == NULL ) return false; + if (rhs == NULL) return false; #if GTEST_OS_WINDOWS return _wcsicmp(lhs, rhs) == 0; @@ -1751,16 +1719,16 @@ String String::Format(const char * format, ...) { } } -// Converts the buffer in a StrStream to a String, converting NUL +// Converts the buffer in a stringstream to a String, converting NUL // bytes to "\\0" along the way. -String StrStreamToString(StrStream* ss) { +String StringStreamToString(::std::stringstream* ss) { const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); - // We need to use a helper StrStream to do this transformation + // We need to use a helper stringstream to do this transformation // because String doesn't support push_back(). - StrStream helper; + ::std::stringstream helper; for (const char* ch = start; ch != end; ++ch) { if (*ch == '\0') { helper << "\\0"; // Replaces NUL with "\\0"; @@ -1964,22 +1932,6 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type, } // namespace internal -#if GTEST_OS_WINDOWS -// We are on Windows. - -// Adds an "exception thrown" fatal failure to the current test. -static void AddExceptionThrownFailure(DWORD exception_code, - const char* location) { - Message message; - message << "Exception thrown with code 0x" << std::setbase(16) << - exception_code << std::setbase(10) << " in " << location << "."; - - internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, - message.GetString()); -} - -#endif // GTEST_OS_WINDOWS - // Google Test requires all tests in the same test case to use the same test // fixture class. This function checks if the current test has the // same fixture class as the first test in the current test case. If @@ -1990,15 +1942,13 @@ bool Test::HasSameFixtureClass() { const TestCase* const test_case = impl->current_test_case(); // Info about the first test in the current test case. - const internal::TestInfoImpl* const first_test_info = - test_case->test_info_list()[0]->impl(); - const internal::TypeId first_fixture_id = first_test_info->fixture_class_id(); + const TestInfo* const first_test_info = test_case->test_info_list()[0]; + const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; const char* const first_test_name = first_test_info->name(); // Info about the current test. - const internal::TestInfoImpl* const this_test_info = - impl->current_test_info()->impl(); - const internal::TypeId this_fixture_id = this_test_info->fixture_class_id(); + const TestInfo* const this_test_info = impl->current_test_info(); + const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; const char* const this_test_name = this_test_info->name(); if (this_fixture_id != first_fixture_id) { @@ -2048,62 +1998,161 @@ bool Test::HasSameFixtureClass() { return true; } -// Runs the test and updates the test result. -void Test::Run() { - if (!HasSameFixtureClass()) return; +#if GTEST_HAS_SEH - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); +// Adds an "exception thrown" fatal failure to the current test. This +// function returns its result via an output parameter pointer because VC++ +// prohibits creation of objects with destructors on stack in functions +// using __try (see error C2712). +static internal::String* FormatSehExceptionMessage(DWORD exception_code, + const char* location) { + Message message; + message << "SEH exception with code 0x" << std::setbase(16) << + exception_code << std::setbase(10) << " thrown in " << location << "."; + + return new internal::String(message.GetString()); +} + +#endif // GTEST_HAS_SEH + +#if GTEST_HAS_EXCEPTIONS + +// Adds an "exception thrown" fatal failure to the current test. +static internal::String FormatCxxExceptionMessage(const char* description, + const char* location) { + Message message; + if (description != NULL) { + message << "C++ exception with description \"" << description << "\""; + } else { + message << "Unknown C++ exception"; + } + message << " thrown in " << location << "."; + + return message.GetString(); +} + +static internal::String PrintTestPartResultToString( + const TestPartResult& test_part_result); + +// A failed Google Test assertion will throw an exception of this type 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 GoogleTestFailureException : public ::std::runtime_error { + public: + explicit GoogleTestFailureException(const TestPartResult& failure) + : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} +}; +#endif // GTEST_HAS_EXCEPTIONS + +// Runs the given method and handles SEH exceptions it throws, when +// SEH is supported; returns the 0-value for type Result in case of an +// SEH exception. (Microsoft compilers cannot handle SEH and C++ +// exceptions in the same function. Therefore, we provide a separate +// wrapper function for handling SEH exceptions.) +template <class T, typename Result> +static Result HandleSehExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { #if GTEST_HAS_SEH - // Catch SEH-style exceptions. - impl->os_stack_trace_getter()->UponLeavingGTest(); __try { - SetUp(); - } __except(internal::UnitTestOptions::GTestShouldProcessSEH( + return (object->*method)(); + } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT GetExceptionCode())) { - AddExceptionThrownFailure(GetExceptionCode(), "SetUp()"); + // We create the exception message on the heap because VC++ prohibits + // creation of objects with destructors on stack in functions using __try + // (see error C2712). + internal::String* exception_message = FormatSehExceptionMessage( + GetExceptionCode(), location); + internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, + *exception_message); + delete exception_message; + return static_cast<Result>(0); } +#else + (void)location; + return (object->*method)(); +#endif // GTEST_HAS_SEH +} - // We will run the test only if SetUp() had no fatal failure. - if (!HasFatalFailure()) { - impl->os_stack_trace_getter()->UponLeavingGTest(); - __try { - TestBody(); - } __except(internal::UnitTestOptions::GTestShouldProcessSEH( - GetExceptionCode())) { - AddExceptionThrownFailure(GetExceptionCode(), "the test body"); +// Runs the given method and catches and reports C++ and/or SEH-style +// exceptions, if they are supported; returns the 0-value for type +// Result in case of an SEH exception. +template <class T, typename Result> +static Result HandleExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { + // NOTE: The user code can affect the way in which Google Test handles + // exceptions by setting GTEST_FLAG(catch_exceptions), but only before + // RUN_ALL_TESTS() starts. It is technically possible to check the flag + // after the exception is caught and either report or re-throw the + // exception based on the flag's value: + // + // try { + // // Perform the test method. + // } catch (...) { + // if (GTEST_FLAG(catch_exceptions)) + // // Report the exception as failure. + // else + // throw; // Re-throws the original exception. + // } + // + // However, the purpose of this flag is to allow the program to drop into + // the debugger when the exception is thrown. On most platforms, once the + // control enters the catch block, the exception origin information is + // lost and the debugger will stop the program at the point of the + // re-throw in this function -- instead of at the point of the original + // throw statement in the code under test. For this reason, we perform + // the check early, sacrificing the ability to affect Google Test's + // exception handling in the method where the exception is thrown. + if (internal::GetUnitTestImpl()->catch_exceptions()) { +#if GTEST_HAS_EXCEPTIONS + try { + return HandleSehExceptionsInMethodIfSupported(object, method, location); + } catch (const GoogleTestFailureException&) { // NOLINT + // This exception doesn't originate in code under test. It makes no + // sense to report it as a test failure. + throw; + } catch (const std::exception& e) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(e.what(), location)); + } catch (...) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(NULL, location)); } + return static_cast<Result>(0); +#else + return HandleSehExceptionsInMethodIfSupported(object, method, location); +#endif // GTEST_HAS_EXCEPTIONS + } else { + return (object->*method)(); } +} - // However, we want to clean up as much as possible. Hence we will - // always call TearDown(), even if SetUp() or the test body has - // failed. - impl->os_stack_trace_getter()->UponLeavingGTest(); - __try { - TearDown(); - } __except(internal::UnitTestOptions::GTestShouldProcessSEH( - GetExceptionCode())) { - AddExceptionThrownFailure(GetExceptionCode(), "TearDown()"); - } +// Runs the test and updates the test result. +void Test::Run() { + if (!HasSameFixtureClass()) return; -#else // We are on a compiler or platform that doesn't support SEH. + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->os_stack_trace_getter()->UponLeavingGTest(); - SetUp(); - + HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); // We will run the test only if SetUp() was successful. if (!HasFatalFailure()) { impl->os_stack_trace_getter()->UponLeavingGTest(); - TestBody(); + HandleExceptionsInMethodIfSupported( + this, &Test::TestBody, "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); - TearDown(); -#endif // GTEST_HAS_SEH + HandleExceptionsInMethodIfSupported( + this, &Test::TearDown, "TearDown()"); } - // Returns true iff the current test has a fatal failure. bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); @@ -2118,22 +2167,26 @@ bool Test::HasNonfatalFailure() { // class TestInfo // Constructs a TestInfo object. It assumes ownership of the test factory -// object via impl_. +// object. TestInfo::TestInfo(const char* a_test_case_name, const char* a_name, const char* a_test_case_comment, const char* a_comment, internal::TypeId fixture_class_id, - internal::TestFactoryBase* factory) { - impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name, - a_test_case_comment, a_comment, - fixture_class_id, factory); -} + internal::TestFactoryBase* factory) + : test_case_name_(a_test_case_name), + name_(a_name), + test_case_comment_(a_test_case_comment), + comment_(a_comment), + fixture_class_id_(fixture_class_id), + should_run_(false), + is_disabled_(false), + matches_filter_(false), + factory_(factory), + result_() {} // Destructs a TestInfo object. -TestInfo::~TestInfo() { - delete impl_; -} +TestInfo::~TestInfo() { delete factory_; } namespace internal { @@ -2189,41 +2242,6 @@ void ReportInvalidTestCaseType(const char* test_case_name, } // namespace internal -// Returns the test case name. -const char* TestInfo::test_case_name() const { - return impl_->test_case_name(); -} - -// Returns the test name. -const char* TestInfo::name() const { - return impl_->name(); -} - -// Returns the test case comment. -const char* TestInfo::test_case_comment() const { - return impl_->test_case_comment(); -} - -// Returns the test comment. -const char* TestInfo::comment() const { - return impl_->comment(); -} - -// Returns true if this test should run. -bool TestInfo::should_run() const { return impl_->should_run(); } - -// Returns true if this test matches the user-specified filter. -bool TestInfo::matches_filter() const { return impl_->matches_filter(); } - -// Returns the result of the test. -const TestResult* TestInfo::result() const { return impl_->result(); } - -// Increments the number of death tests encountered in this test so -// far. -int TestInfo::increment_death_test_count() { - return impl_->result()->increment_death_test_count(); -} - namespace { // A predicate that checks the test name of a TestInfo against a known @@ -2267,70 +2285,54 @@ void UnitTestImpl::RegisterParameterizedTests() { #endif } +} // namespace internal + // Creates the test object, runs it, records its result, and then // deletes it. -void TestInfoImpl::Run() { +void TestInfo::Run() { if (!should_run_) return; // Tells UnitTest where to store test result. - UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_info(parent_); + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); // Notifies the unit test event listeners that a test is about to start. - repeater->OnTestStart(*parent_); + repeater->OnTestStart(*this); - const TimeInMillis start = GetTimeInMillis(); + const TimeInMillis start = internal::GetTimeInMillis(); impl->os_stack_trace_getter()->UponLeavingGTest(); -#if GTEST_HAS_SEH - // Catch SEH-style exceptions. - Test* test = NULL; - - __try { - // Creates the test object. - test = factory_->CreateTest(); - } __except(internal::UnitTestOptions::GTestShouldProcessSEH( - GetExceptionCode())) { - AddExceptionThrownFailure(GetExceptionCode(), - "the test fixture's constructor"); - return; - } -#else // We are on a compiler or platform that doesn't support SEH. - - // TODO(wan): If test->Run() throws, test won't be deleted. This is - // not a problem now as we don't use exceptions. If we were to - // enable exceptions, we should revise the following to be - // exception-safe. // Creates the test object. - Test* test = factory_->CreateTest(); -#endif // GTEST_HAS_SEH - - // Runs the test only if the constructor of the test fixture didn't - // generate a fatal failure. - if (!Test::HasFatalFailure()) { + Test* const test = HandleExceptionsInMethodIfSupported( + factory_, &internal::TestFactoryBase::CreateTest, + "the test fixture's constructor"); + + // Runs the test only if the test object was created and its + // constructor didn't generate a fatal failure. + if ((test != NULL) && !Test::HasFatalFailure()) { + // This doesn't throw as all user code that can throw are wrapped into + // exception handling code. test->Run(); } // Deletes the test object. impl->os_stack_trace_getter()->UponLeavingGTest(); - delete test; - test = NULL; + HandleExceptionsInMethodIfSupported( + test, &Test::DeleteSelf_, "the test fixture's destructor"); - result_.set_elapsed_time(GetTimeInMillis() - start); + result_.set_elapsed_time(internal::GetTimeInMillis() - start); // Notifies the unit test event listener that a test has just finished. - repeater->OnTestEnd(*parent_); + repeater->OnTestEnd(*this); // Tells UnitTest to stop associating assertion results to this // test. impl->set_current_test_info(NULL); } -} // namespace internal - // class TestCase // Gets the number of successful tests in this test case. @@ -2413,45 +2415,26 @@ void TestCase::Run() { repeater->OnTestCaseStart(*this); impl->os_stack_trace_getter()->UponLeavingGTest(); - set_up_tc_(); + HandleExceptionsInMethodIfSupported( + this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); const internal::TimeInMillis start = internal::GetTimeInMillis(); for (int i = 0; i < total_test_count(); i++) { - GetMutableTestInfo(i)->impl()->Run(); + GetMutableTestInfo(i)->Run(); } elapsed_time_ = internal::GetTimeInMillis() - start; impl->os_stack_trace_getter()->UponLeavingGTest(); - tear_down_tc_(); + HandleExceptionsInMethodIfSupported( + this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); + repeater->OnTestCaseEnd(*this); impl->set_current_test_case(NULL); } // Clears the results of all tests in this test case. void TestCase::ClearResult() { - ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult); -} - -// Returns true iff test passed. -bool TestCase::TestPassed(const TestInfo * test_info) { - const internal::TestInfoImpl* const impl = test_info->impl(); - return impl->should_run() && impl->result()->Passed(); -} - -// Returns true iff test failed. -bool TestCase::TestFailed(const TestInfo * test_info) { - const internal::TestInfoImpl* const impl = test_info->impl(); - return impl->should_run() && impl->result()->Failed(); -} - -// Returns true iff test is disabled. -bool TestCase::TestDisabled(const TestInfo * test_info) { - return test_info->impl()->is_disabled(); -} - -// Returns true if the given test should run. -bool TestCase::ShouldRunTest(const TestInfo *test_info) { - return test_info->impl()->should_run(); + ForEach(test_info_list_, TestInfo::ClearTestResult); } // Shuffles the tests in this test case. @@ -2504,9 +2487,9 @@ static const char * TestPartResultTypeToString(TestPartResult::Type type) { #else return "Failure\n"; #endif + default: + return "Unknown result type"; } - - return "Unknown result type"; } // Prints a TestPartResult to a String. @@ -2841,8 +2824,8 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { } } - void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { +void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, + int /*iteration*/) { ColoredPrintf(COLOR_GREEN, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), @@ -3265,9 +3248,9 @@ void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, "errors=\"0\" time=\"%s\">\n", FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str()); for (int i = 0; i < test_case.total_test_count(); ++i) { - StrStream stream; + ::std::stringstream stream; OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i)); - fprintf(out, "%s", StrStreamToString(&stream).c_str()); + fprintf(out, "%s", StringStreamToString(&stream).c_str()); } fprintf(out, " </testsuite>\n"); } @@ -3307,6 +3290,182 @@ String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( // End XmlUnitTestResultPrinter +#if GTEST_CAN_STREAM_RESULTS_ + +// Streams test results to the given port on the given host machine. +class StreamingListener : public EmptyTestEventListener { + public: + // Escapes '=', '&', '%', and '\n' characters in str as "%xx". + static string UrlEncode(const char* str); + + StreamingListener(const string& host, const string& port) + : sockfd_(-1), host_name_(host), port_num_(port) { + MakeConnection(); + Send("gtest_streaming_protocol_version=1.0\n"); + } + + virtual ~StreamingListener() { + if (sockfd_ != -1) + CloseConnection(); + } + + void OnTestProgramStart(const UnitTest& /* unit_test */) { + Send("event=TestProgramStart\n"); + } + + 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. + Send(String::Format("event=TestProgramEnd&passed=%d\n", + unit_test.Passed())); + + // Notify the streaming server to stop. + CloseConnection(); + } + + void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { + Send(String::Format("event=TestIterationStart&iteration=%d\n", + iteration)); + } + + void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { + Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n", + unit_test.Passed(), + StreamableToString(unit_test.elapsed_time()).c_str())); + } + + void OnTestCaseStart(const TestCase& test_case) { + Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name())); + } + + void OnTestCaseEnd(const TestCase& test_case) { + Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n", + test_case.Passed(), + StreamableToString(test_case.elapsed_time()).c_str())); + } + + void OnTestStart(const TestInfo& test_info) { + Send(String::Format("event=TestStart&name=%s\n", test_info.name())); + } + + void OnTestEnd(const TestInfo& test_info) { + Send(String::Format( + "event=TestEnd&passed=%d&elapsed_time=%sms\n", + (test_info.result())->Passed(), + StreamableToString((test_info.result())->elapsed_time()).c_str())); + } + + void OnTestPartResult(const TestPartResult& test_part_result) { + const char* file_name = test_part_result.file_name(); + if (file_name == NULL) + file_name = ""; + Send(String::Format("event=TestPartResult&file=%s&line=%d&message=", + UrlEncode(file_name).c_str(), + test_part_result.line_number())); + Send(UrlEncode(test_part_result.message()) + "\n"); + } + + 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; + } + + // Sends a string to the socket. + 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_; + } + } + + int sockfd_; // socket file descriptor + const string host_name_; + const string port_num_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); +}; // class StreamingListener + +// Checks if str contains '=', '&', '%' or '\n' characters. If yes, +// replaces them by "%xx" where xx is their hexadecimal value. For +// example, replaces "=" with "%3D". This algorithm is O(strlen(str)) +// in both time and space -- important as the input str may contain an +// arbitrarily long test failure message and stack trace. +string StreamingListener::UrlEncode(const char* str) { + string result; + result.reserve(strlen(str) + 1); + for (char ch = *str; ch != '\0'; ch = *++str) { + switch (ch) { + case '%': + case '=': + case '&': + case '\n': + result.append(String::Format("%%%02x", static_cast<unsigned char>(ch))); + break; + default: + result.push_back(ch); + break; + } + } + return result; +} + +void StreamingListener::MakeConnection() { + GTEST_CHECK_(sockfd_ == -1) + << "MakeConnection() can't be called when there is already a connection."; + + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. + hints.ai_socktype = SOCK_STREAM; + addrinfo* servinfo = NULL; + + // Use the getaddrinfo() to get a linked list of IP addresses for + // the given host name. + const int error_num = getaddrinfo( + host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); + if (error_num != 0) { + GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " + << gai_strerror(error_num); + } + + // Loop through all the results and connect to the first we can. + for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; + cur_addr = cur_addr->ai_next) { + sockfd_ = socket( + cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); + if (sockfd_ != -1) { + // Connect the client socket to the server socket. + if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { + close(sockfd_); + sockfd_ = -1; + } + } + } + + freeaddrinfo(servinfo); // all done with this structure + + if (sockfd_ == -1) { + GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " + << host_name_ << ":" << port_num_; + } +} + +// End of class Streaming Listener +#endif // GTEST_CAN_STREAM_RESULTS__ + // Class ScopedTrace // Pushes the given source file location and message onto a per-thread @@ -3547,19 +3706,6 @@ Environment* UnitTest::AddEnvironment(Environment* env) { return env; } -#if GTEST_HAS_EXCEPTIONS -// A failed Google Test assertion will throw an exception of this type -// when 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 GoogleTestFailureException : public ::std::runtime_error { - public: - explicit GoogleTestFailureException(const TestPartResult& failure) - : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} -}; -#endif - // Adds a TestPartResult to the current TestResult object. All Google Test // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the @@ -3608,7 +3754,11 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, // the --gtest_catch_exceptions flags are specified. DebugBreak(); #else - *static_cast<int*>(NULL) = 1; + // Dereference NULL through a volatile pointer to prevent the compiler + // from removing. We use this rather than abort() or __builtin_trap() for + // portability: Symbian doesn't implement abort() well, and some debuggers + // don't correctly trap abort(). + *static_cast<volatile int*>(NULL) = 1; #endif // GTEST_OS_WINDOWS } else if (GTEST_FLAG(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS @@ -3636,17 +3786,19 @@ void UnitTest::RecordPropertyForCurrentTest(const char* key, // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { -#if GTEST_HAS_SEH - // Catch SEH-style exceptions. + // Captures the value of GTEST_FLAG(catch_exceptions). This value will be + // used for the duration of the program. + impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); +#if GTEST_HAS_SEH const bool in_death_test_child_process = internal::GTEST_FLAG(internal_run_death_test).length() > 0; // Either the user wants Google Test to catch exceptions thrown by the // tests or this is executing in the context of death test child // process. In either case the user does not want to see pop-up dialogs - // about crashes - they are expected.. - if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) { + // about crashes - they are expected. + if (impl()->catch_exceptions() || in_death_test_child_process) { #if !GTEST_OS_WINDOWS_MOBILE // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | @@ -3678,20 +3830,12 @@ int UnitTest::Run() { _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. #endif } - - __try { - return impl_->RunAllTests(); - } __except(internal::UnitTestOptions::GTestShouldProcessSEH( - GetExceptionCode())) { - printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode()); - fflush(stdout); - return 1; - } - -#else // We are on a compiler or platform that doesn't support SEH. - - return impl_->RunAllTests(); #endif // GTEST_HAS_SEH + + return HandleExceptionsInMethodIfSupported( + impl(), + &internal::UnitTestImpl::RunAllTests, + "auxiliary test code (environments or event listeners)") ? 0 : 1; } // Returns the working directory when the first TEST() or TEST_F() was @@ -3785,13 +3929,13 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent) post_flag_parse_init_performed_(false), random_seed_(0), // Will be overridden by the flag before first use. random_(0), // Will be reseeded before first use. -#if GTEST_HAS_DEATH_TEST elapsed_time_(0), +#if GTEST_HAS_DEATH_TEST internal_run_death_test_flag_(NULL), - death_test_factory_(new DefaultDeathTestFactory) { -#else - elapsed_time_(0) { -#endif // GTEST_HAS_DEATH_TEST + death_test_factory_(new DefaultDeathTestFactory), +#endif + // Will be overridden by the flag before first use. + catch_exceptions_(false) { listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); } @@ -3828,6 +3972,25 @@ void UnitTestImpl::ConfigureXmlOutput() { } } +#if GTEST_CAN_STREAM_RESULTS_ +// Initializes event listeners for streaming test results in String form. +// Must not be called before InitGoogleTest. +void UnitTestImpl::ConfigureStreamingOutput() { + const string& target = GTEST_FLAG(stream_result_to); + if (!target.empty()) { + const size_t pos = target.find(':'); + if (pos != string::npos) { + listeners()->Append(new StreamingListener(target.substr(0, pos), + target.substr(pos+1))); + } else { + printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", + target.c_str()); + fflush(stdout); + } + } +} +#endif // GTEST_CAN_STREAM_RESULTS_ + // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest @@ -3851,6 +4014,11 @@ void UnitTestImpl::PostFlagParsingInit() { // Configures listeners for XML output. This makes it possible for users // to shut down the default XML output before invoking RUN_ALL_TESTS. ConfigureXmlOutput(); + +#if GTEST_CAN_STREAM_RESULTS_ + // Configures listeners for streaming test results to the specified server. + ConfigureStreamingOutput(); +#endif // GTEST_CAN_STREAM_RESULTS_ } } @@ -3928,27 +4096,26 @@ static void SetUpEnvironment(Environment* env) { env->SetUp(); } static void TearDownEnvironment(Environment* env) { env->TearDown(); } // Runs all tests in this UnitTest object, prints the result, and -// returns 0 if all tests are successful, or 1 otherwise. If any -// exception is thrown during a test on Windows, this test is -// considered to be failed, but the rest of the tests will still be -// run. (We disable exceptions on Linux and Mac OS X, so the issue -// doesn't apply there.) +// returns true if all tests are successful. If any exception is +// thrown during a test, the test is considered to be failed, but the +// rest of the tests will still be run. +// // When parameterized tests are enabled, it expands and registers // parameterized tests first in RegisterParameterizedTests(). // All other functions called from RunAllTests() may safely assume that // parameterized tests are ready to be counted and run. -int UnitTestImpl::RunAllTests() { +bool UnitTestImpl::RunAllTests() { // Makes sure InitGoogleTest() was called. if (!GTestIsInitialized()) { printf("%s", "\nThis test program did NOT call ::testing::InitGoogleTest " "before calling RUN_ALL_TESTS(). Please fix it.\n"); - return 1; + return false; } // Do not run any test if the --help flag was specified. if (g_help_flag) - return 0; + return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. @@ -3980,7 +4147,7 @@ int UnitTestImpl::RunAllTests() { if (GTEST_FLAG(list_tests)) { // This must be called *after* FilterTests() has been called. ListTestsMatchingFilter(); - return 0; + return true; } random_seed_ = GTEST_FLAG(shuffle) ? @@ -3999,7 +4166,9 @@ int UnitTestImpl::RunAllTests() { // Repeats forever if the repeat count is negative. const bool forever = repeat < 0; for (int i = 0; forever || i != repeat; i++) { - ClearResult(); + // We want to preserve failures generated by ad-hoc test + // assertions executed before RUN_ALL_TESTS(). + ClearNonAdHocTestResult(); const TimeInMillis start = GetTimeInMillis(); @@ -4064,8 +4233,7 @@ int UnitTestImpl::RunAllTests() { repeater->OnTestProgramEnd(*parent_); - // Returns 0 if all tests passed, or 1 other wise. - return failed ? 1 : 0; + return !failed; } // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file @@ -4195,12 +4363,12 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { kDisableTestFilter) || internal::UnitTestOptions::MatchesFilter(test_name, kDisableTestFilter); - test_info->impl()->set_is_disabled(is_disabled); + test_info->is_disabled_ = is_disabled; const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(test_case_name, test_name); - test_info->impl()->set_matches_filter(matches_filter); + test_info->matches_filter_ = matches_filter; const bool is_runnable = (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && @@ -4214,7 +4382,7 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { num_runnable_tests += is_runnable; num_selected_tests += is_selected; - test_info->impl()->set_should_run(is_selected); + test_info->should_run_ = is_selected; test_case->set_should_run(test_case->should_run() || is_selected); } } @@ -4230,7 +4398,7 @@ void UnitTestImpl::ListTestsMatchingFilter() { for (size_t j = 0; j < test_case->test_info_list().size(); j++) { const TestInfo* const test_info = test_case->test_info_list()[j]; - if (test_info->matches_filter()) { + if (test_info->matches_filter_) { if (!printed_test_case_name) { printed_test_case_name = true; printf("%s.\n", test_case->name()); @@ -4270,7 +4438,7 @@ OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { // the TestResult for the ad hoc test if no test is running. TestResult* UnitTestImpl::current_test_result() { return current_test_info_ ? - current_test_info_->impl()->result() : &ad_hoc_test_result_; + &(current_test_info_->result_) : &ad_hoc_test_result_; } // Shuffles all test cases, and the tests within each test case, @@ -4299,32 +4467,6 @@ void UnitTestImpl::UnshuffleTests() { } } -// TestInfoImpl constructor. The new instance assumes ownership of the test -// factory object. -TestInfoImpl::TestInfoImpl(TestInfo* parent, - const char* a_test_case_name, - const char* a_name, - const char* a_test_case_comment, - const char* a_comment, - TypeId a_fixture_class_id, - internal::TestFactoryBase* factory) : - parent_(parent), - test_case_name_(String(a_test_case_name)), - name_(String(a_name)), - test_case_comment_(String(a_test_case_comment)), - comment_(String(a_comment)), - fixture_class_id_(a_fixture_class_id), - should_run_(false), - is_disabled_(false), - matches_filter_(false), - factory_(factory) { -} - -// TestInfoImpl destructor. -TestInfoImpl::~TestInfoImpl() { - delete factory_; -} - // Returns the current OS stack trace as a String. // // The maximum number of stack frames to be included is specified by @@ -4342,8 +4484,8 @@ String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); } -// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable -// code warnings. +// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to +// suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; } @@ -4555,6 +4697,10 @@ static const char kColorEncodedHelpMessage[] = GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" " Generate an XML report in the given directory or with the given file\n" " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" +#if GTEST_CAN_STREAM_RESULTS_ +" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" +" Stream test results to the given server.\n" +#endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS @@ -4565,10 +4711,8 @@ static const char kColorEncodedHelpMessage[] = " Turn assertion failures into debugger break-points.\n" " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" " Turn assertion failures into C++ exceptions.\n" -#if GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n" " Suppress pop-ups caused by exceptions.\n" -#endif // GTEST_OS_WINDOWS "\n" "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " "the corresponding\n" @@ -4618,7 +4762,10 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || ParseInt32Flag(arg, kStackTraceDepthFlag, >EST_FLAG(stack_trace_depth)) || - ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)) + ParseStringFlag(arg, kStreamResultToFlag, + >EST_FLAG(stream_result_to)) || + ParseBoolFlag(arg, kThrowOnFailureFlag, + >EST_FLAG(throw_on_failure)) ) { // Yes. Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being diff --git a/testing/gtest/src/gtest_main.cc b/testing/gtest/src/gtest_main.cc index 6d4d22d..a09bbe0 100644 --- a/testing/gtest/src/gtest_main.cc +++ b/testing/gtest/src/gtest_main.cc @@ -29,7 +29,7 @@ #include <iostream> -#include <gtest/gtest.h> +#include "gtest/gtest.h" GTEST_API_ int main(int argc, char **argv) { std::cout << "Running main() from gtest_main.cc\n"; diff --git a/testing/gtest/test/gtest-death-test_test.cc b/testing/gtest/test/gtest-death-test_test.cc index ed5b53b..2f1d385 100644 --- a/testing/gtest/test/gtest-death-test_test.cc +++ b/testing/gtest/test/gtest-death-test_test.cc @@ -31,9 +31,9 @@ // // Tests for death tests. -#include <gtest/gtest-death-test.h> -#include <gtest/gtest.h> -#include <gtest/internal/gtest-filepath.h> +#include "gtest/gtest-death-test.h" +#include "gtest/gtest.h" +#include "gtest/internal/gtest-filepath.h" using testing::internal::AlwaysFalse; using testing::internal::AlwaysTrue; @@ -52,7 +52,7 @@ using testing::internal::AlwaysTrue; #include <signal.h> #include <stdio.h> -#include <gtest/gtest-spi.h> +#include "gtest/gtest-spi.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is @@ -614,17 +614,6 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { abort(); }, ""); } - -TEST(PopUpDeathTest, DoesNotShowPopUpOnThrow) { - printf("This test should be considered failing if it shows " - "any pop-up dialogs.\n"); - fflush(stdout); - - EXPECT_DEATH({ - testing::GTEST_FLAG(catch_exceptions) = false; - throw 1; - }, ""); -} #endif // GTEST_OS_WINDOWS // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort @@ -1005,7 +994,7 @@ TEST(AutoHandleTest, AutoHandleWorks) { typedef unsigned __int64 BiggestParsable; typedef signed __int64 BiggestSignedParsable; const BiggestParsable kBiggestParsableMax = ULLONG_MAX; -const BiggestParsable kBiggestSignedParsableMax = LLONG_MAX; +const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX; #else typedef unsigned long long BiggestParsable; typedef signed long long BiggestSignedParsable; diff --git a/testing/gtest/test/gtest-filepath_test.cc b/testing/gtest/test/gtest-filepath_test.cc index 6250282..549dcef 100644 --- a/testing/gtest/test/gtest-filepath_test.cc +++ b/testing/gtest/test/gtest-filepath_test.cc @@ -38,8 +38,8 @@ // build or make-files for some existing Google Test clients. Do not // #include this file anywhere else! -#include <gtest/internal/gtest-filepath.h> -#include <gtest/gtest.h> +#include "gtest/internal/gtest-filepath.h" +#include "gtest/gtest.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is diff --git a/testing/gtest/test/gtest-linked_ptr_test.cc b/testing/gtest/test/gtest-linked_ptr_test.cc index eae8229..efd6b1e 100644 --- a/testing/gtest/test/gtest-linked_ptr_test.cc +++ b/testing/gtest/test/gtest-linked_ptr_test.cc @@ -30,10 +30,10 @@ // Authors: Dan Egnor (egnor@google.com) // Ported to Windows: Vadim Berman (vadimb@google.com) -#include <gtest/internal/gtest-linked_ptr.h> +#include "gtest/internal/gtest-linked_ptr.h" #include <stdlib.h> -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace { diff --git a/testing/gtest/test/gtest-listener_test.cc b/testing/gtest/test/gtest-listener_test.cc index c9be39a..2aa08ef 100644 --- a/testing/gtest/test/gtest-listener_test.cc +++ b/testing/gtest/test/gtest-listener_test.cc @@ -33,7 +33,7 @@ // This file verifies Google Test event listeners receive events at the // right times. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include <vector> using ::testing::AddGlobalTestEnvironment; diff --git a/testing/gtest/test/gtest-message_test.cc b/testing/gtest/test/gtest-message_test.cc index e42b034..c09c6a8 100644 --- a/testing/gtest/test/gtest-message_test.cc +++ b/testing/gtest/test/gtest-message_test.cc @@ -31,14 +31,13 @@ // // Tests for the Message class. -#include <gtest/gtest-message.h> +#include "gtest/gtest-message.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace { using ::testing::Message; -using ::testing::internal::StrStream; // A helper function that turns a Message into a C string. const char* ToCString(const Message& msg) { @@ -154,9 +153,9 @@ TEST(MessageTest, GetString) { // Tests streaming a Message object to an ostream. TEST(MessageTest, StreamsToOStream) { Message msg("Hello"); - StrStream ss; + ::std::stringstream ss; ss << msg; - EXPECT_STREQ("Hello", testing::internal::StrStreamToString(&ss).c_str()); + EXPECT_STREQ("Hello", testing::internal::StringStreamToString(&ss).c_str()); } // Tests that a Message object doesn't take up too much stack space. diff --git a/testing/gtest/test/gtest-options_test.cc b/testing/gtest/test/gtest-options_test.cc index 2e2cbc9..30b82f3 100644 --- a/testing/gtest/test/gtest-options_test.cc +++ b/testing/gtest/test/gtest-options_test.cc @@ -38,7 +38,7 @@ // make-files on Windows and other platforms. Do not #include this file // anywhere else! -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_OS_WINDOWS_MOBILE #include <windows.h> diff --git a/testing/gtest/test/gtest-param-test2_test.cc b/testing/gtest/test/gtest-param-test2_test.cc index ccb6cfa..4a782fe 100644 --- a/testing/gtest/test/gtest-param-test2_test.cc +++ b/testing/gtest/test/gtest-param-test2_test.cc @@ -32,7 +32,7 @@ // Tests for Google Test itself. This verifies that the basic constructs of // Google Test work. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include "test/gtest-param-test_test.h" diff --git a/testing/gtest/test/gtest-param-test_test.cc b/testing/gtest/test/gtest-param-test_test.cc index 26acce4..c920f4f 100644 --- a/testing/gtest/test/gtest-param-test_test.cc +++ b/testing/gtest/test/gtest-param-test_test.cc @@ -33,7 +33,7 @@ // generators objects produce correct parameter sequences and that // Google Test runtime instantiates correct tests from those sequences. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/test/gtest-param-test_test.h b/testing/gtest/test/gtest-param-test_test.h index b7f9493..d0f6556 100644 --- a/testing/gtest/test/gtest-param-test_test.h +++ b/testing/gtest/test/gtest-param-test_test.h @@ -37,7 +37,7 @@ #ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ #define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_HAS_PARAM_TEST diff --git a/testing/gtest/test/gtest-port_test.cc b/testing/gtest/test/gtest-port_test.cc index 6f1512c..bf42d8b 100644 --- a/testing/gtest/test/gtest-port_test.cc +++ b/testing/gtest/test/gtest-port_test.cc @@ -31,7 +31,7 @@ // // This file tests the internal cross-platform support utilities. -#include <gtest/internal/gtest-port.h> +#include "gtest/internal/gtest-port.h" #include <stdio.h> @@ -41,8 +41,8 @@ #include <utility> // For std::pair and std::make_pair. -#include <gtest/gtest.h> -#include <gtest/gtest-spi.h> +#include "gtest/gtest.h" +#include "gtest/gtest-spi.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is @@ -284,6 +284,17 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { #endif // GTEST_HAS_DEATH_TEST +// Verifies that Google Test choose regular expression engine appropriate to +// the platform. The test will produce compiler errors in case of failure. +// For simplicity, we only cover the most important platforms here. +TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { +#if GTEST_HAS_POSIX_RE + EXPECT_TRUE(GTEST_USES_POSIX_RE); +#else + EXPECT_TRUE(GTEST_USES_SIMPLE_RE); +#endif +} + #if GTEST_USES_POSIX_RE #if GTEST_HAS_TYPED_TEST @@ -366,33 +377,33 @@ TEST(IsInSetTest, WorksForNonNulChars) { EXPECT_TRUE(IsInSet('b', "ab")); } -TEST(IsDigitTest, IsFalseForNonDigit) { - EXPECT_FALSE(IsDigit('\0')); - EXPECT_FALSE(IsDigit(' ')); - EXPECT_FALSE(IsDigit('+')); - EXPECT_FALSE(IsDigit('-')); - EXPECT_FALSE(IsDigit('.')); - EXPECT_FALSE(IsDigit('a')); +TEST(IsAsciiDigitTest, IsFalseForNonDigit) { + EXPECT_FALSE(IsAsciiDigit('\0')); + EXPECT_FALSE(IsAsciiDigit(' ')); + EXPECT_FALSE(IsAsciiDigit('+')); + EXPECT_FALSE(IsAsciiDigit('-')); + EXPECT_FALSE(IsAsciiDigit('.')); + EXPECT_FALSE(IsAsciiDigit('a')); } -TEST(IsDigitTest, IsTrueForDigit) { - EXPECT_TRUE(IsDigit('0')); - EXPECT_TRUE(IsDigit('1')); - EXPECT_TRUE(IsDigit('5')); - EXPECT_TRUE(IsDigit('9')); +TEST(IsAsciiDigitTest, IsTrueForDigit) { + EXPECT_TRUE(IsAsciiDigit('0')); + EXPECT_TRUE(IsAsciiDigit('1')); + EXPECT_TRUE(IsAsciiDigit('5')); + EXPECT_TRUE(IsAsciiDigit('9')); } -TEST(IsPunctTest, IsFalseForNonPunct) { - EXPECT_FALSE(IsPunct('\0')); - EXPECT_FALSE(IsPunct(' ')); - EXPECT_FALSE(IsPunct('\n')); - EXPECT_FALSE(IsPunct('a')); - EXPECT_FALSE(IsPunct('0')); +TEST(IsAsciiPunctTest, IsFalseForNonPunct) { + EXPECT_FALSE(IsAsciiPunct('\0')); + EXPECT_FALSE(IsAsciiPunct(' ')); + EXPECT_FALSE(IsAsciiPunct('\n')); + EXPECT_FALSE(IsAsciiPunct('a')); + EXPECT_FALSE(IsAsciiPunct('0')); } -TEST(IsPunctTest, IsTrueForPunct) { +TEST(IsAsciiPunctTest, IsTrueForPunct) { for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) { - EXPECT_PRED1(IsPunct, *p); + EXPECT_PRED1(IsAsciiPunct, *p); } } @@ -410,47 +421,47 @@ TEST(IsRepeatTest, IsTrueForRepeatChar) { EXPECT_TRUE(IsRepeat('+')); } -TEST(IsWhiteSpaceTest, IsFalseForNonWhiteSpace) { - EXPECT_FALSE(IsWhiteSpace('\0')); - EXPECT_FALSE(IsWhiteSpace('a')); - EXPECT_FALSE(IsWhiteSpace('1')); - EXPECT_FALSE(IsWhiteSpace('+')); - EXPECT_FALSE(IsWhiteSpace('_')); +TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) { + EXPECT_FALSE(IsAsciiWhiteSpace('\0')); + EXPECT_FALSE(IsAsciiWhiteSpace('a')); + EXPECT_FALSE(IsAsciiWhiteSpace('1')); + EXPECT_FALSE(IsAsciiWhiteSpace('+')); + EXPECT_FALSE(IsAsciiWhiteSpace('_')); } -TEST(IsWhiteSpaceTest, IsTrueForWhiteSpace) { - EXPECT_TRUE(IsWhiteSpace(' ')); - EXPECT_TRUE(IsWhiteSpace('\n')); - EXPECT_TRUE(IsWhiteSpace('\r')); - EXPECT_TRUE(IsWhiteSpace('\t')); - EXPECT_TRUE(IsWhiteSpace('\v')); - EXPECT_TRUE(IsWhiteSpace('\f')); +TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) { + EXPECT_TRUE(IsAsciiWhiteSpace(' ')); + EXPECT_TRUE(IsAsciiWhiteSpace('\n')); + EXPECT_TRUE(IsAsciiWhiteSpace('\r')); + EXPECT_TRUE(IsAsciiWhiteSpace('\t')); + EXPECT_TRUE(IsAsciiWhiteSpace('\v')); + EXPECT_TRUE(IsAsciiWhiteSpace('\f')); } -TEST(IsWordCharTest, IsFalseForNonWordChar) { - EXPECT_FALSE(IsWordChar('\0')); - EXPECT_FALSE(IsWordChar('+')); - EXPECT_FALSE(IsWordChar('.')); - EXPECT_FALSE(IsWordChar(' ')); - EXPECT_FALSE(IsWordChar('\n')); +TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) { + EXPECT_FALSE(IsAsciiWordChar('\0')); + EXPECT_FALSE(IsAsciiWordChar('+')); + EXPECT_FALSE(IsAsciiWordChar('.')); + EXPECT_FALSE(IsAsciiWordChar(' ')); + EXPECT_FALSE(IsAsciiWordChar('\n')); } -TEST(IsWordCharTest, IsTrueForLetter) { - EXPECT_TRUE(IsWordChar('a')); - EXPECT_TRUE(IsWordChar('b')); - EXPECT_TRUE(IsWordChar('A')); - EXPECT_TRUE(IsWordChar('Z')); +TEST(IsAsciiWordCharTest, IsTrueForLetter) { + EXPECT_TRUE(IsAsciiWordChar('a')); + EXPECT_TRUE(IsAsciiWordChar('b')); + EXPECT_TRUE(IsAsciiWordChar('A')); + EXPECT_TRUE(IsAsciiWordChar('Z')); } -TEST(IsWordCharTest, IsTrueForDigit) { - EXPECT_TRUE(IsWordChar('0')); - EXPECT_TRUE(IsWordChar('1')); - EXPECT_TRUE(IsWordChar('7')); - EXPECT_TRUE(IsWordChar('9')); +TEST(IsAsciiWordCharTest, IsTrueForDigit) { + EXPECT_TRUE(IsAsciiWordChar('0')); + EXPECT_TRUE(IsAsciiWordChar('1')); + EXPECT_TRUE(IsAsciiWordChar('7')); + EXPECT_TRUE(IsAsciiWordChar('9')); } -TEST(IsWordCharTest, IsTrueForUnderscore) { - EXPECT_TRUE(IsWordChar('_')); +TEST(IsAsciiWordCharTest, IsTrueForUnderscore) { + EXPECT_TRUE(IsAsciiWordChar('_')); } TEST(IsValidEscapeTest, IsFalseForNonPrintable) { diff --git a/testing/gtest/test/gtest-printers_test.cc b/testing/gtest/test/gtest-printers_test.cc index 0ecd871..5eabd23 100644 --- a/testing/gtest/test/gtest-printers_test.cc +++ b/testing/gtest/test/gtest-printers_test.cc @@ -33,7 +33,7 @@ // // This file tests the universal value printer. -#include <gtest/gtest-printers.h> +#include "gtest/gtest-printers.h" #include <ctype.h> #include <limits.h> @@ -48,10 +48,10 @@ #include <utility> #include <vector> -#include <gtest/gtest.h> +#include "gtest/gtest.h" -// hash_map and hash_set are available on Windows. -#if GTEST_OS_WINDOWS +// hash_map and hash_set are available under Visual C++. +#if _MSC_VER #define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. #include <hash_map> // NOLINT #define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. @@ -60,6 +60,42 @@ // Some user-defined types for testing the universal value printer. +// An anonymous enum type. +enum AnonymousEnum { + kAE1 = -1, + kAE2 = 1 +}; + +// An enum without a user-defined printer. +enum EnumWithoutPrinter { + kEWP1 = -2, + kEWP2 = 42 +}; + +// An enum with a << operator. +enum EnumWithStreaming { + kEWS1 = 10, +}; + +std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) { + return os << (e == kEWS1 ? "kEWS1" : "invalid"); +} + +// An enum with a PrintTo() function. +enum EnumWithPrintTo { + kEWPT1 = 1, +}; + +void PrintTo(EnumWithPrintTo e, std::ostream* os) { + *os << (e == kEWPT1 ? "kEWPT1" : "invalid"); +} + +// A class implicitly convertible to BiggestInt. +class BiggestIntConvertible { + public: + operator ::testing::internal::BiggestInt() const { return 42; } +}; + // A user-defined unprintable class template in the global namespace. template <typename T> class UnprintableTemplateInGlobal { @@ -79,15 +115,18 @@ inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) { os << "StreamableInGlobal"; } +void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) { + os << "StreamableInGlobal*"; +} + namespace foo { // A user-defined unprintable type in a user namespace. class UnprintableInFoo { public: - UnprintableInFoo() : x_(0x12EF), y_(0xAB34), z_(0) {} + UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } private: - testing::internal::Int32 x_; - testing::internal::Int32 y_; + char xy_[8]; double z_; }; @@ -101,6 +140,15 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { *os << "PrintableViaPrintTo: " << x.value; } +// A type with a user-defined << for printing its pointer. +struct PointerPrintable { +}; + +::std::ostream& operator<<(::std::ostream& os, + const PointerPrintable* /* x */) { + return os << "PointerPrintable*"; +} + // A user-defined printable class template in a user-chosen namespace. template <typename T> class PrintableViaPrintToTemplate { @@ -164,17 +212,15 @@ using ::std::tr1::make_tuple; using ::std::tr1::tuple; #endif -#if GTEST_OS_WINDOWS +#if _MSC_VER // MSVC defines the following classes in the ::stdext namespace while // gcc defines them in the :: namespace. Note that they are not part // of the C++ standard. - using ::stdext::hash_map; using ::stdext::hash_set; using ::stdext::hash_multimap; using ::stdext::hash_multiset; - -#endif // GTEST_OS_WINDOWS +#endif // Prints a value to a string using the universal value printer. This // is a helper for testing UniversalPrinter<T>::Print() for various types. @@ -195,26 +241,54 @@ string PrintByRef(const T& value) { return ss.str(); } +// Tests printing various enum types. + +TEST(PrintEnumTest, AnonymousEnum) { + EXPECT_EQ("-1", Print(kAE1)); + EXPECT_EQ("1", Print(kAE2)); +} + +TEST(PrintEnumTest, EnumWithoutPrinter) { + EXPECT_EQ("-2", Print(kEWP1)); + EXPECT_EQ("42", Print(kEWP2)); +} + +TEST(PrintEnumTest, EnumWithStreaming) { + EXPECT_EQ("kEWS1", Print(kEWS1)); + EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0))); +} + +TEST(PrintEnumTest, EnumWithPrintTo) { + EXPECT_EQ("kEWPT1", Print(kEWPT1)); + EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0))); +} + +// Tests printing a class implicitly convertible to BiggestInt. + +TEST(PrintClassTest, BiggestIntConvertible) { + EXPECT_EQ("42", Print(BiggestIntConvertible())); +} + // Tests printing various char types. // char. TEST(PrintCharTest, PlainChar) { EXPECT_EQ("'\\0'", Print('\0')); - EXPECT_EQ("'\\'' (39)", Print('\'')); - EXPECT_EQ("'\"' (34)", Print('"')); - EXPECT_EQ("'\\?' (63)", Print('\?')); - EXPECT_EQ("'\\\\' (92)", Print('\\')); + EXPECT_EQ("'\\'' (39, 0x27)", Print('\'')); + EXPECT_EQ("'\"' (34, 0x22)", Print('"')); + EXPECT_EQ("'\\?' (63, 0x3F)", Print('\?')); + EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\')); EXPECT_EQ("'\\a' (7)", Print('\a')); EXPECT_EQ("'\\b' (8)", Print('\b')); - EXPECT_EQ("'\\f' (12)", Print('\f')); - EXPECT_EQ("'\\n' (10)", Print('\n')); - EXPECT_EQ("'\\r' (13)", Print('\r')); + EXPECT_EQ("'\\f' (12, 0xC)", Print('\f')); + EXPECT_EQ("'\\n' (10, 0xA)", Print('\n')); + EXPECT_EQ("'\\r' (13, 0xD)", Print('\r')); EXPECT_EQ("'\\t' (9)", Print('\t')); - EXPECT_EQ("'\\v' (11)", Print('\v')); + EXPECT_EQ("'\\v' (11, 0xB)", Print('\v')); EXPECT_EQ("'\\x7F' (127)", Print('\x7F')); EXPECT_EQ("'\\xFF' (255)", Print('\xFF')); - EXPECT_EQ("' ' (32)", Print(' ')); - EXPECT_EQ("'a' (97)", Print('a')); + EXPECT_EQ("' ' (32, 0x20)", Print(' ')); + EXPECT_EQ("'a' (97, 0x61)", Print('a')); } // signed char. @@ -227,7 +301,7 @@ TEST(PrintCharTest, SignedChar) { // unsigned char. TEST(PrintCharTest, UnsignedChar) { EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0'))); - EXPECT_EQ("'b' (98)", + EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b'))); } @@ -242,23 +316,23 @@ TEST(PrintBuiltInTypeTest, Bool) { // wchar_t. TEST(PrintBuiltInTypeTest, Wchar_t) { EXPECT_EQ("L'\\0'", Print(L'\0')); - EXPECT_EQ("L'\\'' (39)", Print(L'\'')); - EXPECT_EQ("L'\"' (34)", Print(L'"')); - EXPECT_EQ("L'\\?' (63)", Print(L'\?')); - EXPECT_EQ("L'\\\\' (92)", Print(L'\\')); + EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\'')); + EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"')); + EXPECT_EQ("L'\\?' (63, 0x3F)", Print(L'\?')); + EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\')); EXPECT_EQ("L'\\a' (7)", Print(L'\a')); EXPECT_EQ("L'\\b' (8)", Print(L'\b')); - EXPECT_EQ("L'\\f' (12)", Print(L'\f')); - EXPECT_EQ("L'\\n' (10)", Print(L'\n')); - EXPECT_EQ("L'\\r' (13)", Print(L'\r')); + EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f')); + EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n')); + EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r')); EXPECT_EQ("L'\\t' (9)", Print(L'\t')); - EXPECT_EQ("L'\\v' (11)", Print(L'\v')); + EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v')); EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F')); EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF')); - EXPECT_EQ("L' ' (32)", Print(L' ')); - EXPECT_EQ("L'a' (97)", Print(L'a')); - EXPECT_EQ("L'\\x576' (1398)", Print(L'\x576')); - EXPECT_EQ("L'\\xC74D' (51021)", Print(L'\xC74D')); + EXPECT_EQ("L' ' (32, 0x20)", Print(L' ')); + EXPECT_EQ("L'a' (97, 0x61)", Print(L'a')); + EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576))); + EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D))); } // Test that Int64 provides more storage than wchar_t. @@ -364,10 +438,11 @@ TEST(PrintWideCStringTest, Null) { // Tests that wide C strings are escaped properly. TEST(PrintWideCStringTest, EscapesProperly) { - const wchar_t* p = L"'\"\?\\\a\b\f\n\r\t\v\xD3\x576\x8D3\xC74D a"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"'\\\"\\?\\\\\\a\\b\\f" + const wchar_t s[] = {'\'', '"', '\?', '\\', '\a', '\b', '\f', '\n', '\r', + '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; + EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"\\?\\\\\\a\\b\\f" "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", - Print(p)); + Print(static_cast<const wchar_t*>(s))); } #endif // native wchar_t @@ -701,7 +776,7 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { TEST(PrintStlContainerTest, OneElementHashMap) { hash_map<int, char> map1; map1[1] = 'a'; - EXPECT_EQ("{ (1, 'a' (97)) }", Print(map1)); + EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1)); } TEST(PrintStlContainerTest, HashMultiMap) { @@ -741,7 +816,7 @@ TEST(PrintStlContainerTest, HashMultiSet) { std::vector<int> numbers; for (size_t i = 0; i != result.length(); i++) { if (expected_pattern[i] == 'd') { - ASSERT_TRUE(isdigit(result[i]) != 0); + ASSERT_TRUE(isdigit(static_cast<unsigned char>(result[i])) != 0); numbers.push_back(result[i] - '0'); } else { EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " @@ -849,7 +924,7 @@ TEST(PrintTupleTest, VariousSizes) { EXPECT_EQ("(5)", Print(t1)); tuple<char, bool> t2('a', true); - EXPECT_EQ("('a' (97), true)", Print(t2)); + EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); tuple<bool, int, int> t3(false, 2, 3); EXPECT_EQ("(false, 2, 3)", Print(t3)); @@ -878,7 +953,7 @@ TEST(PrintTupleTest, VariousSizes) { tuple<bool, char, short, testing::internal::Int32, // NOLINT testing::internal::Int64, float, double, const char*, void*, string> t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str, NULL, "10"); - EXPECT_EQ("(false, 'a' (97), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + + EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + " pointing to \"8\", NULL, \"10\")", Print(t10)); } @@ -886,7 +961,7 @@ TEST(PrintTupleTest, VariousSizes) { // Nested tuples. TEST(PrintTupleTest, NestedTuple) { tuple<tuple<int, bool>, char> nested(make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97))", Print(nested)); + EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); } #endif // GTEST_HAS_TR1_TUPLE @@ -901,7 +976,7 @@ TEST(PrintUnprintableTypeTest, InGlobalNamespace) { // Unprintable types in a user namespace. TEST(PrintUnprintableTypeTest, InUserNamespace) { - EXPECT_EQ("16-byte object <EF12 0000 34AB 0000 0000 0000 0000 0000>", + EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", Print(::foo::UnprintableInFoo())); } @@ -913,13 +988,13 @@ struct Big { }; TEST(PrintUnpritableTypeTest, BigObject) { - EXPECT_EQ("257-byte object <0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 ... 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 00>", + EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", Print(Big())); } @@ -927,8 +1002,9 @@ TEST(PrintUnpritableTypeTest, BigObject) { // Streamable types in the global namespace. TEST(PrintStreamableTypeTest, InGlobalNamespace) { - EXPECT_EQ("StreamableInGlobal", - Print(StreamableInGlobal())); + StreamableInGlobal x; + EXPECT_EQ("StreamableInGlobal", Print(x)); + EXPECT_EQ("StreamableInGlobal*", Print(&x)); } // Printable template types in a user namespace. @@ -943,6 +1019,13 @@ TEST(PrintPrintableTypeTest, InUserNamespace) { Print(::foo::PrintableViaPrintTo())); } +// Tests printing a pointer to a user-defined type that has a << +// operator for its pointer. +TEST(PrintPrintableTypeTest, PointerInUserNamespace) { + ::foo::PointerPrintable x; + EXPECT_EQ("PointerPrintable*", Print(&x)); +} + // Tests printing user-defined class template that have a PrintTo() function. TEST(PrintPrintableTypeTest, TemplateInUserNamespace) { EXPECT_EQ("PrintableViaPrintToTemplate: 5", @@ -1002,7 +1085,7 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) { const ::foo::UnprintableInFoo x; EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " - "<EF12 0000 34AB 0000 0000 0000 0000 0000>", + "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", PrintByRef(x)); } @@ -1047,26 +1130,35 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) { "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); } +// Useful for testing PrintToString(). We cannot use EXPECT_EQ() +// there as its implementation uses PrintToString(). The caller must +// ensure that 'value' has no side effect. +#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ + EXPECT_TRUE(PrintToString(value) == (expected_string)) \ + << " where " #value " prints as " << (PrintToString(value)) + TEST(PrintToStringTest, WorksForScalar) { - EXPECT_EQ("123", PrintToString(123)); + EXPECT_PRINT_TO_STRING_(123, "123"); } TEST(PrintToStringTest, WorksForPointerToConstChar) { const char* p = "hello"; - EXPECT_EQ("\"hello\"", PrintToString(p)); + EXPECT_PRINT_TO_STRING_(p, "\"hello\""); } TEST(PrintToStringTest, WorksForPointerToNonConstChar) { char s[] = "hello"; char* p = s; - EXPECT_EQ("\"hello\"", PrintToString(p)); + EXPECT_PRINT_TO_STRING_(p, "\"hello\""); } TEST(PrintToStringTest, WorksForArray) { int n[3] = { 1, 2, 3 }; - EXPECT_EQ("{ 1, 2, 3 }", PrintToString(n)); + EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); } +#undef EXPECT_PRINT_TO_STRING_ + TEST(UniversalTersePrintTest, WorksForNonReference) { ::std::stringstream ss; UniversalTersePrint(123, &ss); @@ -1145,7 +1237,7 @@ TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTwoTuple) { Strings result = UniversalTersePrintTupleFieldsToStrings(make_tuple(1, 'a')); ASSERT_EQ(2u, result.size()); EXPECT_EQ("1", result[0]); - EXPECT_EQ("'a' (97)", result[1]); + EXPECT_EQ("'a' (97, 0x61)", result[1]); } TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTersely) { diff --git a/testing/gtest/test/gtest-test-part_test.cc b/testing/gtest/test/gtest-test-part_test.cc index 5a3e919..ca8ba93 100644 --- a/testing/gtest/test/gtest-test-part_test.cc +++ b/testing/gtest/test/gtest-test-part_test.cc @@ -30,9 +30,9 @@ // Author: mheule@google.com (Markus Heule) // -#include <gtest/gtest-test-part.h> +#include "gtest/gtest-test-part.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" using testing::Message; using testing::Test; diff --git a/testing/gtest/test/gtest-tuple_test.cc b/testing/gtest/test/gtest-tuple_test.cc index 532f70b..bfaa3e0 100644 --- a/testing/gtest/test/gtest-tuple_test.cc +++ b/testing/gtest/test/gtest-tuple_test.cc @@ -29,9 +29,9 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/internal/gtest-tuple.h> +#include "gtest/internal/gtest-tuple.h" #include <utility> -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace { diff --git a/testing/gtest/test/gtest-typed-test2_test.cc b/testing/gtest/test/gtest-typed-test2_test.cc index 79a8a87..c284700 100644 --- a/testing/gtest/test/gtest-typed-test2_test.cc +++ b/testing/gtest/test/gtest-typed-test2_test.cc @@ -32,7 +32,7 @@ #include <vector> #include "test/gtest-typed-test_test.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_HAS_TYPED_TEST_P diff --git a/testing/gtest/test/gtest-typed-test_test.cc b/testing/gtest/test/gtest-typed-test_test.cc index f2c3972..dd4ba43 100644 --- a/testing/gtest/test/gtest-typed-test_test.cc +++ b/testing/gtest/test/gtest-typed-test_test.cc @@ -33,7 +33,7 @@ #include <vector> #include "test/gtest-typed-test_test.h" -#include <gtest/gtest.h> +#include "gtest/gtest.h" using testing::Test; diff --git a/testing/gtest/test/gtest-typed-test_test.h b/testing/gtest/test/gtest-typed-test_test.h index 40dfeac..41d7570 100644 --- a/testing/gtest/test/gtest-typed-test_test.h +++ b/testing/gtest/test/gtest-typed-test_test.h @@ -32,7 +32,7 @@ #ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_ #define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_ -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_HAS_TYPED_TEST_P diff --git a/testing/gtest/test/gtest-unittest-api_test.cc b/testing/gtest/test/gtest-unittest-api_test.cc index 7e0f8f8..ed5dea8 100644 --- a/testing/gtest/test/gtest-unittest-api_test.cc +++ b/testing/gtest/test/gtest-unittest-api_test.cc @@ -33,7 +33,7 @@ // This file contains tests verifying correctness of data provided via // UnitTest's public methods. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include <string.h> // For strcmp. #include <algorithm> diff --git a/testing/gtest/test/gtest_break_on_failure_unittest_.cc b/testing/gtest/test/gtest_break_on_failure_unittest_.cc index d28d1d3..3075509 100644 --- a/testing/gtest/test/gtest_break_on_failure_unittest_.cc +++ b/testing/gtest/test/gtest_break_on_failure_unittest_.cc @@ -39,7 +39,7 @@ // This program will be invoked from a Python unit test. It is // expected to fail. Don't run it directly. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #if GTEST_OS_WINDOWS #include <windows.h> @@ -69,7 +69,7 @@ int main(int argc, char **argv) { // a general protection fault (segment violation). SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); -#if !GTEST_OS_WINDOWS_MOBILE +#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE // The default unhandled exception filter does not always exit // with the exception code as exit code - for example it exits with // 0 for EXCEPTION_ACCESS_VIOLATION and 1 for EXCEPTION_BREAKPOINT diff --git a/testing/gtest/test/gtest_catch_exceptions_test.py b/testing/gtest/test/gtest_catch_exceptions_test.py new file mode 100755 index 0000000..061c5c3 --- /dev/null +++ b/testing/gtest/test/gtest_catch_exceptions_test.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python +# +# Copyright 2010 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. + +"""Tests Google Test's exception catching behavior. + +This script invokes gtest_catch_exceptions_test_ and +gtest_catch_exceptions_ex_test_ (programs written with +Google Test) and verifies their output. +""" + +__author__ = 'vladl@google.com (Vlad Losev)' + +import os + +import gtest_test_utils + +# Constants. +LIST_TESTS_FLAG = '--gtest_list_tests' +CATCH_EXCEPTIONS_FLAG = '--gtest_catch_exceptions=1' +FILTER_FLAG='--gtest_filter' + +# Path to the gtest_catch_exceptions_ex_test_ binary, compiled with +# exceptions enabled. +EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( + 'gtest_catch_exceptions_ex_test_') + +# Path to the gtest_catch_exceptions_test_ binary, compiled with +# exceptions disabled. +EXE_PATH = gtest_test_utils.GetTestExecutablePath( + 'gtest_catch_exceptions_no_ex_test_') + +TEST_LIST = gtest_test_utils.Subprocess([EXE_PATH, LIST_TESTS_FLAG]).output + +SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST + +if SUPPORTS_SEH_EXCEPTIONS: + BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH, + CATCH_EXCEPTIONS_FLAG]).output + +EX_BINARY_OUTPUT = gtest_test_utils.Subprocess([EX_EXE_PATH, + CATCH_EXCEPTIONS_FLAG]).output + +# The tests. +if SUPPORTS_SEH_EXCEPTIONS: + # pylint:disable-msg=C6302 + class CatchSehExceptionsTest(gtest_test_utils.TestCase): + """Tests exception-catching behavior.""" + + + def TestSehExceptions(self, test_output): + self.assert_('SEH exception with code 0x2a thrown ' + 'in the test fixture\'s constructor' + in test_output) + self.assert_('SEH exception with code 0x2a thrown ' + 'in the test fixture\'s destructor' + in test_output) + self.assert_('SEH exception with code 0x2a thrown in SetUpTestCase()' + in test_output) + self.assert_('SEH exception with code 0x2a thrown in TearDownTestCase()' + in test_output) + self.assert_('SEH exception with code 0x2a thrown in SetUp()' + in test_output) + self.assert_('SEH exception with code 0x2a thrown in TearDown()' + in test_output) + self.assert_('SEH exception with code 0x2a thrown in the test body' + in test_output) + + def testCatchesSehExceptionsWithCxxExceptionsEnabled(self): + self.TestSehExceptions(EX_BINARY_OUTPUT) + + def testCatchesSehExceptionsWithCxxExceptionsDisabled(self): + self.TestSehExceptions(BINARY_OUTPUT) + + +class CatchCxxExceptionsTest(gtest_test_utils.TestCase): + """Tests C++ exception-catching behavior. + + Tests in this test case verify that: + * C++ exceptions are caught and logged as C++ (not SEH) exceptions + * Exception thrown affect the remainder of the test work flow in the + expected manner. + """ + + def testCatchesCxxExceptionsInFixtureConstructor(self): + self.assert_('C++ exception with description ' + '"Standard C++ exception" thrown ' + 'in the test fixture\'s constructor' + in EX_BINARY_OUTPUT) + self.assert_('unexpected' not in EX_BINARY_OUTPUT, + 'This failure belongs in this test only if ' + '"CxxExceptionInConstructorTest" (no quotes) ' + 'appears on the same line as words "called unexpectedly"') + + def testCatchesCxxExceptionsInFixtureDestructor(self): + self.assert_('C++ exception with description ' + '"Standard C++ exception" thrown ' + 'in the test fixture\'s destructor' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInDestructorTest::TearDownTestCase() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + + def testCatchesCxxExceptionsInSetUpTestCase(self): + self.assert_('C++ exception with description "Standard C++ exception"' + ' thrown in SetUpTestCase()' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInConstructorTest::TearDownTestCase() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTestCaseTest constructor ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTestCaseTest destructor ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTestCaseTest::SetUp() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTestCaseTest::TearDown() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTestCaseTest test body ' + 'called as expected.' + in EX_BINARY_OUTPUT) + + def testCatchesCxxExceptionsInTearDownTestCase(self): + self.assert_('C++ exception with description "Standard C++ exception"' + ' thrown in TearDownTestCase()' + in EX_BINARY_OUTPUT) + + def testCatchesCxxExceptionsInSetUp(self): + self.assert_('C++ exception with description "Standard C++ exception"' + ' thrown in SetUp()' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTest::TearDownTestCase() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTest destructor ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInSetUpTest::TearDown() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('unexpected' not in EX_BINARY_OUTPUT, + 'This failure belongs in this test only if ' + '"CxxExceptionInSetUpTest" (no quotes) ' + 'appears on the same line as words "called unexpectedly"') + + def testCatchesCxxExceptionsInTearDown(self): + self.assert_('C++ exception with description "Standard C++ exception"' + ' thrown in TearDown()' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInTearDownTest::TearDownTestCase() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInTearDownTest destructor ' + 'called as expected.' + in EX_BINARY_OUTPUT) + + def testCatchesCxxExceptionsInTestBody(self): + self.assert_('C++ exception with description "Standard C++ exception"' + ' thrown in the test body' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInTestBodyTest::TearDownTestCase() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInTestBodyTest destructor ' + 'called as expected.' + in EX_BINARY_OUTPUT) + self.assert_('CxxExceptionInTestBodyTest::TearDown() ' + 'called as expected.' + in EX_BINARY_OUTPUT) + + def testCatchesNonStdCxxExceptions(self): + self.assert_('Unknown C++ exception thrown in the test body' + in EX_BINARY_OUTPUT) + + def testUnhandledCxxExceptionsAbortTheProgram(self): + # Filters out SEH exception tests on Windows. Unhandled SEH exceptions + # cause tests to show pop-up windows there. + FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*' + # By default, Google Test doesn't catch the exceptions. + uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess( + [EX_EXE_PATH, FITLER_OUT_SEH_TESTS_FLAG]).output + + self.assert_('Unhandled C++ exception terminating the program' + in uncaught_exceptions_ex_binary_output) + self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/testing/gtest/test/gtest_catch_exceptions_test_.cc b/testing/gtest/test/gtest_catch_exceptions_test_.cc new file mode 100644 index 0000000..3cf7532 --- /dev/null +++ b/testing/gtest/test/gtest_catch_exceptions_test_.cc @@ -0,0 +1,308 @@ +// Copyright 2010, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) +// +// Tests for Google Test itself. Tests in this file throw C++ or SEH +// exceptions, and the output is verified by gtest_catch_exceptions_test.py. + +#include "gtest/gtest.h" + +#include <stdio.h> // NOLINT +#include <stdlib.h> // For exit(). + +#if GTEST_HAS_SEH +#include <windows.h> +#endif + +#if GTEST_HAS_EXCEPTIONS +#include <exception> // For set_terminate(). +#include <stdexcept> +#endif + +using testing::Test; + +#if GTEST_HAS_SEH + +class SehExceptionInConstructorTest : public Test { + public: + SehExceptionInConstructorTest() { RaiseException(42, 0, 0, NULL); } +}; + +TEST_F(SehExceptionInConstructorTest, ThrowsExceptionInConstructor) {} + +class SehExceptionInDestructorTest : public Test { + public: + ~SehExceptionInDestructorTest() { RaiseException(42, 0, 0, NULL); } +}; + +TEST_F(SehExceptionInDestructorTest, ThrowsExceptionInDestructor) {} + +class SehExceptionInSetUpTestCaseTest : public Test { + public: + static void SetUpTestCase() { RaiseException(42, 0, 0, NULL); } +}; + +TEST_F(SehExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) {} + +class SehExceptionInTearDownTestCaseTest : public Test { + public: + static void TearDownTestCase() { RaiseException(42, 0, 0, NULL); } +}; + +TEST_F(SehExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {} + +class SehExceptionInSetUpTest : public Test { + protected: + virtual void SetUp() { RaiseException(42, 0, 0, NULL); } +}; + +TEST_F(SehExceptionInSetUpTest, ThrowsExceptionInSetUp) {} + +class SehExceptionInTearDownTest : public Test { + protected: + virtual void TearDown() { RaiseException(42, 0, 0, NULL); } +}; + +TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {} + +TEST(SehExceptionTest, ThrowsSehException) { + RaiseException(42, 0, 0, NULL); +} + +#endif // GTEST_HAS_SEH + +#if GTEST_HAS_EXCEPTIONS + +class CxxExceptionInConstructorTest : public Test { + public: + CxxExceptionInConstructorTest() { + // Without this macro VC++ complains about unreachable code at the end of + // the constructor. + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( + throw std::runtime_error("Standard C++ exception")); + } + + static void TearDownTestCase() { + printf("%s", + "CxxExceptionInConstructorTest::TearDownTestCase() " + "called as expected.\n"); + } + + protected: + ~CxxExceptionInConstructorTest() { + ADD_FAILURE() << "CxxExceptionInConstructorTest destructor " + << "called unexpectedly."; + } + + virtual void SetUp() { + ADD_FAILURE() << "CxxExceptionInConstructorTest::SetUp() " + << "called unexpectedly."; + } + + virtual void TearDown() { + ADD_FAILURE() << "CxxExceptionInConstructorTest::TearDown() " + << "called unexpectedly."; + } +}; + +TEST_F(CxxExceptionInConstructorTest, ThrowsExceptionInConstructor) { + ADD_FAILURE() << "CxxExceptionInConstructorTest test body " + << "called unexpectedly."; +} + +class CxxExceptionInDestructorTest : public Test { + public: + static void TearDownTestCase() { + printf("%s", + "CxxExceptionInDestructorTest::TearDownTestCase() " + "called as expected.\n"); + } + + protected: + ~CxxExceptionInDestructorTest() { + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( + throw std::runtime_error("Standard C++ exception")); + } +}; + +TEST_F(CxxExceptionInDestructorTest, ThrowsExceptionInDestructor) {} + +class CxxExceptionInSetUpTestCaseTest : public Test { + public: + CxxExceptionInSetUpTestCaseTest() { + printf("%s", + "CxxExceptionInSetUpTestCaseTest constructor " + "called as expected.\n"); + } + + static void SetUpTestCase() { + throw std::runtime_error("Standard C++ exception"); + } + + static void TearDownTestCase() { + printf("%s", + "CxxExceptionInSetUpTestCaseTest::TearDownTestCase() " + "called as expected.\n"); + } + + protected: + ~CxxExceptionInSetUpTestCaseTest() { + printf("%s", + "CxxExceptionInSetUpTestCaseTest destructor " + "called as expected.\n"); + } + + virtual void SetUp() { + printf("%s", + "CxxExceptionInSetUpTestCaseTest::SetUp() " + "called as expected.\n"); + } + + virtual void TearDown() { + printf("%s", + "CxxExceptionInSetUpTestCaseTest::TearDown() " + "called as expected.\n"); + } +}; + +TEST_F(CxxExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) { + printf("%s", + "CxxExceptionInSetUpTestCaseTest test body " + "called as expected.\n"); +} + +class CxxExceptionInTearDownTestCaseTest : public Test { + public: + static void TearDownTestCase() { + throw std::runtime_error("Standard C++ exception"); + } +}; + +TEST_F(CxxExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {} + +class CxxExceptionInSetUpTest : public Test { + public: + static void TearDownTestCase() { + printf("%s", + "CxxExceptionInSetUpTest::TearDownTestCase() " + "called as expected.\n"); + } + + protected: + ~CxxExceptionInSetUpTest() { + printf("%s", + "CxxExceptionInSetUpTest destructor " + "called as expected.\n"); + } + + virtual void SetUp() { throw std::runtime_error("Standard C++ exception"); } + + virtual void TearDown() { + printf("%s", + "CxxExceptionInSetUpTest::TearDown() " + "called as expected.\n"); + } +}; + +TEST_F(CxxExceptionInSetUpTest, ThrowsExceptionInSetUp) { + ADD_FAILURE() << "CxxExceptionInSetUpTest test body " + << "called unexpectedly."; +} + +class CxxExceptionInTearDownTest : public Test { + public: + static void TearDownTestCase() { + printf("%s", + "CxxExceptionInTearDownTest::TearDownTestCase() " + "called as expected.\n"); + } + + protected: + ~CxxExceptionInTearDownTest() { + printf("%s", + "CxxExceptionInTearDownTest destructor " + "called as expected.\n"); + } + + virtual void TearDown() { + throw std::runtime_error("Standard C++ exception"); + } +}; + +TEST_F(CxxExceptionInTearDownTest, ThrowsExceptionInTearDown) {} + +class CxxExceptionInTestBodyTest : public Test { + public: + static void TearDownTestCase() { + printf("%s", + "CxxExceptionInTestBodyTest::TearDownTestCase() " + "called as expected.\n"); + } + + protected: + ~CxxExceptionInTestBodyTest() { + printf("%s", + "CxxExceptionInTestBodyTest destructor " + "called as expected.\n"); + } + + virtual void TearDown() { + printf("%s", + "CxxExceptionInTestBodyTest::TearDown() " + "called as expected.\n"); + } +}; + +TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) { + throw std::runtime_error("Standard C++ exception"); +} + +TEST(CxxExceptionTest, ThrowsNonStdCxxException) { + throw "C-string"; +} + +// This terminate handler aborts the program using exit() rather than abort(). +// This avoids showing pop-ups on Windows systems and core dumps on Unix-like +// ones. +void TerminateHandler() { + fprintf(stderr, "%s\n", "Unhandled C++ exception terminating the program."); + fflush(NULL); + exit(3); +} + +#endif // GTEST_HAS_EXCEPTIONS + +int main(int argc, char** argv) { +#if GTEST_HAS_EXCEPTIONS + std::set_terminate(&TerminateHandler); +#endif + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/testing/gtest/test/gtest_color_test_.cc b/testing/gtest/test/gtest_color_test_.cc index 58d377c..f61ebb8 100644 --- a/testing/gtest/test/gtest_color_test_.cc +++ b/testing/gtest/test/gtest_color_test_.cc @@ -35,7 +35,7 @@ #include <stdio.h> -#include <gtest/gtest.h> +#include "gtest/gtest.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is diff --git a/testing/gtest/test/gtest_env_var_test_.cc b/testing/gtest/test/gtest_env_var_test_.cc index f7c78fc..539afc9 100644 --- a/testing/gtest/test/gtest_env_var_test_.cc +++ b/testing/gtest/test/gtest_env_var_test_.cc @@ -32,7 +32,7 @@ // A helper program for testing that Google Test parses the environment // variables correctly. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include <iostream> diff --git a/testing/gtest/test/gtest_environment_test.cc b/testing/gtest/test/gtest_environment_test.cc index c939261..744b405 100644 --- a/testing/gtest/test/gtest_environment_test.cc +++ b/testing/gtest/test/gtest_environment_test.cc @@ -33,7 +33,11 @@ #include <stdlib.h> #include <stdio.h> -#include <gtest/gtest.h> +#include "gtest/gtest.h" + +#define GTEST_IMPLEMENTATION_ 1 // Required for the next #include. +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ namespace testing { GTEST_DECLARE_string_(filter); @@ -123,6 +127,7 @@ int RunAllTests(MyEnvironment* env, FailureType failure) { env->Reset(); env->set_failure_in_set_up(failure); test_was_run = false; + testing::internal::GetUnitTestImpl()->ClearAdHocTestResult(); return RUN_ALL_TESTS(); } diff --git a/testing/gtest/test/gtest_filter_unittest_.cc b/testing/gtest/test/gtest_filter_unittest_.cc index 325504f..77deffc 100644 --- a/testing/gtest/test/gtest_filter_unittest_.cc +++ b/testing/gtest/test/gtest_filter_unittest_.cc @@ -38,7 +38,7 @@ // The program will be invoked from a Python unit test. Don't run it // directly. -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace { diff --git a/testing/gtest/test/gtest_help_test.py b/testing/gtest/test/gtest_help_test.py index dc67ed3..0777106 100755 --- a/testing/gtest/test/gtest_help_test.py +++ b/testing/gtest/test/gtest_help_test.py @@ -44,12 +44,13 @@ import re import gtest_test_utils +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_') FLAG_PREFIX = '--gtest_' -CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions' DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style' +STREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to' UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing' LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG), @@ -72,7 +73,8 @@ HELP_REGEX = re.compile( FLAG_PREFIX + r'print_time.*' + FLAG_PREFIX + r'output=.*' + FLAG_PREFIX + r'break_on_failure.*' + - FLAG_PREFIX + r'throw_on_failure.*', + FLAG_PREFIX + r'throw_on_failure.*' + + FLAG_PREFIX + r'catch_exceptions.*', re.DOTALL) @@ -109,10 +111,11 @@ class GTestHelpTest(gtest_test_utils.TestCase): exit_code, output = RunWithFlag(flag) self.assertEquals(0, exit_code) self.assert_(HELP_REGEX.search(output), output) - if IS_WINDOWS: - self.assert_(CATCH_EXCEPTIONS_FLAG in output, output) + + if IS_LINUX: + self.assert_(STREAM_RESULT_TO_FLAG in output, output) else: - self.assert_(CATCH_EXCEPTIONS_FLAG not in output, output) + self.assert_(STREAM_RESULT_TO_FLAG not in output, output) if SUPPORTS_DEATH_TESTS and not IS_WINDOWS: self.assert_(DEATH_TEST_STYLE_FLAG in output, output) diff --git a/testing/gtest/test/gtest_help_test_.cc b/testing/gtest/test/gtest_help_test_.cc index aad0d72..31f78c2 100644 --- a/testing/gtest/test/gtest_help_test_.cc +++ b/testing/gtest/test/gtest_help_test_.cc @@ -32,7 +32,7 @@ // This program is meant to be run by gtest_help_test.py. Do not run // it directly. -#include <gtest/gtest.h> +#include "gtest/gtest.h" // When a help flag is specified, this program should skip the tests // and exit with 0; otherwise the following test will be executed, diff --git a/testing/gtest/test/gtest_list_tests_unittest_.cc b/testing/gtest/test/gtest_list_tests_unittest_.cc index a0ed082..2b1d078 100644 --- a/testing/gtest/test/gtest_list_tests_unittest_.cc +++ b/testing/gtest/test/gtest_list_tests_unittest_.cc @@ -38,7 +38,7 @@ // This program will be invoked from a Python unit test. // Don't run it directly. -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace { diff --git a/testing/gtest/test/gtest_main_unittest.cc b/testing/gtest/test/gtest_main_unittest.cc index 7a3f0ad..ecd9bb8 100644 --- a/testing/gtest/test/gtest_main_unittest.cc +++ b/testing/gtest/test/gtest_main_unittest.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/gtest.h> +#include "gtest/gtest.h" // Tests that we don't have to define main() when we link to // gtest_main instead of gtest. diff --git a/testing/gtest/test/gtest_nc.cc b/testing/gtest/test/gtest_nc.cc index 73b5db6..71acf2b 100644 --- a/testing/gtest/test/gtest_nc.cc +++ b/testing/gtest/test/gtest_nc.cc @@ -42,7 +42,7 @@ #ifdef TEST_CANNOT_IGNORE_RUN_ALL_TESTS_RESULT // Tests that the result of RUN_ALL_TESTS() cannot be ignored. -#include <gtest/gtest.h> +#include "gtest/gtest.h" int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); @@ -58,7 +58,7 @@ int main(int argc, char** argv) { // Tests that the compiler catches the typo when a user declares a // Setup() method in a test fixture. -#include <gtest/gtest.h> +#include "gtest/gtest.h" class MyTest : public testing::Test { protected: @@ -69,7 +69,7 @@ class MyTest : public testing::Test { // Tests that the compiler catches the typo when a user calls Setup() // from a test fixture. -#include <gtest/gtest.h> +#include "gtest/gtest.h" class MyTest : public testing::Test { protected: @@ -82,7 +82,7 @@ class MyTest : public testing::Test { // Tests that the compiler catches the typo when a user declares a // Setup() method in a subclass of Environment. -#include <gtest/gtest.h> +#include "gtest/gtest.h" class MyEnvironment : public testing::Environment { public: @@ -93,7 +93,7 @@ class MyEnvironment : public testing::Environment { // Tests that the compiler catches the typo when a user calls Setup() // in an Environment. -#include <gtest/gtest.h> +#include "gtest/gtest.h" class MyEnvironment : public testing::Environment { protected: @@ -107,7 +107,7 @@ class MyEnvironment : public testing::Environment { // Tests that the compiler catches using the wrong test case name in // TYPED_TEST_P. -#include <gtest/gtest.h> +#include "gtest/gtest.h" template <typename T> class FooTest : public testing::Test { @@ -126,7 +126,7 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, testing::Types<int>); // Tests that the compiler catches using the wrong test case name in // REGISTER_TYPED_TEST_CASE_P. -#include <gtest/gtest.h> +#include "gtest/gtest.h" template <typename T> class FooTest : public testing::Test { @@ -145,7 +145,7 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, testing::Types<int>); // Tests that the compiler catches using the wrong test case name in // INSTANTIATE_TYPED_TEST_CASE_P. -#include <gtest/gtest.h> +#include "gtest/gtest.h" template <typename T> class FooTest : public testing::Test { @@ -166,7 +166,7 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, BarTest, testing::Types<int>); // Tests that the compiler catches instantiating TYPED_TEST_CASE_P // twice with the same name prefix. -#include <gtest/gtest.h> +#include "gtest/gtest.h" template <typename T> class FooTest : public testing::Test { @@ -183,21 +183,21 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, testing::Types<double>); #elif defined(TEST_STATIC_ASSERT_TYPE_EQ_IS_NOT_A_TYPE) -#include <gtest/gtest.h> +#include "gtest/gtest.h" // Tests that StaticAssertTypeEq<T1, T2> cannot be used as a type. testing::StaticAssertTypeEq<int, int> dummy; #elif defined(TEST_STATIC_ASSERT_TYPE_EQ_WORKS_IN_NAMESPACE) -#include <gtest/gtest.h> +#include "gtest/gtest.h" // Tests that StaticAssertTypeEq<T1, T2> works in a namespace scope. static bool dummy = testing::StaticAssertTypeEq<int, const int>(); #elif defined(TEST_STATIC_ASSERT_TYPE_EQ_WORKS_IN_CLASS) -#include <gtest/gtest.h> +#include "gtest/gtest.h" template <typename T> class Helper { @@ -215,7 +215,7 @@ void Test() { #elif defined(TEST_STATIC_ASSERT_TYPE_EQ_WORKS_IN_FUNCTION) -#include <gtest/gtest.h> +#include "gtest/gtest.h" void Test() { // Tests that StaticAssertTypeEq<T1, T2> works inside a function. @@ -225,7 +225,7 @@ void Test() { #else // A sanity test. This should compile. -#include <gtest/gtest.h> +#include "gtest/gtest.h" int main() { return RUN_ALL_TESTS(); diff --git a/testing/gtest/test/gtest_nc_test.py b/testing/gtest/test/gtest_nc_test.py index 06ffb3f..bf09234 100755 --- a/testing/gtest/test/gtest_nc_test.py +++ b/testing/gtest/test/gtest_nc_test.py @@ -72,19 +72,27 @@ class GTestNCTest(unittest.TestCase): [r'Setup_should_be_spelled_SetUp']), ('CATCHES_WRONG_CASE_IN_TYPED_TEST_P', - [r'BarTest.*was not declared']), + [r'BarTest.*was not declared', # GCC + r'undeclared identifier .*BarTest', # Clang + ]), ('CATCHES_WRONG_CASE_IN_REGISTER_TYPED_TEST_CASE_P', - [r'BarTest.*was not declared']), + [r'BarTest.*was not declared', # GCC + r'undeclared identifier .*BarTest', # Clang + ]), ('CATCHES_WRONG_CASE_IN_INSTANTIATE_TYPED_TEST_CASE_P', - [r'BarTest.*not declared']), + [r'BarTest.*not declared', # GCC + r'undeclared identifier .*BarTest', # Clang + ]), ('CATCHES_INSTANTIATE_TYPED_TESET_CASE_P_WITH_SAME_NAME_PREFIX', [r'redefinition of.*My.*FooTest']), ('STATIC_ASSERT_TYPE_EQ_IS_NOT_A_TYPE', - [r'StaticAssertTypeEq.* does not name a type']), + [r'StaticAssertTypeEq.* does not name a type', # GCC + r'requires a type.*\n.*StaticAssertTypeEq', # Clang + ]), ('STATIC_ASSERT_TYPE_EQ_WORKS_IN_NAMESPACE', [r'StaticAssertTypeEq.*int.*const int']), diff --git a/testing/gtest/test/gtest_no_test_unittest.cc b/testing/gtest/test/gtest_no_test_unittest.cc index afe2dc0..e3a85f1 100644 --- a/testing/gtest/test/gtest_no_test_unittest.cc +++ b/testing/gtest/test/gtest_no_test_unittest.cc @@ -32,7 +32,7 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/gtest.h> +#include "gtest/gtest.h" int main(int argc, char **argv) { @@ -40,15 +40,18 @@ int main(int argc, char **argv) { // An ad-hoc assertion outside of all tests. // - // This serves two purposes: + // This serves three purposes: // // 1. It verifies that an ad-hoc assertion can be executed even if // no test is defined. - // 2. We had a bug where the XML output won't be generated if an + // 2. It verifies that a failed ad-hoc assertion causes the test + // program to fail. + // 3. We had a bug where the XML output won't be generated if an // assertion is executed before RUN_ALL_TESTS() is called, even // though --gtest_output=xml is specified. This makes sure the // bug is fixed and doesn't regress. - EXPECT_EQ(1, 1); + EXPECT_EQ(1, 2); - return RUN_ALL_TESTS(); + // The above EXPECT_EQ() should cause RUN_ALL_TESTS() to return non-zero. + return RUN_ALL_TESTS() ? 0 : 1; } diff --git a/testing/gtest/test/gtest_output_test.py b/testing/gtest/test/gtest_output_test.py index 425d9da..f409e2a 100755 --- a/testing/gtest/test/gtest_output_test.py +++ b/testing/gtest/test/gtest_output_test.py @@ -52,10 +52,8 @@ CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS' IS_WINDOWS = os.name == 'nt' -if IS_WINDOWS: - GOLDEN_NAME = 'gtest_output_test_golden_win.txt' -else: - GOLDEN_NAME = 'gtest_output_test_golden_lin.txt' +# TODO(vladl@google.com): remove the _lin suffix. +GOLDEN_NAME = 'gtest_output_test_golden_lin.txt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_') @@ -138,6 +136,20 @@ def RemoveTypeInfoDetails(test_output): return re.sub(r'unsigned int', 'unsigned', test_output) +def NormalizeToCurrentPlatform(test_output): + """Normalizes platform specific output details for easier comparison.""" + + if IS_WINDOWS: + # Removes the color information that is not present on Windows. + test_output = re.sub('\x1b\\[(0;3\d)?m', '', test_output) + # Changes failure message headers into the Windows format. + test_output = re.sub(r': Failure\n', r': error: ', test_output) + # Changes file(line_number) to file:line_number. + test_output = re.sub(r'((\w|\.)+)\((\d+)\):', r'\1:\3:', test_output) + + return test_output + + def RemoveTestCounts(output): """Removes test counts from a Google Test program's output.""" @@ -240,7 +252,7 @@ SUPPORTS_STACK_TRACES = False CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS and - (SUPPORTS_THREADS or IS_WINDOWS)) + SUPPORTS_THREADS) class GTestOutputTest(gtest_test_utils.TestCase): @@ -284,9 +296,10 @@ class GTestOutputTest(gtest_test_utils.TestCase): if CAN_GENERATE_GOLDEN_FILE: self.assertEqual(normalized_golden, normalized_actual) else: - normalized_actual = RemoveTestCounts(normalized_actual) - normalized_golden = RemoveTestCounts(self.RemoveUnsupportedTests( - normalized_golden)) + normalized_actual = NormalizeToCurrentPlatform( + RemoveTestCounts(normalized_actual)) + normalized_golden = NormalizeToCurrentPlatform( + RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden))) # This code is very handy when debugging golden file differences: if os.getenv('DEBUG_GTEST_OUTPUT_TEST'): @@ -312,14 +325,9 @@ if __name__ == '__main__': else: message = ( """Unable to write a golden file when compiled in an environment -that does not support all the required features (death tests""") - if IS_WINDOWS: - message += ( - """\nand typed tests). Please check that you are using VC++ 8.0 SP1 -or higher as your compiler.""") - else: - message += """\ntyped tests, and threads). Please generate the -golden file using a binary built with those features enabled.""" +that does not support all the required features (death tests, typed tests, +and multiple threads). Please generate the golden file using a binary built +with those features enabled.""") sys.stderr.write(message) sys.exit(1) diff --git a/testing/gtest/test/gtest_output_test_.cc b/testing/gtest/test/gtest_output_test_.cc index 1ac439c..47343e5 100644 --- a/testing/gtest/test/gtest_output_test_.cc +++ b/testing/gtest/test/gtest_output_test_.cc @@ -32,8 +32,8 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/gtest-spi.h> -#include <gtest/gtest.h> +#include "gtest/gtest-spi.h" +#include "gtest/gtest.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is @@ -441,137 +441,10 @@ TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { << "We should never get here, as SetUp() failed."; } -#if GTEST_OS_WINDOWS - -// This group of tests verifies that Google Test handles SEH and C++ -// exceptions correctly. - -// A function that throws an SEH exception. -static void ThrowSEH() { - int* p = NULL; - *p = 0; // Raises an access violation. -} - -// Tests exceptions thrown in the test fixture constructor. -class ExceptionInFixtureCtorTest : public testing::Test { - protected: - ExceptionInFixtureCtorTest() { - printf("(expecting a failure on thrown exception " - "in the test fixture's constructor)\n"); - - ThrowSEH(); - } - - virtual ~ExceptionInFixtureCtorTest() { - Deinit(); - } - - virtual void SetUp() { - FAIL() << "UNEXPECTED failure in SetUp(). " - << "We should never get here, as the test fixture c'tor threw."; - } - - virtual void TearDown() { - FAIL() << "UNEXPECTED failure in TearDown(). " - << "We should never get here, as the test fixture c'tor threw."; - } - private: - void Deinit() { - FAIL() << "UNEXPECTED failure in the d'tor. " - << "We should never get here, as the test fixture c'tor threw."; - } -}; - -TEST_F(ExceptionInFixtureCtorTest, ExceptionInFixtureCtor) { - FAIL() << "UNEXPECTED failure in the test function. " - << "We should never get here, as the test fixture c'tor threw."; -} - -// Tests exceptions thrown in SetUp(). -class ExceptionInSetUpTest : public testing::Test { - protected: - virtual ~ExceptionInSetUpTest() { - Deinit(); - } - - virtual void SetUp() { - printf("(expecting 3 failures)\n"); - - ThrowSEH(); - } - - virtual void TearDown() { - FAIL() << "Expected failure #2, in TearDown()."; - } - private: - void Deinit() { - FAIL() << "Expected failure #3, in the test fixture d'tor."; - } -}; - -TEST_F(ExceptionInSetUpTest, ExceptionInSetUp) { - FAIL() << "UNEXPECTED failure in the test function. " - << "We should never get here, as SetUp() threw."; +TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) { + ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc"; } -// Tests that TearDown() and the test fixture d'tor are always called, -// even when the test function throws an exception. -class ExceptionInTestFunctionTest : public testing::Test { - protected: - virtual ~ExceptionInTestFunctionTest() { - Deinit(); - } - - virtual void TearDown() { - FAIL() << "Expected failure #2, in TearDown()."; - } - private: - void Deinit() { - FAIL() << "Expected failure #3, in the test fixture d'tor."; - } -}; - -// Tests that the test fixture d'tor is always called, even when the -// test function throws an SEH exception. -TEST_F(ExceptionInTestFunctionTest, SEH) { - printf("(expecting 3 failures)\n"); - - ThrowSEH(); -} - -#if GTEST_HAS_EXCEPTIONS - -// Tests that the test fixture d'tor is always called, even when the -// test function throws a C++ exception. We do this only when -// GTEST_HAS_EXCEPTIONS is non-zero, i.e. C++ exceptions are enabled. -TEST_F(ExceptionInTestFunctionTest, CppException) { - throw 1; -} - -// Tests exceptions thrown in TearDown(). -class ExceptionInTearDownTest : public testing::Test { - protected: - virtual ~ExceptionInTearDownTest() { - Deinit(); - } - - virtual void TearDown() { - throw 1; - } - private: - void Deinit() { - FAIL() << "Expected failure #2, in the test fixture d'tor."; - } -}; - -TEST_F(ExceptionInTearDownTest, ExceptionInTearDown) { - printf("(expecting 2 failures)\n"); -} - -#endif // GTEST_HAS_EXCEPTIONS - -#endif // GTEST_OS_WINDOWS - #if GTEST_IS_THREADSAFE // A unary function that may die. diff --git a/testing/gtest/test/gtest_output_test_golden_lin.txt b/testing/gtest/test/gtest_output_test_golden_lin.txt index 2f3994a..0ba9968 100644 --- a/testing/gtest/test/gtest_output_test_golden_lin.txt +++ b/testing/gtest/test/gtest_output_test_golden_lin.txt @@ -7,7 +7,7 @@ Expected: true gtest_output_test_.cc:#: Failure Value of: 3 Expected: 2 -[0;32m[==========] [mRunning 61 tests from 26 test cases. +[0;32m[==========] [mRunning 62 tests from 27 test cases. [0;32m[----------] [mGlobal test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -235,6 +235,12 @@ gtest_output_test_.cc:#: Failure Failed Expected failure #3, in the test fixture d'tor. [0;31m[ FAILED ] [mFatalFailureInSetUpTest.FailureInSetUp +[0;32m[----------] [m1 test from AddFailureAtTest +[0;32m[ RUN ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber +foo.cc:42: Failure +Failed +Expected failure in foo.cc +[0;31m[ FAILED ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber [0;32m[----------] [m4 tests from MixedUpTestCaseTest [0;32m[ RUN ] [mMixedUpTestCaseTest.FirstTestFromNamespaceFoo [0;32m[ OK ] [mMixedUpTestCaseTest.FirstTestFromNamespaceFoo @@ -418,7 +424,7 @@ Expected failure [0;32m[ RUN ] [mUnsigned/TypedTestP/0.Failure gtest_output_test_.cc:#: Failure Value of: TypeParam() - Actual: \0 + Actual: '\0' Expected: 1U Which is: 1 Expected failure @@ -580,9 +586,9 @@ FooEnvironment::TearDown() called. gtest_output_test_.cc:#: Failure Failed Expected fatal failure. -[0;32m[==========] [m61 tests from 26 test cases ran. +[0;32m[==========] [m62 tests from 27 test cases ran. [0;32m[ PASSED ] [m21 tests. -[0;31m[ FAILED ] [m40 tests, listed below: +[0;31m[ FAILED ] [m41 tests, listed below: [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInSubroutine [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInNestedSubroutine [0;31m[ FAILED ] [mFatalFailureTest.NonfatalFailureInSubroutine @@ -597,6 +603,7 @@ Expected fatal failure. [0;31m[ FAILED ] [mFatalFailureInFixtureConstructorTest.FailureInConstructor [0;31m[ FAILED ] [mNonFatalFailureInSetUpTest.FailureInSetUp [0;31m[ FAILED ] [mFatalFailureInSetUpTest.FailureInSetUp +[0;31m[ FAILED ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber [0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFail [0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFailToo [0;31m[ FAILED ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail @@ -624,7 +631,7 @@ Expected fatal failure. [0;31m[ FAILED ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread [0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -40 FAILED TESTS +41 FAILED TESTS [0;33m YOU HAVE 1 DISABLED TEST [mNote: Google Test filter = FatalFailureTest.*:LoggingTest.* diff --git a/testing/gtest/test/gtest_output_test_golden_win.txt b/testing/gtest/test/gtest_output_test_golden_win.txt deleted file mode 100644 index fb69710..0000000 --- a/testing/gtest/test/gtest_output_test_golden_win.txt +++ /dev/null @@ -1,612 +0,0 @@ -The non-test part of the code is expected to have 2 failures. - -gtest_output_test_.cc:#: error: Value of: false - Actual: false -Expected: true -gtest_output_test_.cc:#: error: Value of: 3 -Expected: 2 -[==========] Running 62 tests from 28 test cases. -[----------] Global test environment set-up. -FooEnvironment::SetUp() called. -BarEnvironment::SetUp() called. -[----------] 1 test from ADeathTest -[ RUN ] ADeathTest.ShouldRunFirst -[ OK ] ADeathTest.ShouldRunFirst -[----------] 1 test from ATypedDeathTest/0, where TypeParam = int -[ RUN ] ATypedDeathTest/0.ShouldRunFirst -[ OK ] ATypedDeathTest/0.ShouldRunFirst -[----------] 1 test from ATypedDeathTest/1, where TypeParam = double -[ RUN ] ATypedDeathTest/1.ShouldRunFirst -[ OK ] ATypedDeathTest/1.ShouldRunFirst -[----------] 1 test from My/ATypeParamDeathTest/0, where TypeParam = int -[ RUN ] My/ATypeParamDeathTest/0.ShouldRunFirst -[ OK ] My/ATypeParamDeathTest/0.ShouldRunFirst -[----------] 1 test from My/ATypeParamDeathTest/1, where TypeParam = double -[ RUN ] My/ATypeParamDeathTest/1.ShouldRunFirst -[ OK ] My/ATypeParamDeathTest/1.ShouldRunFirst -[----------] 2 tests from PassingTest -[ RUN ] PassingTest.PassingTest1 -[ OK ] PassingTest.PassingTest1 -[ RUN ] PassingTest.PassingTest2 -[ OK ] PassingTest.PassingTest2 -[----------] 3 tests from FatalFailureTest -[ RUN ] FatalFailureTest.FatalFailureInSubroutine -(expecting a failure that x should be 1) -gtest_output_test_.cc:#: error: Value of: x - Actual: 2 -Expected: 1 -[ FAILED ] FatalFailureTest.FatalFailureInSubroutine -[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine -(expecting a failure that x should be 1) -gtest_output_test_.cc:#: error: Value of: x - Actual: 2 -Expected: 1 -[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine -[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine -(expecting a failure on false) -gtest_output_test_.cc:#: error: Value of: false - Actual: false -Expected: true -[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine -[----------] 1 test from LoggingTest -[ RUN ] LoggingTest.InterleavingLoggingAndAssertions -(expecting 2 failures on (3) >= (a[i])) -i == 0 -i == 1 -gtest_output_test_.cc:#: error: Expected: (3) >= (a[i]), actual: 3 vs 9 -i == 2 -i == 3 -gtest_output_test_.cc:#: error: Expected: (3) >= (a[i]), actual: 3 vs 6 -[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions -[----------] 5 tests from SCOPED_TRACETest -[ RUN ] SCOPED_TRACETest.ObeysScopes -(expected to fail) -gtest_output_test_.cc:#: error: Failed -This failure is expected, and shouldn't have a trace. -gtest_output_test_.cc:#: error: Failed -This failure is expected, and should have a trace. -Google Test trace: -gtest_output_test_.cc:#: Expected trace -gtest_output_test_.cc:#: error: Failed -This failure is expected, and shouldn't have a trace. -[ FAILED ] SCOPED_TRACETest.ObeysScopes -[ RUN ] SCOPED_TRACETest.WorksInLoop -(expected to fail) -gtest_output_test_.cc:#: error: Value of: n - Actual: 1 -Expected: 2 -Google Test trace: -gtest_output_test_.cc:#: i = 1 -gtest_output_test_.cc:#: error: Value of: n - Actual: 2 -Expected: 1 -Google Test trace: -gtest_output_test_.cc:#: i = 2 -[ FAILED ] SCOPED_TRACETest.WorksInLoop -[ RUN ] SCOPED_TRACETest.WorksInSubroutine -(expected to fail) -gtest_output_test_.cc:#: error: Value of: n - Actual: 1 -Expected: 2 -Google Test trace: -gtest_output_test_.cc:#: n = 1 -gtest_output_test_.cc:#: error: Value of: n - Actual: 2 -Expected: 1 -Google Test trace: -gtest_output_test_.cc:#: n = 2 -[ FAILED ] SCOPED_TRACETest.WorksInSubroutine -[ RUN ] SCOPED_TRACETest.CanBeNested -(expected to fail) -gtest_output_test_.cc:#: error: Value of: n - Actual: 2 -Expected: 1 -Google Test trace: -gtest_output_test_.cc:#: n = 2 -gtest_output_test_.cc:#: -[ FAILED ] SCOPED_TRACETest.CanBeNested -[ RUN ] SCOPED_TRACETest.CanBeRepeated -(expected to fail) -gtest_output_test_.cc:#: error: Failed -This failure is expected, and should contain trace point A. -Google Test trace: -gtest_output_test_.cc:#: A -gtest_output_test_.cc:#: error: Failed -This failure is expected, and should contain trace point A and B. -Google Test trace: -gtest_output_test_.cc:#: B -gtest_output_test_.cc:#: A -gtest_output_test_.cc:#: error: Failed -This failure is expected, and should contain trace point A, B, and C. -Google Test trace: -gtest_output_test_.cc:#: C -gtest_output_test_.cc:#: B -gtest_output_test_.cc:#: A -gtest_output_test_.cc:#: error: Failed -This failure is expected, and should contain trace point A, B, and D. -Google Test trace: -gtest_output_test_.cc:#: D -gtest_output_test_.cc:#: B -gtest_output_test_.cc:#: A -[ FAILED ] SCOPED_TRACETest.CanBeRepeated -[----------] 1 test from NonFatalFailureInFixtureConstructorTest -[ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor -(expecting 5 failures) -gtest_output_test_.cc:#: error: Failed -Expected failure #1, in the test fixture c'tor. -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in SetUp(). -gtest_output_test_.cc:#: error: Failed -Expected failure #3, in the test body. -gtest_output_test_.cc:#: error: Failed -Expected failure #4, in TearDown. -gtest_output_test_.cc:#: error: Failed -Expected failure #5, in the test fixture d'tor. -[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor -[----------] 1 test from FatalFailureInFixtureConstructorTest -[ RUN ] FatalFailureInFixtureConstructorTest.FailureInConstructor -(expecting 2 failures) -gtest_output_test_.cc:#: error: Failed -Expected failure #1, in the test fixture c'tor. -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in the test fixture d'tor. -[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor -[----------] 1 test from NonFatalFailureInSetUpTest -[ RUN ] NonFatalFailureInSetUpTest.FailureInSetUp -(expecting 4 failures) -gtest_output_test_.cc:#: error: Failed -Expected failure #1, in SetUp(). -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in the test function. -gtest_output_test_.cc:#: error: Failed -Expected failure #3, in TearDown(). -gtest_output_test_.cc:#: error: Failed -Expected failure #4, in the test fixture d'tor. -[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp -[----------] 1 test from FatalFailureInSetUpTest -[ RUN ] FatalFailureInSetUpTest.FailureInSetUp -(expecting 3 failures) -gtest_output_test_.cc:#: error: Failed -Expected failure #1, in SetUp(). -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in TearDown(). -gtest_output_test_.cc:#: error: Failed -Expected failure #3, in the test fixture d'tor. -[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp -[----------] 1 test from ExceptionInFixtureCtorTest -[ RUN ] ExceptionInFixtureCtorTest.ExceptionInFixtureCtor -(expecting a failure on thrown exception in the test fixture's constructor) -unknown file: error: Exception thrown with code 0xc0000005 in the test fixture's constructor. -[----------] 1 test from ExceptionInSetUpTest -[ RUN ] ExceptionInSetUpTest.ExceptionInSetUp -(expecting 3 failures) -unknown file: error: Exception thrown with code 0xc0000005 in SetUp(). -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in TearDown(). -gtest_output_test_.cc:#: error: Failed -Expected failure #3, in the test fixture d'tor. -[ FAILED ] ExceptionInSetUpTest.ExceptionInSetUp -[----------] 2 tests from ExceptionInTestFunctionTest -[ RUN ] ExceptionInTestFunctionTest.SEH -(expecting 3 failures) -unknown file: error: Exception thrown with code 0xc0000005 in the test body. -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in TearDown(). -gtest_output_test_.cc:#: error: Failed -Expected failure #3, in the test fixture d'tor. -[ FAILED ] ExceptionInTestFunctionTest.SEH -[ RUN ] ExceptionInTestFunctionTest.CppException -unknown file: error: Exception thrown with code 0xe06d7363 in the test body. -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in TearDown(). -gtest_output_test_.cc:#: error: Failed -Expected failure #3, in the test fixture d'tor. -[ FAILED ] ExceptionInTestFunctionTest.CppException -[----------] 1 test from ExceptionInTearDownTest -[ RUN ] ExceptionInTearDownTest.ExceptionInTearDown -(expecting 2 failures) -unknown file: error: Exception thrown with code 0xe06d7363 in TearDown(). -gtest_output_test_.cc:#: error: Failed -Expected failure #2, in the test fixture d'tor. -[ FAILED ] ExceptionInTearDownTest.ExceptionInTearDown -[----------] 4 tests from MixedUpTestCaseTest -[ RUN ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo -[ OK ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo -[ RUN ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo -[ OK ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo -[ RUN ] MixedUpTestCaseTest.ThisShouldFail -gtest.cc:#: error: Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseTest, -you defined test FirstTestFromNamespaceFoo and test ThisShouldFail -using two different test fixture classes. This can happen if -the two classes are from different namespaces or translation -units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. -[ FAILED ] MixedUpTestCaseTest.ThisShouldFail -[ RUN ] MixedUpTestCaseTest.ThisShouldFailToo -gtest.cc:#: error: Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseTest, -you defined test FirstTestFromNamespaceFoo and test ThisShouldFailToo -using two different test fixture classes. This can happen if -the two classes are from different namespaces or translation -units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. -[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo -[----------] 2 tests from MixedUpTestCaseWithSameTestNameTest -[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[ OK ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -gtest.cc:#: error: Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseWithSameTestNameTest, -you defined test TheSecondTestWithThisNameShouldFail and test TheSecondTestWithThisNameShouldFail -using two different test fixture classes. This can happen if -the two classes are from different namespaces or translation -units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. -[ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[----------] 2 tests from TEST_F_before_TEST_in_same_test_case -[ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F -[ OK ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F -[ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail -gtest.cc:#: error: Failed -All tests in the same test case must use the same test fixture -class, so mixing TEST_F and TEST in the same test case is -illegal. In test case TEST_F_before_TEST_in_same_test_case, -test DefinedUsingTEST_F is defined using TEST_F but -test DefinedUsingTESTAndShouldFail is defined using TEST. You probably -want to change the TEST to TEST_F or move it to another test -case. -[ FAILED ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail -[----------] 2 tests from TEST_before_TEST_F_in_same_test_case -[ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST -[ OK ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST -[ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail -gtest.cc:#: error: Failed -All tests in the same test case must use the same test fixture -class, so mixing TEST_F and TEST in the same test case is -illegal. In test case TEST_before_TEST_F_in_same_test_case, -test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but -test DefinedUsingTEST is defined using TEST. You probably -want to change the TEST to TEST_F or move it to another test -case. -[ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail -[----------] 8 tests from ExpectNonfatalFailureTest -[ RUN ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables -[ OK ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables -[ RUN ] ExpectNonfatalFailureTest.CanReferenceLocalVariables -[ OK ] ExpectNonfatalFailureTest.CanReferenceLocalVariables -[ RUN ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure -[ OK ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure -[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure -(expecting a failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: 0 failures -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure -[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures -(expecting a failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: 2 failures -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure 1. - -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure 2. - -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures -[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure -(expecting a failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. - -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure -[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementReturns -(expecting a failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: 0 failures -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns -[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementThrows -(expecting a failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: 0 failures -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementThrows -[----------] 8 tests from ExpectFatalFailureTest -[ RUN ] ExpectFatalFailureTest.CanReferenceGlobalVariables -[ OK ] ExpectFatalFailureTest.CanReferenceGlobalVariables -[ RUN ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables -[ OK ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables -[ RUN ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure -[ OK ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure -[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure -(expecting a failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: 0 failures -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure -[ RUN ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures -(expecting a failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: 2 failures -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. - -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. - -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures -[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure -(expecting a failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. - -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure -[ RUN ] ExpectFatalFailureTest.FailsWhenStatementReturns -(expecting a failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: 0 failures -[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns -[ RUN ] ExpectFatalFailureTest.FailsWhenStatementThrows -(expecting a failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: 0 failures -[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementThrows -[----------] 2 tests from TypedTest/0, where TypeParam = int -[ RUN ] TypedTest/0.Success -[ OK ] TypedTest/0.Success -[ RUN ] TypedTest/0.Failure -gtest_output_test_.cc:#: error: Value of: TypeParam() - Actual: 0 -Expected: 1 -Expected failure -[ FAILED ] TypedTest/0.Failure, where TypeParam = int -[----------] 2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char -[ RUN ] Unsigned/TypedTestP/0.Success -[ OK ] Unsigned/TypedTestP/0.Success -[ RUN ] Unsigned/TypedTestP/0.Failure -gtest_output_test_.cc:#: error: Value of: TypeParam() - Actual: \0 -Expected: 1U -Which is: 1 -Expected failure -[ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char -[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int -[ RUN ] Unsigned/TypedTestP/1.Success -[ OK ] Unsigned/TypedTestP/1.Success -[ RUN ] Unsigned/TypedTestP/1.Failure -gtest_output_test_.cc:#: error: Value of: TypeParam() - Actual: 0 -Expected: 1U -Which is: 1 -Expected failure -[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int -[----------] 4 tests from ExpectFailureTest -[ RUN ] ExpectFailureTest.ExpectFatalFailure -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 fatal failure containing "Some other fatal failure expected." - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. - -[ FAILED ] ExpectFailureTest.ExpectFatalFailure -[ RUN ] ExpectFailureTest.ExpectNonFatalFailure -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 non-fatal failure containing "Some other non-fatal failure." - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. - -[ FAILED ] ExpectFailureTest.ExpectNonFatalFailure -[ RUN ] ExpectFailureTest.ExpectFatalFailureOnAllThreads -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 fatal failure containing "Some other fatal failure expected." - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. - -[ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads -[ RUN ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. - -(expecting 1 failure) -gtest.cc:#: error: Expected: 1 non-fatal failure containing "Some other non-fatal failure." - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. - -[ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads -[----------] 1 test from PrintingFailingParams/FailingParamTest -[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 -gtest_output_test_.cc:#: error: Value of: GetParam() - Actual: 2 -Expected: 1 -[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -[----------] Global test environment tear-down -BarEnvironment::TearDown() called. -gtest_output_test_.cc:#: error: Failed -Expected non-fatal failure. -FooEnvironment::TearDown() called. -gtest_output_test_.cc:#: error: Failed -Expected fatal failure. -[==========] 62 tests from 28 test cases ran. -[ PASSED ] 21 tests. -[ FAILED ] 41 tests, listed below: -[ FAILED ] FatalFailureTest.FatalFailureInSubroutine -[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine -[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine -[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions -[ FAILED ] SCOPED_TRACETest.ObeysScopes -[ FAILED ] SCOPED_TRACETest.WorksInLoop -[ FAILED ] SCOPED_TRACETest.WorksInSubroutine -[ FAILED ] SCOPED_TRACETest.CanBeNested -[ FAILED ] SCOPED_TRACETest.CanBeRepeated -[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor -[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor -[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp -[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp -[ FAILED ] ExceptionInFixtureCtorTest.ExceptionInFixtureCtor -[ FAILED ] ExceptionInSetUpTest.ExceptionInSetUp -[ FAILED ] ExceptionInTestFunctionTest.SEH -[ FAILED ] ExceptionInTestFunctionTest.CppException -[ FAILED ] ExceptionInTearDownTest.ExceptionInTearDown -[ FAILED ] MixedUpTestCaseTest.ThisShouldFail -[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo -[ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[ FAILED ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail -[ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementThrows -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure -[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns -[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementThrows -[ FAILED ] TypedTest/0.Failure, where TypeParam = int -[ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char -[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int -[ FAILED ] ExpectFailureTest.ExpectFatalFailure -[ FAILED ] ExpectFailureTest.ExpectNonFatalFailure -[ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads -[ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads -[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 - -41 FAILED TESTS - YOU HAVE 1 DISABLED TEST - -Note: Google Test filter = FatalFailureTest.*:LoggingTest.* -[==========] Running 4 tests from 2 test cases. -[----------] Global test environment set-up. -[----------] 3 tests from FatalFailureTest -[ RUN ] FatalFailureTest.FatalFailureInSubroutine -(expecting a failure that x should be 1) -gtest_output_test_.cc:#: error: Value of: x - Actual: 2 -Expected: 1 -[ FAILED ] FatalFailureTest.FatalFailureInSubroutine (? ms) -[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine -(expecting a failure that x should be 1) -gtest_output_test_.cc:#: error: Value of: x - Actual: 2 -Expected: 1 -[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms) -[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine -(expecting a failure on false) -gtest_output_test_.cc:#: error: Value of: false - Actual: false -Expected: true -[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine (? ms) -[----------] 3 tests from FatalFailureTest (? ms total) - -[----------] 1 test from LoggingTest -[ RUN ] LoggingTest.InterleavingLoggingAndAssertions -(expecting 2 failures on (3) >= (a[i])) -i == 0 -i == 1 -gtest_output_test_.cc:#: error: Expected: (3) >= (a[i]), actual: 3 vs 9 -i == 2 -i == 3 -gtest_output_test_.cc:#: error: Expected: (3) >= (a[i]), actual: 3 vs 6 -[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions (? ms) -[----------] 1 test from LoggingTest (? ms total) - -[----------] Global test environment tear-down -[==========] 4 tests from 2 test cases ran. (? ms total) -[ PASSED ] 0 tests. -[ FAILED ] 4 tests, listed below: -[ FAILED ] FatalFailureTest.FatalFailureInSubroutine -[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine -[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine -[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions - - 4 FAILED TESTS - YOU HAVE 1 DISABLED TEST - -Note: Google Test filter = *DISABLED_* -[==========] Running 1 test from 1 test case. -[----------] Global test environment set-up. -[----------] 1 test from DisabledTestsWarningTest -[ RUN ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning -[ OK ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning -[----------] Global test environment tear-down -[==========] 1 test from 1 test case ran. -[ PASSED ] 1 test. -Note: Google Test filter = PassingTest.* -Note: This is test shard 1 of 2. -[==========] Running 1 test from 1 test case. -[----------] Global test environment set-up. -[----------] 1 test from PassingTest -[ RUN ] PassingTest.PassingTest2 -[ OK ] PassingTest.PassingTest2 -[----------] Global test environment tear-down -[==========] 1 test from 1 test case ran. -[ PASSED ] 1 test. - - YOU HAVE 1 DISABLED TEST - diff --git a/testing/gtest/test/gtest_pred_impl_unittest.cc b/testing/gtest/test/gtest_pred_impl_unittest.cc index e7ee54b..35dc9bc 100644 --- a/testing/gtest/test/gtest_pred_impl_unittest.cc +++ b/testing/gtest/test/gtest_pred_impl_unittest.cc @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// This file is AUTOMATICALLY GENERATED on 10/02/2008 by command +// This file is AUTOMATICALLY GENERATED on 09/24/2010 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // Regression test for gtest_pred_impl.h @@ -49,8 +49,8 @@ #include <iostream> -#include <gtest/gtest.h> -#include <gtest/gtest-spi.h> +#include "gtest/gtest.h" +#include "gtest/gtest-spi.h" // A user-defined data type. struct Bool { @@ -103,11 +103,10 @@ testing::AssertionResult PredFormatFunction1(const char* e1, if (PredFunction1(v1)) return testing::AssertionSuccess(); - testing::Message msg; - msg << e1 + return testing::AssertionFailure() + << e1 << " is expected to be positive, but evaluates to " << v1 << "."; - return testing::AssertionFailure(msg); } // A unary predicate-formatter functor. @@ -494,11 +493,10 @@ testing::AssertionResult PredFormatFunction2(const char* e1, if (PredFunction2(v1, v2)) return testing::AssertionSuccess(); - testing::Message msg; - msg << e1 << " + " << e2 + return testing::AssertionFailure() + << e1 << " + " << e2 << " is expected to be positive, but evaluates to " << v1 + v2 << "."; - return testing::AssertionFailure(msg); } // A binary predicate-formatter functor. @@ -927,11 +925,10 @@ testing::AssertionResult PredFormatFunction3(const char* e1, if (PredFunction3(v1, v2, v3)) return testing::AssertionSuccess(); - testing::Message msg; - msg << e1 << " + " << e2 << " + " << e3 + return testing::AssertionFailure() + << e1 << " + " << e2 << " + " << e3 << " is expected to be positive, but evaluates to " << v1 + v2 + v3 << "."; - return testing::AssertionFailure(msg); } // A ternary predicate-formatter functor. @@ -1402,11 +1399,10 @@ testing::AssertionResult PredFormatFunction4(const char* e1, if (PredFunction4(v1, v2, v3, v4)) return testing::AssertionSuccess(); - testing::Message msg; - msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 + return testing::AssertionFailure() + << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " is expected to be positive, but evaluates to " << v1 + v2 + v3 + v4 << "."; - return testing::AssertionFailure(msg); } // A 4-ary predicate-formatter functor. @@ -1919,11 +1915,10 @@ testing::AssertionResult PredFormatFunction5(const char* e1, if (PredFunction5(v1, v2, v3, v4, v5)) return testing::AssertionSuccess(); - testing::Message msg; - msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 + return testing::AssertionFailure() + << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 << " is expected to be positive, but evaluates to " << v1 + v2 + v3 + v4 + v5 << "."; - return testing::AssertionFailure(msg); } // A 5-ary predicate-formatter functor. diff --git a/testing/gtest/test/gtest_prod_test.cc b/testing/gtest/test/gtest_prod_test.cc index bc3201d..060abce 100644 --- a/testing/gtest/test/gtest_prod_test.cc +++ b/testing/gtest/test/gtest_prod_test.cc @@ -31,7 +31,7 @@ // // Unit test for include/gtest/gtest_prod.h. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include "test/production.h" // Tests that private members can be accessed from a TEST declared as diff --git a/testing/gtest/test/gtest_repeat_test.cc b/testing/gtest/test/gtest_repeat_test.cc index df6868b..ff9063a 100644 --- a/testing/gtest/test/gtest_repeat_test.cc +++ b/testing/gtest/test/gtest_repeat_test.cc @@ -33,7 +33,7 @@ #include <stdlib.h> #include <iostream> -#include <gtest/gtest.h> +#include "gtest/gtest.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is diff --git a/testing/gtest/test/gtest_shuffle_test_.cc b/testing/gtest/test/gtest_shuffle_test_.cc index 53ecf77..0752789 100644 --- a/testing/gtest/test/gtest_shuffle_test_.cc +++ b/testing/gtest/test/gtest_shuffle_test_.cc @@ -31,7 +31,7 @@ // Verifies that test shuffling works. -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace { diff --git a/testing/gtest/test/gtest_sole_header_test.cc b/testing/gtest/test/gtest_sole_header_test.cc index de91e80..ccd091a 100644 --- a/testing/gtest/test/gtest_sole_header_test.cc +++ b/testing/gtest/test/gtest_sole_header_test.cc @@ -32,7 +32,7 @@ // This test verifies that it's possible to use Google Test by including // the gtest.h header file alone. -#include <gtest/gtest.h> +#include "gtest/gtest.h" namespace { diff --git a/testing/gtest/test/gtest_stress_test.cc b/testing/gtest/test/gtest_stress_test.cc index f5af78c..4e7d9bf 100644 --- a/testing/gtest/test/gtest_stress_test.cc +++ b/testing/gtest/test/gtest_stress_test.cc @@ -32,7 +32,7 @@ // Tests that SCOPED_TRACE() and various Google Test assertions can be // used in a large number of threads concurrently. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include <iostream> #include <vector> diff --git a/testing/gtest/test/gtest_throw_on_failure_ex_test.cc b/testing/gtest/test/gtest_throw_on_failure_ex_test.cc index 8bf9dc9..8d46c76 100644 --- a/testing/gtest/test/gtest_throw_on_failure_ex_test.cc +++ b/testing/gtest/test/gtest_throw_on_failure_ex_test.cc @@ -31,7 +31,7 @@ // Tests Google Test's throw-on-failure mode with exceptions enabled. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include <stdlib.h> #include <stdio.h> diff --git a/testing/gtest/test/gtest_throw_on_failure_test_.cc b/testing/gtest/test/gtest_throw_on_failure_test_.cc index 88fbd5a..03776ec 100644 --- a/testing/gtest/test/gtest_throw_on_failure_test_.cc +++ b/testing/gtest/test/gtest_throw_on_failure_test_.cc @@ -35,7 +35,7 @@ // invoked by gtest_throw_on_failure_test.py, and is expected to exit // with non-zero in the throw-on-failure mode or 0 otherwise. -#include <gtest/gtest.h> +#include "gtest/gtest.h" int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); diff --git a/testing/gtest/test/gtest_uninitialized_test_.cc b/testing/gtest/test/gtest_uninitialized_test_.cc index e8b2aa8..4431698 100644 --- a/testing/gtest/test/gtest_uninitialized_test_.cc +++ b/testing/gtest/test/gtest_uninitialized_test_.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) -#include <gtest/gtest.h> +#include "gtest/gtest.h" TEST(DummyTest, Dummy) { // This test doesn't verify anything. We just need it to create a diff --git a/testing/gtest/test/gtest_unittest.cc b/testing/gtest/test/gtest_unittest.cc index 40049ae..cb189a3 100644 --- a/testing/gtest/test/gtest_unittest.cc +++ b/testing/gtest/test/gtest_unittest.cc @@ -32,7 +32,7 @@ // Tests for Google Test itself. This verifies that the basic constructs of // Google Test work. -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include <vector> // Verifies that the command line flag variables can be accessed @@ -52,11 +52,12 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { || testing::GTEST_FLAG(show_internal_stack_frames) || testing::GTEST_FLAG(shuffle) || testing::GTEST_FLAG(stack_trace_depth) > 0 + || testing::GTEST_FLAG(stream_result_to) != "unknown" || testing::GTEST_FLAG(throw_on_failure); EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. } -#include <gtest/gtest-spi.h> +#include "gtest/gtest-spi.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is @@ -125,6 +126,7 @@ using testing::GTEST_FLAG(repeat); using testing::GTEST_FLAG(show_internal_stack_frames); using testing::GTEST_FLAG(shuffle); using testing::GTEST_FLAG(stack_trace_depth); +using testing::GTEST_FLAG(stream_result_to); using testing::GTEST_FLAG(throw_on_failure); using testing::IsNotSubstring; using testing::IsSubstring; @@ -178,6 +180,7 @@ using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; using testing::internal::Shuffle; using testing::internal::ShuffleRange; +using testing::internal::SkipPrefix; using testing::internal::StreamableToString; using testing::internal::String; using testing::internal::TestEventListenersAccessor; @@ -190,19 +193,15 @@ using testing::internal::kReference; using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::scoped_ptr; -#if GTEST_HAS_STREAM_REDIRECTION_ +#if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; -#endif // GTEST_HAS_STREAM_REDIRECTION_ +#endif #if GTEST_IS_THREADSAFE using testing::internal::ThreadWithParam; #endif -#if GTEST_HAS_PROTOBUF_ -using ::testing::internal::TestMessage; -#endif // GTEST_HAS_PROTOBUF_ - class TestingVector : public std::vector<int> { }; @@ -373,7 +372,11 @@ TEST(CodePointToUtf8Test, CanEncode8To11Bits) { EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer)); // 101 0111 0110 => 110-10101 10-110110 - EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer)); + // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints + // in wide strings and wide chars. In order to accomodate them, we have to + // introduce such character constants as integers. + EXPECT_STREQ("\xD5\xB6", + CodePointToUtf8(static_cast<wchar_t>(0x576), buffer)); } // Tests that Unicode code-points that have 12 to 16 bits are encoded @@ -381,10 +384,12 @@ TEST(CodePointToUtf8Test, CanEncode8To11Bits) { TEST(CodePointToUtf8Test, CanEncode12To16Bits) { char buffer[32]; // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 - EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer)); + EXPECT_STREQ("\xE0\xA3\x93", + CodePointToUtf8(static_cast<wchar_t>(0x8D3), buffer)); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 - EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer)); + EXPECT_STREQ("\xEC\x9D\x8D", + CodePointToUtf8(static_cast<wchar_t>(0xC74D), buffer)); } #if !GTEST_WIDE_STRING_USES_UTF16_ @@ -439,20 +444,23 @@ TEST(WideStringToUtf8Test, CanEncode8To11Bits) { EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); // 101 0111 0110 => 110-10101 10-110110 - EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str()); - EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str()); + const wchar_t s[] = { 0x576, '\0' }; + EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); + EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); } // Tests that Unicode code-points that have 12 to 16 bits are encoded // as 1110xxxx 10xxxxxx 10xxxxxx. TEST(WideStringToUtf8Test, CanEncode12To16Bits) { // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 - EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str()); - EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str()); + const wchar_t s1[] = { 0x8D3, '\0' }; + EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); + EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 - EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str()); - EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str()); + const wchar_t s2[] = { 0xC74D, '\0' }; + EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); + EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); } // Tests that the conversion stops when the function encounters \0 character. @@ -466,7 +474,6 @@ TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); } - #if !GTEST_WIDE_STRING_USES_UTF16_ // Tests that Unicode code-points that have 17 to 21 bits are encoded // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile @@ -490,25 +497,29 @@ TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { // Tests that surrogate pairs are encoded correctly on the systems using // UTF-16 encoding in the wide strings. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { - EXPECT_STREQ("\xF0\x90\x90\x80", - WideStringToUtf8(L"\xD801\xDC00", -1).c_str()); + const wchar_t s[] = { 0xD801, 0xDC00, '\0' }; + EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); } // Tests that encoding an invalid UTF-16 surrogate pair // generates the expected result. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { // Leading surrogate is at the end of the string. - EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str()); + const wchar_t s1[] = { 0xD800, '\0' }; + EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); // Leading surrogate is not followed by the trailing surrogate. - EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str()); + const wchar_t s2[] = { 0xD800, 'M', '\0' }; + EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); // Trailing surrogate appearas without a leading surrogate. - EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str()); + const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' }; + EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ // Tests that codepoint concatenation works correctly. #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { + const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; EXPECT_STREQ( "\xF4\x88\x98\xB4" "\xEC\x9D\x8D" @@ -516,13 +527,14 @@ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { "\xD5\xB6" "\xE0\xA3\x93" "\xF4\x88\x98\xB4", - WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str()); + WideStringToUtf8(s, -1).c_str()); } #else TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { + const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'}; EXPECT_STREQ( "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", - WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str()); + WideStringToUtf8(s, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ @@ -1336,6 +1348,17 @@ TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure."); } +#if GTEST_HAS_GLOBAL_STRING +TEST_F(ExpectFatalFailureTest, AcceptsStringObject) { + EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure.")); +} +#endif + +TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) { + EXPECT_FATAL_FAILURE(AddFatalFailure(), + ::std::string("Expected fatal failure.")); +} + TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { // We have another test below to verify that the macro catches fatal // failures generated on another thread. @@ -1413,6 +1436,18 @@ TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { "Expected non-fatal failure."); } +#if GTEST_HAS_GLOBAL_STRING +TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) { + EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), + ::string("Expected non-fatal failure.")); +} +#endif + +TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { + EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), + ::std::string("Expected non-fatal failure.")); +} + TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { // We have another test below to verify that the macro catches // non-fatal failures generated on another thread. @@ -1717,6 +1752,7 @@ class GTestFlagSaverTest : public Test { GTEST_FLAG(repeat) = 1; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; + GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG(throw_on_failure) = false; } @@ -1743,6 +1779,7 @@ class GTestFlagSaverTest : public Test { EXPECT_EQ(1, GTEST_FLAG(repeat)); EXPECT_FALSE(GTEST_FLAG(shuffle)); EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth)); + EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str()); EXPECT_FALSE(GTEST_FLAG(throw_on_failure)); GTEST_FLAG(also_run_disabled_tests) = true; @@ -1758,6 +1795,7 @@ class GTestFlagSaverTest : public Test { GTEST_FLAG(repeat) = 100; GTEST_FLAG(shuffle) = true; GTEST_FLAG(stack_trace_depth) = 1; + GTEST_FLAG(stream_result_to) = "localhost:1234"; GTEST_FLAG(throw_on_failure) = true; } private: @@ -3766,6 +3804,17 @@ TEST(AssertionTest, ExpectWorksWithUncopyableObject) { "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); } +enum NamedEnum { + kE1 = 0, + kE2 = 1, +}; + +TEST(AssertionTest, NamedEnum) { + EXPECT_EQ(kE1, kE1); + EXPECT_LT(kE1, kE2); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1"); +} // The version of gcc used in XCode 2.2 has a bug and doesn't allow // anonymous enums in assertions. Therefore the following test is not @@ -3775,7 +3824,7 @@ TEST(AssertionTest, ExpectWorksWithUncopyableObject) { // Tests using assertions with anonymous enums. enum { - CASE_A = -1, + kCaseA = -1, #if GTEST_OS_LINUX // We want to test the case where the size of the anonymous enum is // larger than sizeof(int), to make sure our implementation of the @@ -3783,37 +3832,44 @@ enum { // (incorrectly) doesn't allow an enum value to exceed the range of // an int, so this has to be conditionally compiled. // - // On Linux, CASE_B and CASE_A have the same value when truncated to + // On Linux, kCaseB and kCaseA have the same value when truncated to // int size. We want to test whether this will confuse the // assertions. - CASE_B = testing::internal::kMaxBiggestInt, + kCaseB = testing::internal::kMaxBiggestInt, #else - CASE_B = INT_MAX, + kCaseB = INT_MAX, #endif // GTEST_OS_LINUX + kCaseC = 42, }; TEST(AssertionTest, AnonymousEnum) { #if GTEST_OS_LINUX - EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B)); + EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB)); #endif // GTEST_OS_LINUX - EXPECT_EQ(CASE_A, CASE_A); - EXPECT_NE(CASE_A, CASE_B); - EXPECT_LT(CASE_A, CASE_B); - EXPECT_LE(CASE_A, CASE_B); - EXPECT_GT(CASE_B, CASE_A); - EXPECT_GE(CASE_A, CASE_A); - EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B), - "(CASE_A) >= (CASE_B)"); - - ASSERT_EQ(CASE_A, CASE_A); - ASSERT_NE(CASE_A, CASE_B); - ASSERT_LT(CASE_A, CASE_B); - ASSERT_LE(CASE_A, CASE_B); - ASSERT_GT(CASE_B, CASE_A); - ASSERT_GE(CASE_A, CASE_A); - EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B), - "Value of: CASE_B"); + EXPECT_EQ(kCaseA, kCaseA); + EXPECT_NE(kCaseA, kCaseB); + EXPECT_LT(kCaseA, kCaseB); + EXPECT_LE(kCaseA, kCaseB); + EXPECT_GT(kCaseB, kCaseA); + EXPECT_GE(kCaseA, kCaseA); + EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), + "(kCaseA) >= (kCaseB)"); + EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), + "-1 vs 42"); + + ASSERT_EQ(kCaseA, kCaseA); + ASSERT_NE(kCaseA, kCaseB); + ASSERT_LT(kCaseA, kCaseB); + ASSERT_LE(kCaseA, kCaseB); + ASSERT_GT(kCaseB, kCaseA); + ASSERT_GE(kCaseA, kCaseA); + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), + "Value of: kCaseB"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), + "Actual: 42"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), + "Which is: -1"); } #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) @@ -4392,6 +4448,21 @@ TEST(MacroTest, ADD_FAILURE) { EXPECT_FALSE(aborted); } +// Tests ADD_FAILURE_AT. +TEST(MacroTest, ADD_FAILURE_AT) { + // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and + // the failure message contains the user-streamed part. + EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!"); + + // Verifies that the user-streamed part is optional. + EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed"); + + // Unfortunately, we cannot verify that the failure message contains + // the right file path and line number the same way, as + // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and + // line number. Instead, we do that in gtest_output_test_.cc. +} + // Tests FAIL. TEST(MacroTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL(), @@ -4461,8 +4532,8 @@ TEST(EqAssertionTest, WideChar) { wchar = L'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar"); - wchar = L'\x8119'; - EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar), + wchar = 0x8119; + EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar), "Value of: wchar"); } @@ -4500,20 +4571,22 @@ TEST(EqAssertionTest, StdString) { // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, StdWideString) { - // Compares an std::wstring to a const wchar_t* that has identical - // content. - EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119"); - // Compares two identical std::wstrings. const ::std::wstring wstr1(L"A * in the middle"); const ::std::wstring wstr2(wstr1); ASSERT_EQ(wstr1, wstr2); + // Compares an std::wstring to a const wchar_t* that has identical + // content. + const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; + EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); + // Compares an std::wstring to a const wchar_t* that has different // content. + const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120"); - }, "L\"Test\\x8120\""); + EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); + }, "kTestX8120"); // Compares two std::wstrings that have different contents, one of // which having a NUL character in the middle. @@ -4565,18 +4638,20 @@ TEST(EqAssertionTest, GlobalString) { // Tests using ::wstring values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, GlobalWideString) { - // Compares a const wchar_t* to a ::wstring that has identical content. - ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119")); - // Compares two identical ::wstrings. static const ::wstring wstr1(L"A * in the middle"); static const ::wstring wstr2(wstr1); EXPECT_EQ(wstr1, wstr2); + // Compares a const wchar_t* to a ::wstring that has identical content. + const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; + ASSERT_EQ(kTestX8119, ::wstring(kTestX8119)); + // Compares a const wchar_t* to a ::wstring that has different // content. + const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119")); + EXPECT_EQ(kTestX8120, ::wstring(kTestX8119)); }, "Test\\x8119"); // Compares a wchar_t* to a ::wstring that has different content. @@ -4651,6 +4726,65 @@ TEST(EqAssertionTest, OtherPointer) { "0x1234"); } +// A class that supports binary comparison operators but not streaming. +class UnprintableChar { + public: + explicit UnprintableChar(char ch) : char_(ch) {} + + bool operator==(const UnprintableChar& rhs) const { + return char_ == rhs.char_; + } + bool operator!=(const UnprintableChar& rhs) const { + return char_ != rhs.char_; + } + bool operator<(const UnprintableChar& rhs) const { + return char_ < rhs.char_; + } + bool operator<=(const UnprintableChar& rhs) const { + return char_ <= rhs.char_; + } + bool operator>(const UnprintableChar& rhs) const { + return char_ > rhs.char_; + } + bool operator>=(const UnprintableChar& rhs) const { + return char_ >= rhs.char_; + } + + private: + char char_; +}; + +// Tests that ASSERT_EQ() and friends don't require the arguments to +// be printable. +TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) { + const UnprintableChar x('x'), y('y'); + ASSERT_EQ(x, x); + EXPECT_NE(x, y); + ASSERT_LT(x, y); + EXPECT_LE(x, y); + ASSERT_GT(y, x); + EXPECT_GE(x, x); + + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>"); + EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>"); + EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>"); + EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>"); + + // Code tested by EXPECT_FATAL_FAILURE cannot reference local + // variables, so we have to write UnprintableChar('x') instead of x. + EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')), + "1-byte object <78>"); + EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), + "1-byte object <78>"); + EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), + "1-byte object <79>"); + EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), + "1-byte object <78>"); + EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), + "1-byte object <79>"); +} + // Tests the FRIEND_TEST macro. // This class has a private member we want to test. We will test it @@ -5049,6 +5183,7 @@ struct Flags { repeat(1), shuffle(false), stack_trace_depth(kMaxStackTraceDepth), + stream_result_to(""), throw_on_failure(false) {} // Factory methods. @@ -5149,6 +5284,14 @@ struct Flags { return flags; } + // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has + // the given value. + static Flags StreamResultTo(const char* stream_result_to) { + Flags flags; + flags.stream_result_to = stream_result_to; + return flags; + } + // Creates a Flags struct where the gtest_throw_on_failure flag has // the given value. static Flags ThrowOnFailure(bool throw_on_failure) { @@ -5170,6 +5313,7 @@ struct Flags { Int32 repeat; bool shuffle; Int32 stack_trace_depth; + const char* stream_result_to; bool throw_on_failure; }; @@ -5190,6 +5334,7 @@ class InitGoogleTestTest : public Test { GTEST_FLAG(repeat) = 1; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; + GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG(throw_on_failure) = false; } @@ -5218,8 +5363,10 @@ class InitGoogleTestTest : public Test { EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed)); EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle)); - EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth)); + EXPECT_STREQ(expected.stream_result_to, + GTEST_FLAG(stream_result_to).c_str()); + EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); } // Parses a command line (specified by argc1 and argv1), then @@ -5232,16 +5379,16 @@ class InitGoogleTestTest : public Test { const bool saved_help_flag = ::testing::internal::g_help_flag; ::testing::internal::g_help_flag = false; -#if GTEST_HAS_STREAM_REDIRECTION_ +#if GTEST_HAS_STREAM_REDIRECTION CaptureStdout(); -#endif // GTEST_HAS_STREAM_REDIRECTION_ +#endif // Parses the command line. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); -#if GTEST_HAS_STREAM_REDIRECTION_ +#if GTEST_HAS_STREAM_REDIRECTION const String captured_stdout = GetCapturedStdout(); -#endif // GTEST_HAS_STREAM_REDIRECTION_ +#endif // Verifies the flag values. CheckFlags(expected); @@ -5254,7 +5401,7 @@ class InitGoogleTestTest : public Test { // help message for the flags it recognizes. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); -#if GTEST_HAS_STREAM_REDIRECTION_ +#if GTEST_HAS_STREAM_REDIRECTION const char* const expected_help_fragment = "This program contains tests written using"; if (should_print_help) { @@ -5263,7 +5410,7 @@ class InitGoogleTestTest : public Test { EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment, captured_stdout); } -#endif // GTEST_HAS_STREAM_REDIRECTION_ +#endif // GTEST_HAS_STREAM_REDIRECTION ::testing::internal::g_help_flag = saved_help_flag; } @@ -5880,6 +6027,22 @@ TEST_F(InitGoogleTestTest, StackTraceDepth) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); } +TEST_F(InitGoogleTestTest, StreamResultTo) { + const char* argv[] = { + "foo.exe", + "--gtest_stream_result_to=localhost:1234", + NULL + }; + + const char* argv2[] = { + "foo.exe", + NULL + }; + + GTEST_TEST_PARSING_FLAGS_( + argv, argv2, Flags::StreamResultTo("localhost:1234"), false); +} + // Tests parsing --gtest_throw_on_failure. TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) { const char* argv[] = { @@ -6743,6 +6906,41 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. // GTEST_FAIL is the same as FAIL. EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure", "An expected failure"); + + // GTEST_ASSERT_XY is the same as ASSERT_XY. + + GTEST_ASSERT_EQ(0, 0); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure", + "An expected failure"); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure", + "An expected failure"); + + GTEST_ASSERT_NE(0, 1); + GTEST_ASSERT_NE(1, 0); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure", + "An expected failure"); + + GTEST_ASSERT_LE(0, 0); + GTEST_ASSERT_LE(0, 1); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure", + "An expected failure"); + + GTEST_ASSERT_LT(0, 1); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure", + "An expected failure"); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure", + "An expected failure"); + + GTEST_ASSERT_GE(0, 0); + GTEST_ASSERT_GE(1, 0); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure", + "An expected failure"); + + GTEST_ASSERT_GT(1, 0); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure", + "An expected failure"); + EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure", + "An expected failure"); } // Tests for internal utilities necessary for implementation of the universal @@ -6760,13 +6958,10 @@ TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { } // Tests that IsAProtocolMessage<T>::value is true when T is -// ProtocolMessage or a sub-class of it. +// proto2::Message or a sub-class of it. TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value); -#if GTEST_HAS_PROTOBUF_ - EXPECT_TRUE(IsAProtocolMessage<const TestMessage>::value); -#endif // GTEST_HAS_PROTOBUF_ } // Tests that IsAProtocolMessage<T>::value is false when T is neither @@ -7075,3 +7270,29 @@ TEST(NativeArrayTest, WorksForTwoDimensionalArray) { ASSERT_EQ(2U, na.size()); EXPECT_EQ(a, na.begin()); } + +// Tests SkipPrefix(). + +TEST(SkipPrefixTest, SkipsWhenPrefixMatches) { + const char* const str = "hello"; + + const char* p = str; + EXPECT_TRUE(SkipPrefix("", &p)); + EXPECT_EQ(str, p); + + p = str; + EXPECT_TRUE(SkipPrefix("hell", &p)); + EXPECT_EQ(str + 4, p); +} + +TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { + const char* const str = "world"; + + const char* p = str; + EXPECT_FALSE(SkipPrefix("W", &p)); + EXPECT_EQ(str, p); + + p = str; + EXPECT_FALSE(SkipPrefix("world!", &p)); + EXPECT_EQ(str, p); +} diff --git a/testing/gtest/test/gtest_xml_outfile1_test_.cc b/testing/gtest/test/gtest_xml_outfile1_test_.cc index 664baad..531ced4 100644 --- a/testing/gtest/test/gtest_xml_outfile1_test_.cc +++ b/testing/gtest/test/gtest_xml_outfile1_test_.cc @@ -32,7 +32,7 @@ // gtest_xml_outfile1_test_ writes some xml via TestProperty used by // gtest_xml_outfiles_test.py -#include <gtest/gtest.h> +#include "gtest/gtest.h" class PropertyOne : public testing::Test { protected: diff --git a/testing/gtest/test/gtest_xml_outfile2_test_.cc b/testing/gtest/test/gtest_xml_outfile2_test_.cc index 3411a3d..7b400b2 100644 --- a/testing/gtest/test/gtest_xml_outfile2_test_.cc +++ b/testing/gtest/test/gtest_xml_outfile2_test_.cc @@ -32,7 +32,7 @@ // gtest_xml_outfile2_test_ writes some xml via TestProperty used by // gtest_xml_outfiles_test.py -#include <gtest/gtest.h> +#include "gtest/gtest.h" class PropertyTwo : public testing::Test { protected: diff --git a/testing/gtest/test/gtest_xml_output_unittest_.cc b/testing/gtest/test/gtest_xml_output_unittest_.cc index fc07ef4..693ffb9 100644 --- a/testing/gtest/test/gtest_xml_output_unittest_.cc +++ b/testing/gtest/test/gtest_xml_output_unittest_.cc @@ -38,7 +38,7 @@ // This program will be invoked from a Python unit test. Don't run it // directly. -#include <gtest/gtest.h> +#include "gtest/gtest.h" using ::testing::InitGoogleTest; using ::testing::TestEventListeners; diff --git a/testing/gtest/test/production.h b/testing/gtest/test/production.h index 8f16fff..98fd5e4 100644 --- a/testing/gtest/test/production.h +++ b/testing/gtest/test/production.h @@ -34,7 +34,7 @@ #ifndef GTEST_TEST_PRODUCTION_H_ #define GTEST_TEST_PRODUCTION_H_ -#include <gtest/gtest_prod.h> +#include "gtest/gtest_prod.h" class PrivateCode { public: diff --git a/testing/gtest/test/run_tests_util.py b/testing/gtest/test/run_tests_util.py deleted file mode 100755 index a123569..0000000 --- a/testing/gtest/test/run_tests_util.py +++ /dev/null @@ -1,466 +0,0 @@ -# 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. - -"""Provides facilities for running SCons-built Google Test/Mock tests.""" - - -import optparse -import os -import re -import sets -import sys - -try: - # subrocess module is a preferable way to invoke subprocesses but it may - # not be available on MacOS X 10.4. - # Suppresses the 'Import not at the top of the file' lint complaint. - # pylint: disable-msg=C6204 - import subprocess -except ImportError: - subprocess = None - -HELP_MSG = """Runs the specified tests for %(proj)s. - -SYNOPSIS - run_tests.py [OPTION]... [BUILD_DIR]... [TEST]... - -DESCRIPTION - Runs the specified tests (either binary or Python), and prints a - summary of the results. BUILD_DIRS will be used to search for the - binaries. If no TESTs are specified, all binary tests found in - BUILD_DIRs and all Python tests found in the directory test/ (in the - %(proj)s root) are run. - - TEST is a name of either a binary or a Python test. A binary test is - an executable file named *_test or *_unittest (with the .exe - extension on Windows) A Python test is a script named *_test.py or - *_unittest.py. - -OPTIONS - -h, --help - Print this help message. - -c CONFIGURATIONS - Specify build directories via build configurations. - CONFIGURATIONS is either a comma-separated list of build - configurations or 'all'. Each configuration is equivalent to - adding 'scons/build/<configuration>/%(proj)s/scons' to BUILD_DIRs. - Specifying -c=all is equivalent to providing all directories - listed in KNOWN BUILD DIRECTORIES section below. - -a - Equivalent to -c=all - -b - Equivalent to -c=all with the exception that the script will not - fail if some of the KNOWN BUILD DIRECTORIES do not exists; the - script will simply not run the tests there. 'b' stands for - 'built directories'. - -RETURN VALUE - Returns 0 if all tests are successful; otherwise returns 1. - -EXAMPLES - run_tests.py - Runs all tests for the default build configuration. - run_tests.py -a - Runs all tests with binaries in KNOWN BUILD DIRECTORIES. - run_tests.py -b - Runs all tests in KNOWN BUILD DIRECTORIES that have been - built. - run_tests.py foo/ - Runs all tests in the foo/ directory and all Python tests in - the directory test. The Python tests are instructed to look - for binaries in foo/. - run_tests.py bar_test.exe test/baz_test.exe foo/ bar/ - Runs foo/bar_test.exe, bar/bar_test.exe, foo/baz_test.exe, and - bar/baz_test.exe. - run_tests.py foo bar test/foo_test.py - Runs test/foo_test.py twice instructing it to look for its - test binaries in the directories foo and bar, - correspondingly. - -KNOWN BUILD DIRECTORIES - run_tests.py knows about directories where the SCons build script - deposits its products. These are the directories where run_tests.py - will be looking for its binaries. Currently, %(proj)s's SConstruct file - defines them as follows (the default build directory is the first one - listed in each group): - On Windows: - <%(proj)s root>/scons/build/win-dbg8/%(proj)s/scons/ - <%(proj)s root>/scons/build/win-opt8/%(proj)s/scons/ - On Mac: - <%(proj)s root>/scons/build/mac-dbg/%(proj)s/scons/ - <%(proj)s root>/scons/build/mac-opt/%(proj)s/scons/ - On other platforms: - <%(proj)s root>/scons/build/dbg/%(proj)s/scons/ - <%(proj)s root>/scons/build/opt/%(proj)s/scons/""" - -IS_WINDOWS = os.name == 'nt' -IS_MAC = os.name == 'posix' and os.uname()[0] == 'Darwin' -IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0] - -# Definition of CONFIGS must match that of the build directory names in the -# SConstruct script. The first list item is the default build configuration. -if IS_WINDOWS: - CONFIGS = ('win-dbg8', 'win-opt8') -elif IS_MAC: - CONFIGS = ('mac-dbg', 'mac-opt') -else: - CONFIGS = ('dbg', 'opt') - -if IS_WINDOWS or IS_CYGWIN: - PYTHON_TEST_REGEX = re.compile(r'_(unit)?test\.py$', re.IGNORECASE) - BINARY_TEST_REGEX = re.compile(r'_(unit)?test(\.exe)?$', re.IGNORECASE) - BINARY_TEST_SEARCH_REGEX = re.compile(r'_(unit)?test\.exe$', re.IGNORECASE) -else: - PYTHON_TEST_REGEX = re.compile(r'_(unit)?test\.py$') - BINARY_TEST_REGEX = re.compile(r'_(unit)?test$') - BINARY_TEST_SEARCH_REGEX = BINARY_TEST_REGEX - - -def _GetGtestBuildDir(injected_os, script_dir, config): - """Calculates path to the Google Test SCons build directory.""" - - return injected_os.path.normpath(injected_os.path.join(script_dir, - 'scons/build', - config, - 'gtest/scons')) - - -def _GetConfigFromBuildDir(build_dir): - """Extracts the configuration name from the build directory.""" - - # We don't want to depend on build_dir containing the correct path - # separators. - m = re.match(r'.*[\\/]([^\\/]+)[\\/][^\\/]+[\\/]scons[\\/]?$', build_dir) - if m: - return m.group(1) - else: - print >>sys.stderr, ('%s is an invalid build directory that does not ' - 'correspond to any configuration.' % (build_dir,)) - return '' - - -# All paths in this script are either absolute or relative to the current -# working directory, unless otherwise specified. -class TestRunner(object): - """Provides facilities for running Python and binary tests for Google Test.""" - - def __init__(self, - script_dir, - build_dir_var_name='BUILD_DIR', - injected_os=os, - injected_subprocess=subprocess, - injected_build_dir_finder=_GetGtestBuildDir): - """Initializes a TestRunner instance. - - Args: - script_dir: File path to the calling script. - build_dir_var_name: Name of the env variable used to pass the - the build directory path to the invoked - tests. - injected_os: standard os module or a mock/stub for - testing. - injected_subprocess: standard subprocess module or a mock/stub - for testing - injected_build_dir_finder: function that determines the path to - the build directory. - """ - - self.os = injected_os - self.subprocess = injected_subprocess - self.build_dir_finder = injected_build_dir_finder - self.build_dir_var_name = build_dir_var_name - self.script_dir = script_dir - - def _GetBuildDirForConfig(self, config): - """Returns the build directory for a given configuration.""" - - return self.build_dir_finder(self.os, self.script_dir, config) - - def _Run(self, args): - """Runs the executable with given args (args[0] is the executable name). - - Args: - args: Command line arguments for the process. - - Returns: - Process's exit code if it exits normally, or -signal if the process is - killed by a signal. - """ - - if self.subprocess: - return self.subprocess.Popen(args).wait() - else: - return self.os.spawnv(self.os.P_WAIT, args[0], args) - - def _RunBinaryTest(self, test): - """Runs the binary test given its path. - - Args: - test: Path to the test binary. - - Returns: - Process's exit code if it exits normally, or -signal if the process is - killed by a signal. - """ - - return self._Run([test]) - - def _RunPythonTest(self, test, build_dir): - """Runs the Python test script with the specified build directory. - - Args: - test: Path to the test's Python script. - build_dir: Path to the directory where the test binary is to be found. - - Returns: - Process's exit code if it exits normally, or -signal if the process is - killed by a signal. - """ - - old_build_dir = self.os.environ.get(self.build_dir_var_name) - - try: - self.os.environ[self.build_dir_var_name] = build_dir - - # If this script is run on a Windows machine that has no association - # between the .py extension and a python interpreter, simply passing - # the script name into subprocess.Popen/os.spawn will not work. - print 'Running %s . . .' % (test,) - return self._Run([sys.executable, test]) - - finally: - if old_build_dir is None: - del self.os.environ[self.build_dir_var_name] - else: - self.os.environ[self.build_dir_var_name] = old_build_dir - - def _FindFilesByRegex(self, directory, regex): - """Returns files in a directory whose names match a regular expression. - - Args: - directory: Path to the directory to search for files. - regex: Regular expression to filter file names. - - Returns: - The list of the paths to the files in the directory. - """ - - return [self.os.path.join(directory, file_name) - for file_name in self.os.listdir(directory) - if re.search(regex, file_name)] - - # TODO(vladl@google.com): Implement parsing of scons/SConscript to run all - # tests defined there when no tests are specified. - # TODO(vladl@google.com): Update the docstring after the code is changed to - # try to test all builds defined in scons/SConscript. - def GetTestsToRun(self, - args, - named_configurations, - built_configurations, - available_configurations=CONFIGS, - python_tests_to_skip=None): - """Determines what tests should be run. - - Args: - args: The list of non-option arguments from the command line. - named_configurations: The list of configurations specified via -c or -a. - built_configurations: True if -b has been specified. - available_configurations: a list of configurations available on the - current platform, injectable for testing. - python_tests_to_skip: a collection of (configuration, python test name)s - that need to be skipped. - - Returns: - A tuple with 2 elements: the list of Python tests to run and the list of - binary tests to run. - """ - - if named_configurations == 'all': - named_configurations = ','.join(available_configurations) - - normalized_args = [self.os.path.normpath(arg) for arg in args] - - # A final list of build directories which will be searched for the test - # binaries. First, add directories specified directly on the command - # line. - build_dirs = filter(self.os.path.isdir, normalized_args) - - # Adds build directories specified via their build configurations using - # the -c or -a options. - if named_configurations: - build_dirs += [self._GetBuildDirForConfig(config) - for config in named_configurations.split(',')] - - # Adds KNOWN BUILD DIRECTORIES if -b is specified. - if built_configurations: - build_dirs += [self._GetBuildDirForConfig(config) - for config in available_configurations - if self.os.path.isdir(self._GetBuildDirForConfig(config))] - - # If no directories were specified either via -a, -b, -c, or directly, use - # the default configuration. - elif not build_dirs: - build_dirs = [self._GetBuildDirForConfig(available_configurations[0])] - - # Makes sure there are no duplications. - build_dirs = sets.Set(build_dirs) - - errors_found = False - listed_python_tests = [] # All Python tests listed on the command line. - listed_binary_tests = [] # All binary tests listed on the command line. - - test_dir = self.os.path.normpath(self.os.path.join(self.script_dir, 'test')) - - # Sifts through non-directory arguments fishing for any Python or binary - # tests and detecting errors. - for argument in sets.Set(normalized_args) - build_dirs: - if re.search(PYTHON_TEST_REGEX, argument): - python_path = self.os.path.join(test_dir, - self.os.path.basename(argument)) - if self.os.path.isfile(python_path): - listed_python_tests.append(python_path) - else: - sys.stderr.write('Unable to find Python test %s' % argument) - errors_found = True - elif re.search(BINARY_TEST_REGEX, argument): - # This script also accepts binary test names prefixed with test/ for - # the convenience of typing them (can use path completions in the - # shell). Strips test/ prefix from the binary test names. - listed_binary_tests.append(self.os.path.basename(argument)) - else: - sys.stderr.write('%s is neither test nor build directory' % argument) - errors_found = True - - if errors_found: - return None - - user_has_listed_tests = listed_python_tests or listed_binary_tests - - if user_has_listed_tests: - selected_python_tests = listed_python_tests - else: - selected_python_tests = self._FindFilesByRegex(test_dir, - PYTHON_TEST_REGEX) - - # TODO(vladl@google.com): skip unbuilt Python tests when -b is specified. - python_test_pairs = [] - for directory in build_dirs: - for test in selected_python_tests: - config = _GetConfigFromBuildDir(directory) - file_name = os.path.basename(test) - if python_tests_to_skip and (config, file_name) in python_tests_to_skip: - print ('NOTE: %s is skipped for configuration %s, as it does not ' - 'work there.' % (file_name, config)) - else: - python_test_pairs.append((directory, test)) - - binary_test_pairs = [] - for directory in build_dirs: - if user_has_listed_tests: - binary_test_pairs.extend( - [(directory, self.os.path.join(directory, test)) - for test in listed_binary_tests]) - else: - tests = self._FindFilesByRegex(directory, BINARY_TEST_SEARCH_REGEX) - binary_test_pairs.extend([(directory, test) for test in tests]) - - return (python_test_pairs, binary_test_pairs) - - def RunTests(self, python_tests, binary_tests): - """Runs Python and binary tests and reports results to the standard output. - - Args: - python_tests: List of Python tests to run in the form of tuples - (build directory, Python test script). - binary_tests: List of binary tests to run in the form of tuples - (build directory, binary file). - - Returns: - The exit code the program should pass into sys.exit(). - """ - - if python_tests or binary_tests: - results = [] - for directory, test in python_tests: - results.append((directory, - test, - self._RunPythonTest(test, directory) == 0)) - for directory, test in binary_tests: - results.append((directory, - self.os.path.basename(test), - self._RunBinaryTest(test) == 0)) - - failed = [(directory, test) - for (directory, test, success) in results - if not success] - print - print '%d tests run.' % len(results) - if failed: - print 'The following %d tests failed:' % len(failed) - for (directory, test) in failed: - print '%s in %s' % (test, directory) - return 1 - else: - print 'All tests passed!' - else: # No tests defined - print 'Nothing to test - no tests specified!' - - return 0 - - -def ParseArgs(project_name, argv=None, help_callback=None): - """Parses the options run_tests.py uses.""" - - # Suppresses lint warning on unused arguments. These arguments are - # required by optparse, even though they are unused. - # pylint: disable-msg=W0613 - def PrintHelp(option, opt, value, parser): - print HELP_MSG % {'proj': project_name} - sys.exit(1) - - parser = optparse.OptionParser() - parser.add_option('-c', - action='store', - dest='configurations', - default=None) - parser.add_option('-a', - action='store_const', - dest='configurations', - default=None, - const='all') - parser.add_option('-b', - action='store_const', - dest='built_configurations', - default=False, - const=True) - # Replaces the built-in help with ours. - parser.remove_option('-h') - parser.add_option('-h', '--help', - action='callback', - callback=help_callback or PrintHelp) - return parser.parse_args(argv) diff --git a/testing/gtest/test/run_tests_util_test.py b/testing/gtest/test/run_tests_util_test.py deleted file mode 100755 index 9c55726..0000000 --- a/testing/gtest/test/run_tests_util_test.py +++ /dev/null @@ -1,676 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2009 Google Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Tests for run_tests_util.py test runner script.""" - -__author__ = 'vladl@google.com (Vlad Losev)' - -import os -import re -import sets -import unittest - -import run_tests_util - - -GTEST_DBG_DIR = 'scons/build/dbg/gtest/scons' -GTEST_OPT_DIR = 'scons/build/opt/gtest/scons' -GTEST_OTHER_DIR = 'scons/build/other/gtest/scons' - - -def AddExeExtension(path): - """Appends .exe to the path on Windows or Cygwin.""" - - if run_tests_util.IS_WINDOWS or run_tests_util.IS_CYGWIN: - return path + '.exe' - else: - return path - - -class FakePath(object): - """A fake os.path module for testing.""" - - def __init__(self, current_dir=os.getcwd(), known_paths=None): - self.current_dir = current_dir - self.tree = {} - self.path_separator = os.sep - - # known_paths contains either absolute or relative paths. Relative paths - # are absolutized with self.current_dir. - if known_paths: - self._AddPaths(known_paths) - - def _AddPath(self, path): - ends_with_slash = path.endswith('/') - path = self.abspath(path) - if ends_with_slash: - path += self.path_separator - name_list = path.split(self.path_separator) - tree = self.tree - for name in name_list[:-1]: - if not name: - continue - if name in tree: - tree = tree[name] - else: - tree[name] = {} - tree = tree[name] - - name = name_list[-1] - if name: - if name in tree: - assert tree[name] == 1 - else: - tree[name] = 1 - - def _AddPaths(self, paths): - for path in paths: - self._AddPath(path) - - def PathElement(self, path): - """Returns an internal representation of directory tree entry for path.""" - tree = self.tree - name_list = self.abspath(path).split(self.path_separator) - for name in name_list: - if not name: - continue - tree = tree.get(name, None) - if tree is None: - break - - return tree - - # Silences pylint warning about using standard names. - # pylint: disable-msg=C6409 - def normpath(self, path): - return os.path.normpath(path) - - def abspath(self, path): - return self.normpath(os.path.join(self.current_dir, path)) - - def isfile(self, path): - return self.PathElement(self.abspath(path)) == 1 - - def isdir(self, path): - return type(self.PathElement(self.abspath(path))) == type(dict()) - - def basename(self, path): - return os.path.basename(path) - - def dirname(self, path): - return os.path.dirname(path) - - def join(self, *kargs): - return os.path.join(*kargs) - - -class FakeOs(object): - """A fake os module for testing.""" - P_WAIT = os.P_WAIT - - def __init__(self, fake_path_module): - self.path = fake_path_module - - # Some methods/attributes are delegated to the real os module. - self.environ = os.environ - - # pylint: disable-msg=C6409 - def listdir(self, path): - assert self.path.isdir(path) - return self.path.PathElement(path).iterkeys() - - def spawnv(self, wait, executable, *kargs): - assert wait == FakeOs.P_WAIT - return self.spawn_impl(executable, kargs) - - -class GetTestsToRunTest(unittest.TestCase): - """Exercises TestRunner.GetTestsToRun.""" - - def NormalizeGetTestsToRunResults(self, results): - """Normalizes path data returned from GetTestsToRun for comparison.""" - - def NormalizePythonTestPair(pair): - """Normalizes path data in the (directory, python_script) pair.""" - - return (os.path.normpath(pair[0]), os.path.normpath(pair[1])) - - def NormalizeBinaryTestPair(pair): - """Normalizes path data in the (directory, binary_executable) pair.""" - - directory, executable = map(os.path.normpath, pair) - - # On Windows and Cygwin, the test file names have the .exe extension, but - # they can be invoked either by name or by name+extension. Our test must - # accommodate both situations. - if run_tests_util.IS_WINDOWS or run_tests_util.IS_CYGWIN: - executable = re.sub(r'\.exe$', '', executable) - return (directory, executable) - - python_tests = sets.Set(map(NormalizePythonTestPair, results[0])) - binary_tests = sets.Set(map(NormalizeBinaryTestPair, results[1])) - return (python_tests, binary_tests) - - def AssertResultsEqual(self, results, expected): - """Asserts results returned by GetTestsToRun equal to expected results.""" - - self.assertEqual(self.NormalizeGetTestsToRunResults(results), - self.NormalizeGetTestsToRunResults(expected), - 'Incorrect set of tests returned:\n%s\nexpected:\n%s' % - (results, expected)) - - def setUp(self): - self.fake_os = FakeOs(FakePath( - current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)), - known_paths=[AddExeExtension(GTEST_DBG_DIR + '/gtest_unittest'), - AddExeExtension(GTEST_OPT_DIR + '/gtest_unittest'), - 'test/gtest_color_test.py'])) - self.fake_configurations = ['dbg', 'opt'] - self.test_runner = run_tests_util.TestRunner(script_dir='.', - injected_os=self.fake_os, - injected_subprocess=None) - - def testBinaryTestsOnly(self): - """Exercises GetTestsToRun with parameters designating binary tests only.""" - - # A default build. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_unittest'], - '', - False, - available_configurations=self.fake_configurations), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')])) - - # An explicitly specified directory. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'gtest_unittest'], - '', - False, - available_configurations=self.fake_configurations), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')])) - - # A particular configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_unittest'], - 'other', - False, - available_configurations=self.fake_configurations), - ([], - [(GTEST_OTHER_DIR, GTEST_OTHER_DIR + '/gtest_unittest')])) - - # All available configurations - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_unittest'], - 'all', - False, - available_configurations=self.fake_configurations), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'), - (GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')])) - - # All built configurations (unbuilt don't cause failure). - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_unittest'], - '', - True, - available_configurations=self.fake_configurations + ['unbuilt']), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'), - (GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')])) - - # A combination of an explicit directory and a configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'gtest_unittest'], - 'opt', - False, - available_configurations=self.fake_configurations), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'), - (GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')])) - - # Same test specified in an explicit directory and via a configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'gtest_unittest'], - 'dbg', - False, - available_configurations=self.fake_configurations), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')])) - - # All built configurations + explicit directory + explicit configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'gtest_unittest'], - 'opt', - True, - available_configurations=self.fake_configurations), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'), - (GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')])) - - def testPythonTestsOnly(self): - """Exercises GetTestsToRun with parameters designating Python tests only.""" - - # A default build. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_color_test.py'], - '', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - [])) - - # An explicitly specified directory. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'test/gtest_color_test.py'], - '', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - [])) - - # A particular configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_color_test.py'], - 'other', - False, - available_configurations=self.fake_configurations), - ([(GTEST_OTHER_DIR, 'test/gtest_color_test.py')], - [])) - - # All available configurations - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['test/gtest_color_test.py'], - 'all', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py'), - (GTEST_OPT_DIR, 'test/gtest_color_test.py')], - [])) - - # All built configurations (unbuilt don't cause failure). - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_color_test.py'], - '', - True, - available_configurations=self.fake_configurations + ['unbuilt']), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py'), - (GTEST_OPT_DIR, 'test/gtest_color_test.py')], - [])) - - # A combination of an explicit directory and a configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'gtest_color_test.py'], - 'opt', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py'), - (GTEST_OPT_DIR, 'test/gtest_color_test.py')], - [])) - - # Same test specified in an explicit directory and via a configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'gtest_color_test.py'], - 'dbg', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - [])) - - # All built configurations + explicit directory + explicit configuration. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [GTEST_DBG_DIR, 'gtest_color_test.py'], - 'opt', - True, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py'), - (GTEST_OPT_DIR, 'test/gtest_color_test.py')], - [])) - - def testCombinationOfBinaryAndPythonTests(self): - """Exercises GetTestsToRun with mixed binary/Python tests.""" - - # Use only default configuration for this test. - - # Neither binary nor Python tests are specified so find all. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [], - '', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')])) - - # Specifying both binary and Python tests. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_unittest', 'gtest_color_test.py'], - '', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')])) - - # Specifying binary tests suppresses Python tests. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_unittest'], - '', - False, - available_configurations=self.fake_configurations), - ([], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')])) - - # Specifying Python tests suppresses binary tests. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_color_test.py'], - '', - False, - available_configurations=self.fake_configurations), - ([(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - [])) - - def testIgnoresNonTestFiles(self): - """Verifies that GetTestsToRun ignores non-test files in the filesystem.""" - - self.fake_os = FakeOs(FakePath( - current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)), - known_paths=[AddExeExtension(GTEST_DBG_DIR + '/gtest_nontest'), - 'test/'])) - self.test_runner = run_tests_util.TestRunner(script_dir='.', - injected_os=self.fake_os, - injected_subprocess=None) - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [], - '', - True, - available_configurations=self.fake_configurations), - ([], [])) - - def testWorksFromDifferentDir(self): - """Exercises GetTestsToRun from a directory different from run_test.py's.""" - - # Here we simulate an test script in directory /d/ called from the - # directory /a/b/c/. - self.fake_os = FakeOs(FakePath( - current_dir=os.path.abspath('/a/b/c'), - known_paths=[ - '/a/b/c/', - AddExeExtension('/d/' + GTEST_DBG_DIR + '/gtest_unittest'), - AddExeExtension('/d/' + GTEST_OPT_DIR + '/gtest_unittest'), - '/d/test/gtest_color_test.py'])) - self.fake_configurations = ['dbg', 'opt'] - self.test_runner = run_tests_util.TestRunner(script_dir='/d/', - injected_os=self.fake_os, - injected_subprocess=None) - # A binary test. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_unittest'], - '', - False, - available_configurations=self.fake_configurations), - ([], - [('/d/' + GTEST_DBG_DIR, '/d/' + GTEST_DBG_DIR + '/gtest_unittest')])) - - # A Python test. - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - ['gtest_color_test.py'], - '', - False, - available_configurations=self.fake_configurations), - ([('/d/' + GTEST_DBG_DIR, '/d/test/gtest_color_test.py')], [])) - - def testNonTestBinary(self): - """Exercises GetTestsToRun with a non-test parameter.""" - - self.assert_( - not self.test_runner.GetTestsToRun( - ['gtest_unittest_not_really'], - '', - False, - available_configurations=self.fake_configurations)) - - def testNonExistingPythonTest(self): - """Exercises GetTestsToRun with a non-existent Python test parameter.""" - - self.assert_( - not self.test_runner.GetTestsToRun( - ['nonexistent_test.py'], - '', - False, - available_configurations=self.fake_configurations)) - - if run_tests_util.IS_WINDOWS or run_tests_util.IS_CYGWIN: - - def testDoesNotPickNonExeFilesOnWindows(self): - """Verifies that GetTestsToRun does not find _test files on Windows.""" - - self.fake_os = FakeOs(FakePath( - current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)), - known_paths=['/d/' + GTEST_DBG_DIR + '/gtest_test', 'test/'])) - self.test_runner = run_tests_util.TestRunner(script_dir='.', - injected_os=self.fake_os, - injected_subprocess=None) - self.AssertResultsEqual( - self.test_runner.GetTestsToRun( - [], - '', - True, - available_configurations=self.fake_configurations), - ([], [])) - - -class RunTestsTest(unittest.TestCase): - """Exercises TestRunner.RunTests.""" - - def SpawnSuccess(self, unused_executable, unused_argv): - """Fakes test success by returning 0 as an exit code.""" - - self.num_spawn_calls += 1 - return 0 - - def SpawnFailure(self, unused_executable, unused_argv): - """Fakes test success by returning 1 as an exit code.""" - - self.num_spawn_calls += 1 - return 1 - - def setUp(self): - self.fake_os = FakeOs(FakePath( - current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)), - known_paths=[ - AddExeExtension(GTEST_DBG_DIR + '/gtest_unittest'), - AddExeExtension(GTEST_OPT_DIR + '/gtest_unittest'), - 'test/gtest_color_test.py'])) - self.fake_configurations = ['dbg', 'opt'] - self.test_runner = run_tests_util.TestRunner( - script_dir=os.path.dirname(__file__) or '.', - injected_os=self.fake_os, - injected_subprocess=None) - self.num_spawn_calls = 0 # A number of calls to spawn. - - def testRunPythonTestSuccess(self): - """Exercises RunTests to handle a Python test success.""" - - self.fake_os.spawn_impl = self.SpawnSuccess - self.assertEqual( - self.test_runner.RunTests( - [(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - []), - 0) - self.assertEqual(self.num_spawn_calls, 1) - - def testRunBinaryTestSuccess(self): - """Exercises RunTests to handle a binary test success.""" - - self.fake_os.spawn_impl = self.SpawnSuccess - self.assertEqual( - self.test_runner.RunTests( - [], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]), - 0) - self.assertEqual(self.num_spawn_calls, 1) - - def testRunPythonTestFauilure(self): - """Exercises RunTests to handle a Python test failure.""" - - self.fake_os.spawn_impl = self.SpawnFailure - self.assertEqual( - self.test_runner.RunTests( - [(GTEST_DBG_DIR, 'test/gtest_color_test.py')], - []), - 1) - self.assertEqual(self.num_spawn_calls, 1) - - def testRunBinaryTestFailure(self): - """Exercises RunTests to handle a binary test failure.""" - - self.fake_os.spawn_impl = self.SpawnFailure - self.assertEqual( - self.test_runner.RunTests( - [], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]), - 1) - self.assertEqual(self.num_spawn_calls, 1) - - def testCombinedTestSuccess(self): - """Exercises RunTests to handle a success of both Python and binary test.""" - - self.fake_os.spawn_impl = self.SpawnSuccess - self.assertEqual( - self.test_runner.RunTests( - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]), - 0) - self.assertEqual(self.num_spawn_calls, 2) - - def testCombinedTestSuccessAndFailure(self): - """Exercises RunTests to handle a success of both Python and binary test.""" - - def SpawnImpl(executable, argv): - self.num_spawn_calls += 1 - # Simulates failure of a Python test and success of a binary test. - if '.py' in executable or '.py' in argv[0]: - return 1 - else: - return 0 - - self.fake_os.spawn_impl = SpawnImpl - self.assertEqual( - self.test_runner.RunTests( - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')], - [(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]), - 0) - self.assertEqual(self.num_spawn_calls, 2) - - -class ParseArgsTest(unittest.TestCase): - """Exercises ParseArgs.""" - - def testNoOptions(self): - options, args = run_tests_util.ParseArgs('gtest', argv=['script.py']) - self.assertEqual(args, ['script.py']) - self.assert_(options.configurations is None) - self.assertFalse(options.built_configurations) - - def testOptionC(self): - options, args = run_tests_util.ParseArgs( - 'gtest', argv=['script.py', '-c', 'dbg']) - self.assertEqual(args, ['script.py']) - self.assertEqual(options.configurations, 'dbg') - self.assertFalse(options.built_configurations) - - def testOptionA(self): - options, args = run_tests_util.ParseArgs('gtest', argv=['script.py', '-a']) - self.assertEqual(args, ['script.py']) - self.assertEqual(options.configurations, 'all') - self.assertFalse(options.built_configurations) - - def testOptionB(self): - options, args = run_tests_util.ParseArgs('gtest', argv=['script.py', '-b']) - self.assertEqual(args, ['script.py']) - self.assert_(options.configurations is None) - self.assertTrue(options.built_configurations) - - def testOptionCAndOptionB(self): - options, args = run_tests_util.ParseArgs( - 'gtest', argv=['script.py', '-c', 'dbg', '-b']) - self.assertEqual(args, ['script.py']) - self.assertEqual(options.configurations, 'dbg') - self.assertTrue(options.built_configurations) - - def testOptionH(self): - help_called = [False] - - # Suppresses lint warning on unused arguments. These arguments are - # required by optparse, even though they are unused. - # pylint: disable-msg=W0613 - def VerifyHelp(option, opt, value, parser): - help_called[0] = True - - # Verifies that -h causes the help callback to be called. - help_called[0] = False - _, args = run_tests_util.ParseArgs( - 'gtest', argv=['script.py', '-h'], help_callback=VerifyHelp) - self.assertEqual(args, ['script.py']) - self.assertTrue(help_called[0]) - - # Verifies that --help causes the help callback to be called. - help_called[0] = False - _, args = run_tests_util.ParseArgs( - 'gtest', argv=['script.py', '--help'], help_callback=VerifyHelp) - self.assertEqual(args, ['script.py']) - self.assertTrue(help_called[0]) - - -if __name__ == '__main__': - unittest.main() diff --git a/testing/gtest/xcode/Samples/FrameworkSample/widget_test.cc b/testing/gtest/xcode/Samples/FrameworkSample/widget_test.cc index 61c0d2f..8725994 100644 --- a/testing/gtest/xcode/Samples/FrameworkSample/widget_test.cc +++ b/testing/gtest/xcode/Samples/FrameworkSample/widget_test.cc @@ -36,7 +36,7 @@ // This is a simple test file for the Widget class in the Widget.framework #include <string> -#include <gtest/gtest.h> +#include "gtest/gtest.h" #include <Widget/widget.h> diff --git a/testing/gtest_mac_unittest.mm b/testing/gtest_mac_unittest.mm index 552beee..c5bc47f 100644 --- a/testing/gtest_mac_unittest.mm +++ b/testing/gtest_mac_unittest.mm @@ -10,12 +10,12 @@ #import <Foundation/Foundation.h> -#include "base/scoped_nsautorelease_pool.h" +#include "base/mac/scoped_nsautorelease_pool.h" #include "testing/gtest/include/gtest/internal/gtest-port.h" #include "testing/gtest/include/gtest/gtest.h" TEST(GTestMac, ExpectNSEQ) { - base::ScopedNSAutoreleasePool pool; + base::mac::ScopedNSAutoreleasePool pool; EXPECT_NSEQ(@"a", @"a"); @@ -26,7 +26,7 @@ TEST(GTestMac, ExpectNSEQ) { } TEST(GTestMac, AssertNSEQ) { - base::ScopedNSAutoreleasePool pool; + base::mac::ScopedNSAutoreleasePool pool; NSNumber* n1 = [NSNumber numberWithInt:42]; NSNumber* n2 = [NSNumber numberWithInt:42]; @@ -35,13 +35,13 @@ TEST(GTestMac, AssertNSEQ) { } TEST(GTestMac, ExpectNSNE) { - base::ScopedNSAutoreleasePool pool; + base::mac::ScopedNSAutoreleasePool pool; EXPECT_NSNE([NSNumber numberWithInt:2], [NSNumber numberWithInt:42]); } TEST(GTestMac, AssertNSNE) { - base::ScopedNSAutoreleasePool pool; + base::mac::ScopedNSAutoreleasePool pool; ASSERT_NSNE(@"a", @"b"); } |